od2961 commited on
Commit
93f2b5e
·
verified ·
1 Parent(s): 796c893

Release frozen ModeBench Levels 1, 2 and 3 with verified splits and executable evaluation

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. CONTENT_SHA256.json +1376 -0
  2. EVALUATION.md +28 -0
  3. LICENSE_PROVENANCE.md +17 -0
  4. LOADER_VALIDATION.json +19 -0
  5. MANIFEST.json +0 -0
  6. PROMPTS.md +9 -0
  7. README.md +192 -0
  8. SPLITS.md +46 -0
  9. VALIDATION.json +396 -0
  10. code/oat_drgrpo/__init__.py +1 -0
  11. code/oat_drgrpo/ant_maze_worker_v10.py +207 -0
  12. code/oat_drgrpo/ant_maze_worker_v11.py +91 -0
  13. code/oat_drgrpo/ant_maze_worker_v12.py +248 -0
  14. code/oat_drgrpo/ant_maze_worker_v5.py +170 -0
  15. code/oat_drgrpo/ant_maze_worker_v8.py +196 -0
  16. code/oat_drgrpo/ant_maze_worker_v9.py +240 -0
  17. code/oat_drgrpo/canonical_actions.py +915 -0
  18. code/oat_drgrpo/math_grader.py +2141 -0
  19. code/oat_drgrpo/math_route.py +458 -0
  20. code/oat_drgrpo/mathir.py +906 -0
  21. code/oat_drgrpo/maze_modebench.py +517 -0
  22. code/oat_drgrpo/maze_modebench_process.py +168 -0
  23. code/oat_drgrpo/maze_modebench_worker.py +179 -0
  24. code/oat_drgrpo/maze_runtime_identity.py +87 -0
  25. code/oat_drgrpo/modebench_guided.py +85 -0
  26. code/oat_drgrpo/pantry_plan.py +370 -0
  27. code/oat_drgrpo/pantry_support_action.py +180 -0
  28. code/oat_drgrpo/python_modebench.py +238 -0
  29. code/oat_drgrpo/python_modebench_process.py +135 -0
  30. code/oat_drgrpo/python_modebench_worker.py +43 -0
  31. code/oat_drgrpo/templates.py +492 -0
  32. data/level1_countdown/eval.parquet +3 -0
  33. data/level1_countdown/train.parquet +3 -0
  34. data/level1_graph_coloring/eval.parquet +3 -0
  35. data/level1_graph_coloring/train.parquet +3 -0
  36. data/level1_graph_coloring_unique_answer/eval.parquet +3 -0
  37. data/level1_mathir/eval.parquet +3 -0
  38. data/level1_mathir/train.parquet +3 -0
  39. data/level1_pantry_plan/dev.parquet +3 -0
  40. data/level1_pantry_plan/eval.parquet +3 -0
  41. data/level1_pantry_plan/train.parquet +3 -0
  42. data/level1_python_factors/eval.parquet +3 -0
  43. data/level1_python_factors/train.parquet +3 -0
  44. data/level2_countdown/dev.parquet +3 -0
  45. data/level2_countdown/eval.parquet +3 -0
  46. data/level2_countdown/train.parquet +3 -0
  47. data/level2_graph_coloring/dev.parquet +3 -0
  48. data/level2_graph_coloring/eval.parquet +3 -0
  49. data/level2_graph_coloring/train.parquet +3 -0
  50. data/level2_mathir/dev.parquet +3 -0
CONTENT_SHA256.json ADDED
@@ -0,0 +1,1376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "files": [
3
+ {
4
+ "bytes": 2919,
5
+ "git_blob_sha1": "ac47b1381dfd276db6f7ae76c3fb85ca4abd7f38",
6
+ "path_in_repo": "EVALUATION.md",
7
+ "sha256": "22857d29101323623e3d8ba23e9ea5efb530706e02c62daf163ff924ddeb4d75"
8
+ },
9
+ {
10
+ "bytes": 778,
11
+ "git_blob_sha1": "09062826b28ccae4af267ea8f6dda72c4e3e1bd5",
12
+ "path_in_repo": "LICENSE_PROVENANCE.md",
13
+ "sha256": "b7b05e3788472a530d7b3528789c41c524c575004cf4e258dd4438a91ab3196d"
14
+ },
15
+ {
16
+ "bytes": 866,
17
+ "git_blob_sha1": "719fe37db1574d8e8a3389c5961c9b37b283d7a1",
18
+ "path_in_repo": "LOADER_VALIDATION.json",
19
+ "sha256": "71ef5258c2c1e25e8e681b7f8272134715cecfcd434182c8d14bdf52ee2b9d10"
20
+ },
21
+ {
22
+ "bytes": 280422,
23
+ "git_blob_sha1": "e6561ee03d20b803b9cb2a73a618aa9cc7796707",
24
+ "path_in_repo": "MANIFEST.json",
25
+ "sha256": "858f23b93bbc555a69f080dff59cd1f4ef62f05133e1dc3e616ad734e56f9a07"
26
+ },
27
+ {
28
+ "bytes": 1502,
29
+ "git_blob_sha1": "89920ef9e56164214c0f211d7e9ddcc70fb488fc",
30
+ "path_in_repo": "PROMPTS.md",
31
+ "sha256": "564623a9953728e2bff9df8a7fb0e07ce433d6c375d9d1a999a322118b062959"
32
+ },
33
+ {
34
+ "bytes": 9355,
35
+ "git_blob_sha1": "f1008a760e8a2c480105449ad2cd51f99dff4777",
36
+ "path_in_repo": "README.md",
37
+ "sha256": "97aba5563179bfbaffa4027eb12289c8093b3ec6574495ae423d24992dfa150d"
38
+ },
39
+ {
40
+ "bytes": 2430,
41
+ "git_blob_sha1": "6e4c10f02da9f24952462b4f2e909035847af2f2",
42
+ "path_in_repo": "SPLITS.md",
43
+ "sha256": "e8dfe2a3026382ff6c7d3a84b399824c1a36d180763aa4f99e6bed2b904c6563"
44
+ },
45
+ {
46
+ "bytes": 12448,
47
+ "git_blob_sha1": "2164c02230f3cdd416efec76c8fbebb6c5d2c79a",
48
+ "path_in_repo": "VALIDATION.json",
49
+ "sha256": "eb6d6fe6cbdb41d5963c17da012c16d03b7ac6a34cfeeaeb303c6f6b04841927"
50
+ },
51
+ {
52
+ "bytes": 71,
53
+ "git_blob_sha1": "13437e8afc6380b580b0dc8ed00c20798ad54c1c",
54
+ "path_in_repo": "code/oat_drgrpo/__init__.py",
55
+ "sha256": "3345b113aadcb190054dba65691d8c2aa51194979c5ead9d3aa87dabd27f8238"
56
+ },
57
+ {
58
+ "bytes": 8188,
59
+ "git_blob_sha1": "b6c40463ecd2992c71d2547d5f03906f64541b39",
60
+ "path_in_repo": "code/oat_drgrpo/ant_maze_worker_v10.py",
61
+ "sha256": "bebbff349fa31024ac87f1dd856050e7ef56c346babea735313fd36a5fe03ec6"
62
+ },
63
+ {
64
+ "bytes": 4163,
65
+ "git_blob_sha1": "b703dbcff59ca32229dab9285ce15598136f0c08",
66
+ "path_in_repo": "code/oat_drgrpo/ant_maze_worker_v11.py",
67
+ "sha256": "b7c2540239b1afb3454d83c7d5f7634bd1d994692e2fe6710ccdde63cc441e14"
68
+ },
69
+ {
70
+ "bytes": 9066,
71
+ "git_blob_sha1": "dcf98c2fed9dc9120a7bcd1b82dd428bf6aac9dc",
72
+ "path_in_repo": "code/oat_drgrpo/ant_maze_worker_v12.py",
73
+ "sha256": "84b4d11157951782cb253259ac5a8301491d020f716a84debcdb825bb902bb8b"
74
+ },
75
+ {
76
+ "bytes": 6087,
77
+ "git_blob_sha1": "129e24b2a95bdf64247b78d56d49544f0cee19f0",
78
+ "path_in_repo": "code/oat_drgrpo/ant_maze_worker_v5.py",
79
+ "sha256": "faa55c2035b26ba8eb20685a92535430505334e90569adaf3d803955a5680ea7"
80
+ },
81
+ {
82
+ "bytes": 6876,
83
+ "git_blob_sha1": "d7e707168626baf68a047835a9a3b5b8f37d089b",
84
+ "path_in_repo": "code/oat_drgrpo/ant_maze_worker_v8.py",
85
+ "sha256": "7f9ab36749115d062f0f49d833355fef9240a94555bdf5274bf7f4da70e573f8"
86
+ },
87
+ {
88
+ "bytes": 8847,
89
+ "git_blob_sha1": "ad2207840d75de00b39eda0e6435832f21cc447c",
90
+ "path_in_repo": "code/oat_drgrpo/ant_maze_worker_v9.py",
91
+ "sha256": "1a811aab3b61dd18c5de770086f090b67db01017bf08f4431a775ec497b1b0cc"
92
+ },
93
+ {
94
+ "bytes": 37065,
95
+ "git_blob_sha1": "527d0360b3de59fe9b5e18c244e167726118578d",
96
+ "path_in_repo": "code/oat_drgrpo/canonical_actions.py",
97
+ "sha256": "0fcbc0409ec89ce6dced35f1e3b5ae787076dfcc5aafdfa4194fee52c1aa187f"
98
+ },
99
+ {
100
+ "bytes": 69515,
101
+ "git_blob_sha1": "a8c9de23e450ab68e7ecb5c487fea2e3eaf40fca",
102
+ "path_in_repo": "code/oat_drgrpo/math_grader.py",
103
+ "sha256": "5bc8a2382ab30d9ccb2dfa4a9cbfb78be28187e1b5049063814cc262b5bac255"
104
+ },
105
+ {
106
+ "bytes": 17571,
107
+ "git_blob_sha1": "934d0b61350b9d75a780ab045ae2fe08e41e3bf3",
108
+ "path_in_repo": "code/oat_drgrpo/math_route.py",
109
+ "sha256": "0c430a9e8f4c215665b673d4fbca8e5e4db3dd050814fe30a2a07ac7750317cc"
110
+ },
111
+ {
112
+ "bytes": 31858,
113
+ "git_blob_sha1": "c8ae33d19bcc57f45ae54419f18df65794fb2cd6",
114
+ "path_in_repo": "code/oat_drgrpo/mathir.py",
115
+ "sha256": "1f35d72b68033e1a272305034ca15ab3a53a74edd93a838de831262c75b5825a"
116
+ },
117
+ {
118
+ "bytes": 20894,
119
+ "git_blob_sha1": "1d0b73feb7aca3393ef72cd0c8efd86e17e53def",
120
+ "path_in_repo": "code/oat_drgrpo/maze_modebench.py",
121
+ "sha256": "ee1557c7e229055d9b1235c53fe1ea0160aa9f2a69cc330a6f6ef7b8d9439b62"
122
+ },
123
+ {
124
+ "bytes": 5746,
125
+ "git_blob_sha1": "761c637e121198e41e9bc33bbb1aaf81f523d136",
126
+ "path_in_repo": "code/oat_drgrpo/maze_modebench_process.py",
127
+ "sha256": "c6e6b9093e9cf9bc537151313dfd9c7d650dcbbe254a4c1ef61d2c5b20b6c3d6"
128
+ },
129
+ {
130
+ "bytes": 6948,
131
+ "git_blob_sha1": "3ca827edab0e61cf99553fa5adfe4e610a75f1b7",
132
+ "path_in_repo": "code/oat_drgrpo/maze_modebench_worker.py",
133
+ "sha256": "2ee1fa9b1bbde5509c34eb42c2806bc215fba0bddd8d6ca9ce9e67648170f3a2"
134
+ },
135
+ {
136
+ "bytes": 2664,
137
+ "git_blob_sha1": "be2625c3af1d2745bb09afd5a82a7dcba522f4bd",
138
+ "path_in_repo": "code/oat_drgrpo/maze_runtime_identity.py",
139
+ "sha256": "5f3799be54aa693d957a7a0e23dd0f014e8c84715756e68b1263484289842112"
140
+ },
141
+ {
142
+ "bytes": 3146,
143
+ "git_blob_sha1": "913ae043739916add64523d5b524e4539469c690",
144
+ "path_in_repo": "code/oat_drgrpo/modebench_guided.py",
145
+ "sha256": "b1e744d18e186ab138469059a7557147a436c142eebf354b94138c0f6aa9534c"
146
+ },
147
+ {
148
+ "bytes": 13574,
149
+ "git_blob_sha1": "886b4a79de5cf0e05ab7a7482742c6b7e97c79d3",
150
+ "path_in_repo": "code/oat_drgrpo/pantry_plan.py",
151
+ "sha256": "dd246a0510fc5d2964794b6d228ff30cc682200cdc0073540bf45e3273666712"
152
+ },
153
+ {
154
+ "bytes": 6411,
155
+ "git_blob_sha1": "7326a50ad0f6142ee9d2f5fb70952ff46a990678",
156
+ "path_in_repo": "code/oat_drgrpo/pantry_support_action.py",
157
+ "sha256": "78c555485b1975fd17cc8ad30886f3665b41a4c6423b14ade9540136db212a6a"
158
+ },
159
+ {
160
+ "bytes": 8552,
161
+ "git_blob_sha1": "05a89956f9e8246b598719fd88bc865f6b9b8f45",
162
+ "path_in_repo": "code/oat_drgrpo/python_modebench.py",
163
+ "sha256": "0fa4a452d5935f3922ef3e2ffeacbc5d9f3ddb8defdcbb31c04050346313c726"
164
+ },
165
+ {
166
+ "bytes": 4570,
167
+ "git_blob_sha1": "8f3f3741ee282225fb6678c8342376a6275acea5",
168
+ "path_in_repo": "code/oat_drgrpo/python_modebench_process.py",
169
+ "sha256": "5b8471171f9ef433d111db19b39dba172482bfcc32e01897cf3382357096680e"
170
+ },
171
+ {
172
+ "bytes": 1200,
173
+ "git_blob_sha1": "738d25f77fabf9570432efccadba7ac4e55a4de6",
174
+ "path_in_repo": "code/oat_drgrpo/python_modebench_worker.py",
175
+ "sha256": "6595e9ea6a1786753734e8ddb03efd4d78ac7f6091e8dc3c6db312eef12db210"
176
+ },
177
+ {
178
+ "bytes": 19110,
179
+ "git_blob_sha1": "3d136b4ce41c9dcd45653db8e474ac6f6e1f9643",
180
+ "path_in_repo": "code/oat_drgrpo/templates.py",
181
+ "sha256": "6af7522ff71e02dbe46867a722288c0681f7136ca8d297b59c3c9a55fd30b123"
182
+ },
183
+ {
184
+ "bytes": 8432,
185
+ "git_blob_sha1": "a401ec339d4f01a15ac95bd5ef78e9455c23a673",
186
+ "path_in_repo": "data/level1_countdown/eval.parquet",
187
+ "sha256": "a1da95c1b5997a0c8d804c8bf7b607817b11bb8c7982b3d04bd4c345da7b9c33"
188
+ },
189
+ {
190
+ "bytes": 13725,
191
+ "git_blob_sha1": "fdeceaa2187186d504b743a86a1eee96768e303d",
192
+ "path_in_repo": "data/level1_countdown/train.parquet",
193
+ "sha256": "00054c212d28ccb103b982cb56de7c381691b91a8ee3af7d984c5e0d57fe74f1"
194
+ },
195
+ {
196
+ "bytes": 13112,
197
+ "git_blob_sha1": "83015c9011e65a5703107f0e08699bf8c5a268c1",
198
+ "path_in_repo": "data/level1_graph_coloring/eval.parquet",
199
+ "sha256": "5c009576b979ac78b9bf73c80790e0048a75f4c27c400569907f096e18a220fb"
200
+ },
201
+ {
202
+ "bytes": 22522,
203
+ "git_blob_sha1": "ab59a3c26fa48dd213ee22612d9a98c73a483e3c",
204
+ "path_in_repo": "data/level1_graph_coloring/train.parquet",
205
+ "sha256": "56266083798c5e86223e7705d3ed2b97d22dc8aba56814402a0c09afc9eddf30"
206
+ },
207
+ {
208
+ "bytes": 13015,
209
+ "git_blob_sha1": "e5d2aaf558802717ddb4aa9466a707244ba3c540",
210
+ "path_in_repo": "data/level1_graph_coloring_unique_answer/eval.parquet",
211
+ "sha256": "759ba48dbcd3fcd4f000449eed1b9e0ea55319dc9677f5150842180ea95893bf"
212
+ },
213
+ {
214
+ "bytes": 20812,
215
+ "git_blob_sha1": "acae2f38e3d448f0aafb70b9549a88d2d3ad8598",
216
+ "path_in_repo": "data/level1_mathir/eval.parquet",
217
+ "sha256": "fc0280c144e5c9c54624303cd508612dbbb3a0ef130dfee9a42fb8f9413e9902"
218
+ },
219
+ {
220
+ "bytes": 37345,
221
+ "git_blob_sha1": "3e8e4a9a352bde694a385000da38c9aafd20ce1e",
222
+ "path_in_repo": "data/level1_mathir/train.parquet",
223
+ "sha256": "aac7f11f814eb85769cd16fe8464d886cef3daade22d3d61de50385de9c0662a"
224
+ },
225
+ {
226
+ "bytes": 36731,
227
+ "git_blob_sha1": "4183df90f133ce99d5fe8bda1f2d8de9e972f727",
228
+ "path_in_repo": "data/level1_pantry_plan/dev.parquet",
229
+ "sha256": "0411b6d32ff14491d14ab5c9edf37a28e8d6fc9ad95ad3afc3f172ba7ec23319"
230
+ },
231
+ {
232
+ "bytes": 48960,
233
+ "git_blob_sha1": "eed241a0c7d6b95569f4dc4be7b56dd4b7e48165",
234
+ "path_in_repo": "data/level1_pantry_plan/eval.parquet",
235
+ "sha256": "2807515694c01108c5b8a616eded485a6ffded07fd1f9eb5fa0155cfeb7c2c34"
236
+ },
237
+ {
238
+ "bytes": 98671,
239
+ "git_blob_sha1": "6da3fc0a1e1df610b190620fba44dac0cf0fa06f",
240
+ "path_in_repo": "data/level1_pantry_plan/train.parquet",
241
+ "sha256": "eced2be5ca3fb8194703e8f9d7cfd5d29a1ee701369be14cd388d2004b80a8a3"
242
+ },
243
+ {
244
+ "bytes": 16281,
245
+ "git_blob_sha1": "cfd9c975bce895b1ac9d8e23fb3804518a30caaa",
246
+ "path_in_repo": "data/level1_python_factors/eval.parquet",
247
+ "sha256": "88a3f35b0f3e8e9b8ec4da5151ca7697afc79894c0507d00c258d4154983cea0"
248
+ },
249
+ {
250
+ "bytes": 31553,
251
+ "git_blob_sha1": "36d5f2b6a3bd731d93e1bb3f78c3b8e5e1ed6f62",
252
+ "path_in_repo": "data/level1_python_factors/train.parquet",
253
+ "sha256": "86e4abc2ff3f2efff47c67aaa3263af2fcb226adefcb8fa52e94ff3c15a94948"
254
+ },
255
+ {
256
+ "bytes": 8674,
257
+ "git_blob_sha1": "cf79ba519180e1c556c039c4c3179c1ec3395a2b",
258
+ "path_in_repo": "data/level2_countdown/dev.parquet",
259
+ "sha256": "2f9451228cfd2a49580d3c93b21f58685a477adf2a40d014f480a8f3cc91ef99"
260
+ },
261
+ {
262
+ "bytes": 8752,
263
+ "git_blob_sha1": "20240aac2147eae6bb47ba61f27fb858ff6f64e3",
264
+ "path_in_repo": "data/level2_countdown/eval.parquet",
265
+ "sha256": "50b90a6197ff1ac83ba0020239bb903bb597c334a27329d3e8703f163cf5d17c"
266
+ },
267
+ {
268
+ "bytes": 14452,
269
+ "git_blob_sha1": "53d155f2a232f9cb548a539f0a76412359b001f2",
270
+ "path_in_repo": "data/level2_countdown/train.parquet",
271
+ "sha256": "bd6a3645bd2e84e90478ddd9f4c4f4f69c28f41a6df7615acb91a9f92374db97"
272
+ },
273
+ {
274
+ "bytes": 13257,
275
+ "git_blob_sha1": "35d98a6485ec63a1fd73c3273e2548c51d60f9dd",
276
+ "path_in_repo": "data/level2_graph_coloring/dev.parquet",
277
+ "sha256": "9d32ed70ff3f002f35dd23b5197e4b06a477b08e4e418bc682675b1e0402ece7"
278
+ },
279
+ {
280
+ "bytes": 13086,
281
+ "git_blob_sha1": "5c2a1fc00d8c430167a3bfa2577ffaa1be6a3c3e",
282
+ "path_in_repo": "data/level2_graph_coloring/eval.parquet",
283
+ "sha256": "63e5f1b8f4b3db950022080c9971cec71c864d369f346f64aa9c303da5b1e33f"
284
+ },
285
+ {
286
+ "bytes": 23261,
287
+ "git_blob_sha1": "97cefe83f9d3e6f0bd5209cb6f8c05edda93968a",
288
+ "path_in_repo": "data/level2_graph_coloring/train.parquet",
289
+ "sha256": "bd250e096ea785d45e76d0de1c7d872ca8822e95181568cb8ae1b69a6b905fd8"
290
+ },
291
+ {
292
+ "bytes": 20318,
293
+ "git_blob_sha1": "958cdc0c99d63d212ca3deea980cbb02198c7715",
294
+ "path_in_repo": "data/level2_mathir/dev.parquet",
295
+ "sha256": "3dbbb10af2589e467ace24420fe67387fb299ba465a1180163a2b62910dd2fd4"
296
+ },
297
+ {
298
+ "bytes": 20588,
299
+ "git_blob_sha1": "8d21abc6a5a99e41b676e9eda5bf142884a8df5c",
300
+ "path_in_repo": "data/level2_mathir/eval.parquet",
301
+ "sha256": "646e8780fdfbad6ec5681fba1583dafc9ac6755200b2cb80f497dab75320819f"
302
+ },
303
+ {
304
+ "bytes": 37680,
305
+ "git_blob_sha1": "953a8006cc94ba05d16a30a96f43c996bd0a31d9",
306
+ "path_in_repo": "data/level2_mathir/train.parquet",
307
+ "sha256": "f32e8223d9335f2460182d21f5b787e3fb895162255d42a6995d5669a0750a54"
308
+ },
309
+ {
310
+ "bytes": 49384,
311
+ "git_blob_sha1": "d63caee7fb6d3dd8e349738b1e4f4baae623bcfe",
312
+ "path_in_repo": "data/level2_pantry_plan/dev.parquet",
313
+ "sha256": "1c33bea8878ea99b007399cdc9de1b69da8053d5f700728b4203f5bef49a7f76"
314
+ },
315
+ {
316
+ "bytes": 48888,
317
+ "git_blob_sha1": "6e0211e6619483c142b6004ea16fb7bf0c0043aa",
318
+ "path_in_repo": "data/level2_pantry_plan/eval.parquet",
319
+ "sha256": "94a1aac4a48bfd21e363433397fcd834bbd39c096551900f63b29dadc960905b"
320
+ },
321
+ {
322
+ "bytes": 96678,
323
+ "git_blob_sha1": "cee4689e5f96bc81b78bcd2d961b76d15e3a735c",
324
+ "path_in_repo": "data/level2_pantry_plan/train.parquet",
325
+ "sha256": "dd531d612bd8addef1f6a4da8f61cbf8c5068a8738b0f0033a310a292c89a9fe"
326
+ },
327
+ {
328
+ "bytes": 16949,
329
+ "git_blob_sha1": "65fa0921e42e8c740ab24e5f343ae21d01a7e0c6",
330
+ "path_in_repo": "data/level2_python_factors/dev.parquet",
331
+ "sha256": "70d3c17097338e96a5284dae841d0461173ad7c019c33b3c8dbbff990a70ccd3"
332
+ },
333
+ {
334
+ "bytes": 17020,
335
+ "git_blob_sha1": "95efdd0bf554b50a6e02e451cf84e8341285117c",
336
+ "path_in_repo": "data/level2_python_factors/eval.parquet",
337
+ "sha256": "3b6f96ca863cb4a5be793fd4e5e12337db48622faf3f70782553c37f64675a42"
338
+ },
339
+ {
340
+ "bytes": 33339,
341
+ "git_blob_sha1": "468ac2e9880eddaf0297f39d7f2e5f588358b84c",
342
+ "path_in_repo": "data/level2_python_factors/train.parquet",
343
+ "sha256": "3662ed77c4c9ab7e3b2fae14217b86b5f0939a27326a7edd139bb789bd84c5db"
344
+ },
345
+ {
346
+ "bytes": 15097,
347
+ "git_blob_sha1": "f89aa6748044731d032c00bf3cae7bd5ef4d866f",
348
+ "path_in_repo": "data/level3_countdown/dev.parquet",
349
+ "sha256": "c88bea04f663a199a26371a03f5b36c2a7d0ff70031286b308a51264984a35ae"
350
+ },
351
+ {
352
+ "bytes": 14941,
353
+ "git_blob_sha1": "53831ca966031f6397918813c682ea797fce3828",
354
+ "path_in_repo": "data/level3_countdown/eval.parquet",
355
+ "sha256": "b8c8540758fb32b8d49c0bc0f1c4337b6f29017f9f9fdcb618365d232a3e8c9a"
356
+ },
357
+ {
358
+ "bytes": 23693,
359
+ "git_blob_sha1": "a703c78d510255e92fed871ea2f52a7d3ecafecf",
360
+ "path_in_repo": "data/level3_countdown/train.parquet",
361
+ "sha256": "6003fd18559b3a1caaaed1a036d74badd61a4774346b480e49a00e28acbe7f02"
362
+ },
363
+ {
364
+ "bytes": 15287,
365
+ "git_blob_sha1": "13f5f88123cbf2a437231c414db672a6795f5558",
366
+ "path_in_repo": "data/level3_graph_coloring/dev.parquet",
367
+ "sha256": "a9a33bc4666a34184bea8bd3cb311fa00346811852ff466547d399327f93a9d2"
368
+ },
369
+ {
370
+ "bytes": 15173,
371
+ "git_blob_sha1": "7c9a96184999e44a8271887274e6e34fe51d2a08",
372
+ "path_in_repo": "data/level3_graph_coloring/eval.parquet",
373
+ "sha256": "dd4bc7dedf28e5d153c80046abd3f8e8a80a6adcdd11b80aa05dde3cd5378bc7"
374
+ },
375
+ {
376
+ "bytes": 23853,
377
+ "git_blob_sha1": "f05ab1bdf30cd5c7ee427ea25e7d1c8d4723eec3",
378
+ "path_in_repo": "data/level3_graph_coloring/train.parquet",
379
+ "sha256": "0f6d9e8a5196a9536a39b56583272584cb2722b8317466cc4cd4c52767edeed9"
380
+ },
381
+ {
382
+ "bytes": 24048,
383
+ "git_blob_sha1": "5da9121267611637c7ceaa62bf06ede3faaf26f7",
384
+ "path_in_repo": "data/level3_mathir/dev.parquet",
385
+ "sha256": "9bb2d32ceda8ef0fde17e3ce4ee934f5f2142aab871bd79755a96b563ca93e39"
386
+ },
387
+ {
388
+ "bytes": 24589,
389
+ "git_blob_sha1": "d416291875da5b3d0729f4b32d5f7b07254aa146",
390
+ "path_in_repo": "data/level3_mathir/eval.parquet",
391
+ "sha256": "9903ce6c9a612887787db2e803519fa715214e6733e2c684e85d1735c770d89a"
392
+ },
393
+ {
394
+ "bytes": 43948,
395
+ "git_blob_sha1": "505b77b364ca13b32af324353e0c19d4431a29b4",
396
+ "path_in_repo": "data/level3_mathir/train.parquet",
397
+ "sha256": "e07fe596001de4614d40bd73e5c2898ee32357e87c4c09863568015461f3c3fc"
398
+ },
399
+ {
400
+ "bytes": 59675,
401
+ "git_blob_sha1": "f443672f8041777b7d3b2063592c65899154c012",
402
+ "path_in_repo": "data/level3_pantry_plan/dev.parquet",
403
+ "sha256": "4e508afec73597913468094dc7aeac59735b3d0767b1700bddf07bd7e7e643e8"
404
+ },
405
+ {
406
+ "bytes": 59289,
407
+ "git_blob_sha1": "37a3a052529dd4cc66146e2bb2a13ee1badbe9eb",
408
+ "path_in_repo": "data/level3_pantry_plan/eval.parquet",
409
+ "sha256": "63840b51ead4a7799c1376e49739322f2a085beaef981389a5f077ff058757a7"
410
+ },
411
+ {
412
+ "bytes": 121812,
413
+ "git_blob_sha1": "03470cd851bd0e5cb80dbffc3ac2a2a3acf43150",
414
+ "path_in_repo": "data/level3_pantry_plan/train.parquet",
415
+ "sha256": "e97d3cda0e229934b32cd87a5a11627f124167918502ede632b7d6e3be56b255"
416
+ },
417
+ {
418
+ "bytes": 24170,
419
+ "git_blob_sha1": "a4cdf607f4a0dc6b502eae70e7b2da3de503da1a",
420
+ "path_in_repo": "data/level3_python_factors/dev.parquet",
421
+ "sha256": "1d72c49e9d43afa00b1b4c2f3b75bdbc9b753e4334d346b5283b7dadcdbdffe3"
422
+ },
423
+ {
424
+ "bytes": 24013,
425
+ "git_blob_sha1": "a512741389bb3d987e5c936c0ff5dbfd157c883a",
426
+ "path_in_repo": "data/level3_python_factors/eval.parquet",
427
+ "sha256": "77d32ab09bb2125206b5fe291251b74219130a1a89d79d2b2d93700305ee0f21"
428
+ },
429
+ {
430
+ "bytes": 41093,
431
+ "git_blob_sha1": "60efbfa212cf7076ddc4b1f8ba838f7a10336ef8",
432
+ "path_in_repo": "data/level3_python_factors/train.parquet",
433
+ "sha256": "cf5ee666dd126716d0a0cf68c9a74512bbb222ca68ad8839dcb276fab988e358"
434
+ },
435
+ {
436
+ "bytes": 11357,
437
+ "git_blob_sha1": "261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64",
438
+ "path_in_repo": "licenses/source_repository_APACHE_2.0.txt",
439
+ "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4"
440
+ },
441
+ {
442
+ "bytes": 1261933,
443
+ "git_blob_sha1": "6269793f92edd108cbab8bc7f994eae80028d269",
444
+ "path_in_repo": "provenance/confirmation_report.json",
445
+ "sha256": "b685cfa6b20d6f9b714239546a7946947af95af3d4e83ed8ab1b7ad96c453195"
446
+ },
447
+ {
448
+ "bytes": 3860,
449
+ "git_blob_sha1": "1cb5aaaef42fe9bf623444fb0e8d678870802242",
450
+ "path_in_repo": "provenance/e119_level2_qwen05b_factorial_20260901.md",
451
+ "sha256": "76c338cd34e92aae8310403fc2e26786b613280bec6a66dbf049acf24d321225"
452
+ },
453
+ {
454
+ "bytes": 9094,
455
+ "git_blob_sha1": "2d401ed9328f62690878a1fc47ad4ba852b1f5d6",
456
+ "path_in_repo": "provenance/e122_level3_factorial_20260909.md",
457
+ "sha256": "fd094df005e8df2110c33ba0d69e2bcbcd5e83b45ad86bc4271ac444b4f18bdb"
458
+ },
459
+ {
460
+ "bytes": 48308,
461
+ "git_blob_sha1": "5971aafb29ce14ec3ae59331c5772ea52ecd2b7f",
462
+ "path_in_repo": "provenance/pantry_ingredient_source.json",
463
+ "sha256": "ce86c69b5b36c047b256254820282d54ab45f0137d26295f0842646de3578226"
464
+ },
465
+ {
466
+ "bytes": 5708,
467
+ "git_blob_sha1": "89910c7e049b6d80a276bf3eaa98c9c125a18969",
468
+ "path_in_repo": "provenance/source_code/ops/check_paper_domain_prompts.py",
469
+ "sha256": "53a6b77703836ca9f92cd58cc6a9efc711e3c8a5466a4b6ab7d1b6214ccdfbff"
470
+ },
471
+ {
472
+ "bytes": 14400,
473
+ "git_blob_sha1": "6b5b4ddffb6a074f08ab9ed5ae824aaebd3aaf10",
474
+ "path_in_repo": "provenance/source_code/ops/evaluate_modebench_level2_viability.py",
475
+ "sha256": "f6c9de12ff86f079cbf4cdd8db37c2ee2a9a8ff069c84fa149dcb43da4b67e2f"
476
+ },
477
+ {
478
+ "bytes": 20188,
479
+ "git_blob_sha1": "32dee56c3d4b4163f7062eb9b991ba63da656141",
480
+ "path_in_repo": "provenance/source_code/ops/evaluate_modebench_level3.py",
481
+ "sha256": "df43446b3a748db7dd5b055b3a36bd7ad5db6e3fd2966960fee89669e03cf324"
482
+ },
483
+ {
484
+ "bytes": 20354,
485
+ "git_blob_sha1": "d4c76773cc52d97f4c4a98ae696a5dac7a113ef4",
486
+ "path_in_repo": "provenance/source_code/ops/evaluate_modebench_level3_independent.py",
487
+ "sha256": "faf980b6594a065fe5a475058a43862821be96dd7f19cfae00259684623b4ab7"
488
+ },
489
+ {
490
+ "bytes": 17616,
491
+ "git_blob_sha1": "dd7d6e4ba3152fd37bef173f5b0770c47d3a307d",
492
+ "path_in_repo": "provenance/source_code/ops/exp_scaling/materialize_modebench_harder_v2.py",
493
+ "sha256": "056ceee55fbff1a7288473c5f36c941de3de96908e93bb18b65668299473a676"
494
+ },
495
+ {
496
+ "bytes": 6236,
497
+ "git_blob_sha1": "1e0fa766b1eff11a81d94878aa7b98327ac095da",
498
+ "path_in_repo": "provenance/source_code/ops/exp_scaling/materialize_modebench_level3.py",
499
+ "sha256": "0a38e3695cd3b2c8e25367e50a16d5a0f98bcd48d1f52af344c8322b14c19d1b"
500
+ },
501
+ {
502
+ "bytes": 21494,
503
+ "git_blob_sha1": "3dca49050d4bcb45cd0cafcb199b2ed0330a51cf",
504
+ "path_in_repo": "provenance/source_code/ops/exp_scaling/modebench_level3_v3_common.py",
505
+ "sha256": "1cb2a47b7b1751da8229be7940bd932816daea09a56bae4b6d62cb2bef1e9522"
506
+ },
507
+ {
508
+ "bytes": 2492,
509
+ "git_blob_sha1": "afe1df64fbfae0d1c6e1c87941cc7c487f845db2",
510
+ "path_in_repo": "provenance/source_code/ops/modebench_independent_seeds.py",
511
+ "sha256": "a92a0f5441b5a22d6c9b5ccb72edf30fb22404acfc30b15efbd8ea4ee9104d92"
512
+ },
513
+ {
514
+ "bytes": 4703,
515
+ "git_blob_sha1": "7db25a627511310758bc0f08d360f9ae5f6bda54",
516
+ "path_in_repo": "provenance/source_code/tests/test_modebench_hf_release.py",
517
+ "sha256": "c944a8bcbbc171fbd4750c2a47fe3301df57388e5f6dbb04b4c114ed8d3d02c1"
518
+ },
519
+ {
520
+ "bytes": 28,
521
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
522
+ "path_in_repo": "provenance/source_data/exact_countdown_easy3_probe/eval/dataset_dict.json",
523
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
524
+ },
525
+ {
526
+ "bytes": 481,
527
+ "git_blob_sha1": "5db33a5d461fde3365428ea1e1ebdee57e5e6d21",
528
+ "path_in_repo": "provenance/source_data/exact_countdown_easy3_probe/eval/multi_answer/dataset_info.json",
529
+ "sha256": "937ede6f568e39159d9ec7906776651b4a8ef82983246f2a8bd6648398a268a6"
530
+ },
531
+ {
532
+ "bytes": 247,
533
+ "git_blob_sha1": "76c9388cc9deea0b527bcb3431734151604101d5",
534
+ "path_in_repo": "provenance/source_data/exact_countdown_easy3_probe/eval/multi_answer/state.json",
535
+ "sha256": "ae88b13d1684218849d4c235002b8f7f770599b34be92230195f616e3a25fde6"
536
+ },
537
+ {
538
+ "bytes": 21,
539
+ "git_blob_sha1": "40d5c04b431649b5c469de1fd03044ba97b6fded",
540
+ "path_in_repo": "provenance/source_data/exact_countdown_easy3_probe/train/dataset_dict.json",
541
+ "sha256": "c172eebfc28c1400d6be4338ce7d00191507ffb4ae64c315f039585c894df5b7"
542
+ },
543
+ {
544
+ "bytes": 481,
545
+ "git_blob_sha1": "5db33a5d461fde3365428ea1e1ebdee57e5e6d21",
546
+ "path_in_repo": "provenance/source_data/exact_countdown_easy3_probe/train/train/dataset_info.json",
547
+ "sha256": "937ede6f568e39159d9ec7906776651b4a8ef82983246f2a8bd6648398a268a6"
548
+ },
549
+ {
550
+ "bytes": 247,
551
+ "git_blob_sha1": "67858f3ed56a9481782b3ef9a00df41c3071dec2",
552
+ "path_in_repo": "provenance/source_data/exact_countdown_easy3_probe/train/train/state.json",
553
+ "sha256": "902d4a51a4dc5bd0b3c3984ae68bb0a29e7ac4ba95199d555d04e01d9121f299"
554
+ },
555
+ {
556
+ "bytes": 45,
557
+ "git_blob_sha1": "aa7c0f1e0ccb96d330850535916e18ee4bc36082",
558
+ "path_in_repo": "provenance/source_data/graph_coloring_modebench_v2/eval/dataset_dict.json",
559
+ "sha256": "81c8ff31a03c8612cebfb1c48127291d14558c7227ca25542d7b2bb226ed988c"
560
+ },
561
+ {
562
+ "bytes": 481,
563
+ "git_blob_sha1": "5db33a5d461fde3365428ea1e1ebdee57e5e6d21",
564
+ "path_in_repo": "provenance/source_data/graph_coloring_modebench_v2/eval/multi_answer/dataset_info.json",
565
+ "sha256": "937ede6f568e39159d9ec7906776651b4a8ef82983246f2a8bd6648398a268a6"
566
+ },
567
+ {
568
+ "bytes": 247,
569
+ "git_blob_sha1": "16d25a6197aea9df9d43bf5de62cb222a701ecb1",
570
+ "path_in_repo": "provenance/source_data/graph_coloring_modebench_v2/eval/multi_answer/state.json",
571
+ "sha256": "8008d939336a53476cdf6715afb460e831036b36efee3c61c065f0bc23904718"
572
+ },
573
+ {
574
+ "bytes": 481,
575
+ "git_blob_sha1": "5db33a5d461fde3365428ea1e1ebdee57e5e6d21",
576
+ "path_in_repo": "provenance/source_data/graph_coloring_modebench_v2/eval/unique_answer/dataset_info.json",
577
+ "sha256": "937ede6f568e39159d9ec7906776651b4a8ef82983246f2a8bd6648398a268a6"
578
+ },
579
+ {
580
+ "bytes": 247,
581
+ "git_blob_sha1": "b56860156dbefd057cfc78aed7afd93ddf28dd5e",
582
+ "path_in_repo": "provenance/source_data/graph_coloring_modebench_v2/eval/unique_answer/state.json",
583
+ "sha256": "79c6a7ccd0fbd2c2a98d14199217aebee651d320abe0133d5b147da842cdf5de"
584
+ },
585
+ {
586
+ "bytes": 1085,
587
+ "git_blob_sha1": "9bcc0f6dcf87f0a9a7ed1f5ead8e994960873784",
588
+ "path_in_repo": "provenance/source_data/graph_coloring_modebench_v2/identity.json",
589
+ "sha256": "6dfa0c5e3339feb2cd6199a808fd9d30a16ec181c89605a34c0b8ce4c12bf85a"
590
+ },
591
+ {
592
+ "bytes": 21,
593
+ "git_blob_sha1": "40d5c04b431649b5c469de1fd03044ba97b6fded",
594
+ "path_in_repo": "provenance/source_data/graph_coloring_modebench_v2/train/dataset_dict.json",
595
+ "sha256": "c172eebfc28c1400d6be4338ce7d00191507ffb4ae64c315f039585c894df5b7"
596
+ },
597
+ {
598
+ "bytes": 481,
599
+ "git_blob_sha1": "5db33a5d461fde3365428ea1e1ebdee57e5e6d21",
600
+ "path_in_repo": "provenance/source_data/graph_coloring_modebench_v2/train/train/dataset_info.json",
601
+ "sha256": "937ede6f568e39159d9ec7906776651b4a8ef82983246f2a8bd6648398a268a6"
602
+ },
603
+ {
604
+ "bytes": 247,
605
+ "git_blob_sha1": "3fe22da20625dff007474a2c75055c3ce71bdaf6",
606
+ "path_in_repo": "provenance/source_data/graph_coloring_modebench_v2/train/train/state.json",
607
+ "sha256": "cac8943c3972749dc2678275ec49afc6b6b4e50f4c33fbb6b00e15813a49f6f9"
608
+ },
609
+ {
610
+ "bytes": 28,
611
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
612
+ "path_in_repo": "provenance/source_data/mathir_action_menu_v1/eval/dataset_dict.json",
613
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
614
+ },
615
+ {
616
+ "bytes": 559,
617
+ "git_blob_sha1": "c15fdbab4b5c6018a0638960fc92f250777ce2d9",
618
+ "path_in_repo": "provenance/source_data/mathir_action_menu_v1/eval/multi_answer/dataset_info.json",
619
+ "sha256": "524a7bcf8a0a2067c688f41612fbfce06a30c9ac3e3ef1472ef4b057609ccc27"
620
+ },
621
+ {
622
+ "bytes": 247,
623
+ "git_blob_sha1": "1281fdfaf4f2046d8ad8adefb59fb1f53b53ecc7",
624
+ "path_in_repo": "provenance/source_data/mathir_action_menu_v1/eval/multi_answer/state.json",
625
+ "sha256": "d6765f2eb1fcb90fe917f82f593ab90c6ea99a1fd5f9beef1c8f0e5844ff62f0"
626
+ },
627
+ {
628
+ "bytes": 1289,
629
+ "git_blob_sha1": "c7213187024467b8b02ddc5325ae0e0599823ee2",
630
+ "path_in_repo": "provenance/source_data/mathir_action_menu_v1/identity.json",
631
+ "sha256": "a278cca1b222202a40616750e1e0c56799f02ded838eef51eeb3b097d75b103f"
632
+ },
633
+ {
634
+ "bytes": 21,
635
+ "git_blob_sha1": "40d5c04b431649b5c469de1fd03044ba97b6fded",
636
+ "path_in_repo": "provenance/source_data/mathir_action_menu_v1/train/dataset_dict.json",
637
+ "sha256": "c172eebfc28c1400d6be4338ce7d00191507ffb4ae64c315f039585c894df5b7"
638
+ },
639
+ {
640
+ "bytes": 559,
641
+ "git_blob_sha1": "c15fdbab4b5c6018a0638960fc92f250777ce2d9",
642
+ "path_in_repo": "provenance/source_data/mathir_action_menu_v1/train/train/dataset_info.json",
643
+ "sha256": "524a7bcf8a0a2067c688f41612fbfce06a30c9ac3e3ef1472ef4b057609ccc27"
644
+ },
645
+ {
646
+ "bytes": 247,
647
+ "git_blob_sha1": "76069e469a1c17b32053c56d352cd9f7d8bb1d18",
648
+ "path_in_repo": "provenance/source_data/mathir_action_menu_v1/train/train/state.json",
649
+ "sha256": "023c546290b2182a30761450cb650fb021e8144c752b6c7667beb10c58011efe"
650
+ },
651
+ {
652
+ "bytes": 31577,
653
+ "git_blob_sha1": "7523dd09f3eb166ddafd0c882fb8d52824d5f125",
654
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/admission_fairness_report.json",
655
+ "sha256": "0070600d687715fadff0cdf920e8959aeb6bcb398c566047bcdc285a05a611cb"
656
+ },
657
+ {
658
+ "bytes": 28,
659
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
660
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/countdown/dev/dataset_dict.json",
661
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
662
+ },
663
+ {
664
+ "bytes": 481,
665
+ "git_blob_sha1": "5db33a5d461fde3365428ea1e1ebdee57e5e6d21",
666
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/countdown/dev/multi_answer/dataset_info.json",
667
+ "sha256": "937ede6f568e39159d9ec7906776651b4a8ef82983246f2a8bd6648398a268a6"
668
+ },
669
+ {
670
+ "bytes": 247,
671
+ "git_blob_sha1": "23c40b5235ab80a11a29ecf0909836707cdb4695",
672
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/countdown/dev/multi_answer/state.json",
673
+ "sha256": "c2c852d47b4a21edbc86cacc47339f87d6b74006a6f3e7bba31bfb9362ac1532"
674
+ },
675
+ {
676
+ "bytes": 28,
677
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
678
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/countdown/eval/dataset_dict.json",
679
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
680
+ },
681
+ {
682
+ "bytes": 481,
683
+ "git_blob_sha1": "5db33a5d461fde3365428ea1e1ebdee57e5e6d21",
684
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/countdown/eval/multi_answer/dataset_info.json",
685
+ "sha256": "937ede6f568e39159d9ec7906776651b4a8ef82983246f2a8bd6648398a268a6"
686
+ },
687
+ {
688
+ "bytes": 247,
689
+ "git_blob_sha1": "a21ae45e27992d524e1c3963a4b1be6b3deeec9b",
690
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/countdown/eval/multi_answer/state.json",
691
+ "sha256": "e7bd76961f10ef2ba7154a81636d97e08b91a6f58ad7c70f159ddbe1b5f54061"
692
+ },
693
+ {
694
+ "bytes": 21,
695
+ "git_blob_sha1": "40d5c04b431649b5c469de1fd03044ba97b6fded",
696
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/countdown/train/dataset_dict.json",
697
+ "sha256": "c172eebfc28c1400d6be4338ce7d00191507ffb4ae64c315f039585c894df5b7"
698
+ },
699
+ {
700
+ "bytes": 481,
701
+ "git_blob_sha1": "5db33a5d461fde3365428ea1e1ebdee57e5e6d21",
702
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/countdown/train/train/dataset_info.json",
703
+ "sha256": "937ede6f568e39159d9ec7906776651b4a8ef82983246f2a8bd6648398a268a6"
704
+ },
705
+ {
706
+ "bytes": 247,
707
+ "git_blob_sha1": "8650d0a35bc3bf9d04dac0904d0b0845598662f8",
708
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/countdown/train/train/state.json",
709
+ "sha256": "f8f51e5c0788d05708a44fdbd16ace7b602cc6993b6f678296826f610ab6ab61"
710
+ },
711
+ {
712
+ "bytes": 28,
713
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
714
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/graph_coloring/dev/dataset_dict.json",
715
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
716
+ },
717
+ {
718
+ "bytes": 481,
719
+ "git_blob_sha1": "5db33a5d461fde3365428ea1e1ebdee57e5e6d21",
720
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/graph_coloring/dev/multi_answer/dataset_info.json",
721
+ "sha256": "937ede6f568e39159d9ec7906776651b4a8ef82983246f2a8bd6648398a268a6"
722
+ },
723
+ {
724
+ "bytes": 247,
725
+ "git_blob_sha1": "0bba9de9623af0576f2cd0b556a0f38eec7c2693",
726
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/graph_coloring/dev/multi_answer/state.json",
727
+ "sha256": "6cf8a5162993168b51312bc9e2de58ada3a4cd8e23ff6109beaf25cbe9206681"
728
+ },
729
+ {
730
+ "bytes": 28,
731
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
732
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/graph_coloring/eval/dataset_dict.json",
733
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
734
+ },
735
+ {
736
+ "bytes": 481,
737
+ "git_blob_sha1": "5db33a5d461fde3365428ea1e1ebdee57e5e6d21",
738
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/graph_coloring/eval/multi_answer/dataset_info.json",
739
+ "sha256": "937ede6f568e39159d9ec7906776651b4a8ef82983246f2a8bd6648398a268a6"
740
+ },
741
+ {
742
+ "bytes": 247,
743
+ "git_blob_sha1": "c0bb6e49e58b98278c4671f4a12c5d254aa1677d",
744
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/graph_coloring/eval/multi_answer/state.json",
745
+ "sha256": "d92e2d1f778196ca811c6b102212e72c8119b2d13b21611a04d39fe4e149bde9"
746
+ },
747
+ {
748
+ "bytes": 21,
749
+ "git_blob_sha1": "40d5c04b431649b5c469de1fd03044ba97b6fded",
750
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/graph_coloring/train/dataset_dict.json",
751
+ "sha256": "c172eebfc28c1400d6be4338ce7d00191507ffb4ae64c315f039585c894df5b7"
752
+ },
753
+ {
754
+ "bytes": 481,
755
+ "git_blob_sha1": "5db33a5d461fde3365428ea1e1ebdee57e5e6d21",
756
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/graph_coloring/train/train/dataset_info.json",
757
+ "sha256": "937ede6f568e39159d9ec7906776651b4a8ef82983246f2a8bd6648398a268a6"
758
+ },
759
+ {
760
+ "bytes": 247,
761
+ "git_blob_sha1": "2aa010d5067bc555d64b72123910d88708c57179",
762
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/graph_coloring/train/train/state.json",
763
+ "sha256": "570d70eb1cdf7aee52dce77ca0febd3322ed2ac434df091e01fa13d03f41d022"
764
+ },
765
+ {
766
+ "bytes": 17289,
767
+ "git_blob_sha1": "0da053bd543463b777c61e4921c502568eb74e3e",
768
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/identity.json",
769
+ "sha256": "2af80f4d31a44482574b314cc37ef84bde48c53ecc2ff78dadf97571f0d73fb2"
770
+ },
771
+ {
772
+ "bytes": 28,
773
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
774
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/mathir/dev/dataset_dict.json",
775
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
776
+ },
777
+ {
778
+ "bytes": 559,
779
+ "git_blob_sha1": "c15fdbab4b5c6018a0638960fc92f250777ce2d9",
780
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/mathir/dev/multi_answer/dataset_info.json",
781
+ "sha256": "524a7bcf8a0a2067c688f41612fbfce06a30c9ac3e3ef1472ef4b057609ccc27"
782
+ },
783
+ {
784
+ "bytes": 247,
785
+ "git_blob_sha1": "09207b5e91bd7f457902033de3562b99e0f89432",
786
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/mathir/dev/multi_answer/state.json",
787
+ "sha256": "1d40e16033cad5ec2b8bef6ff61bd56a624a2d8c3ed95d0dba42b99e91212570"
788
+ },
789
+ {
790
+ "bytes": 28,
791
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
792
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/mathir/eval/dataset_dict.json",
793
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
794
+ },
795
+ {
796
+ "bytes": 559,
797
+ "git_blob_sha1": "c15fdbab4b5c6018a0638960fc92f250777ce2d9",
798
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/mathir/eval/multi_answer/dataset_info.json",
799
+ "sha256": "524a7bcf8a0a2067c688f41612fbfce06a30c9ac3e3ef1472ef4b057609ccc27"
800
+ },
801
+ {
802
+ "bytes": 247,
803
+ "git_blob_sha1": "09bca51c5a6d593e0e142960849ec071abc6228b",
804
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/mathir/eval/multi_answer/state.json",
805
+ "sha256": "3ebd34460b5ba4802edf8b0c0540788c237739ffb7823de13fa7457917903602"
806
+ },
807
+ {
808
+ "bytes": 21,
809
+ "git_blob_sha1": "40d5c04b431649b5c469de1fd03044ba97b6fded",
810
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/mathir/train/dataset_dict.json",
811
+ "sha256": "c172eebfc28c1400d6be4338ce7d00191507ffb4ae64c315f039585c894df5b7"
812
+ },
813
+ {
814
+ "bytes": 559,
815
+ "git_blob_sha1": "c15fdbab4b5c6018a0638960fc92f250777ce2d9",
816
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/mathir/train/train/dataset_info.json",
817
+ "sha256": "524a7bcf8a0a2067c688f41612fbfce06a30c9ac3e3ef1472ef4b057609ccc27"
818
+ },
819
+ {
820
+ "bytes": 247,
821
+ "git_blob_sha1": "f1a71948cfd17b56ca96ed489ce7128595a22f46",
822
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/mathir/train/train/state.json",
823
+ "sha256": "2f22359a66ab796dabdcd4531923d7e7b3842fd1cf120bb7d33bd5371ebc35e6"
824
+ },
825
+ {
826
+ "bytes": 28,
827
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
828
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/pantry/dev/dataset_dict.json",
829
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
830
+ },
831
+ {
832
+ "bytes": 649,
833
+ "git_blob_sha1": "424248b26b9785c58704f9c453d455f680b4adb7",
834
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/pantry/dev/multi_answer/dataset_info.json",
835
+ "sha256": "321f2702833c5746cecdd10b289a15f8cc9396a4d5280e9126dc2ab83e8d2d4e"
836
+ },
837
+ {
838
+ "bytes": 247,
839
+ "git_blob_sha1": "26fa98f9fb8b6e72a68c9cf5d0f387c84c5affdb",
840
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/pantry/dev/multi_answer/state.json",
841
+ "sha256": "1b81977ac243d83e3bb5a6897ff5f07bfb62da185b72e8a9594163718cc5e5e2"
842
+ },
843
+ {
844
+ "bytes": 28,
845
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
846
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/pantry/eval/dataset_dict.json",
847
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
848
+ },
849
+ {
850
+ "bytes": 649,
851
+ "git_blob_sha1": "424248b26b9785c58704f9c453d455f680b4adb7",
852
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/pantry/eval/multi_answer/dataset_info.json",
853
+ "sha256": "321f2702833c5746cecdd10b289a15f8cc9396a4d5280e9126dc2ab83e8d2d4e"
854
+ },
855
+ {
856
+ "bytes": 247,
857
+ "git_blob_sha1": "e1a192d22c9794a83a935b82723ddcba2e7a6028",
858
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/pantry/eval/multi_answer/state.json",
859
+ "sha256": "fea69ac923bc43715f875dc09d8de34b9ecc9e5aecd4f384e65b284ce3ebd9f9"
860
+ },
861
+ {
862
+ "bytes": 21,
863
+ "git_blob_sha1": "40d5c04b431649b5c469de1fd03044ba97b6fded",
864
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/pantry/train/dataset_dict.json",
865
+ "sha256": "c172eebfc28c1400d6be4338ce7d00191507ffb4ae64c315f039585c894df5b7"
866
+ },
867
+ {
868
+ "bytes": 649,
869
+ "git_blob_sha1": "424248b26b9785c58704f9c453d455f680b4adb7",
870
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/pantry/train/train/dataset_info.json",
871
+ "sha256": "321f2702833c5746cecdd10b289a15f8cc9396a4d5280e9126dc2ab83e8d2d4e"
872
+ },
873
+ {
874
+ "bytes": 247,
875
+ "git_blob_sha1": "ed4ffe9d6fd34cc4099b784e83c04c9b2ed4240d",
876
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/pantry/train/train/state.json",
877
+ "sha256": "21515626c163d9096329d6024e6ab89cf5bbb4aca5756bc1b51993d05078b178"
878
+ },
879
+ {
880
+ "bytes": 28,
881
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
882
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/python_factors/dev/dataset_dict.json",
883
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
884
+ },
885
+ {
886
+ "bytes": 481,
887
+ "git_blob_sha1": "5db33a5d461fde3365428ea1e1ebdee57e5e6d21",
888
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/python_factors/dev/multi_answer/dataset_info.json",
889
+ "sha256": "937ede6f568e39159d9ec7906776651b4a8ef82983246f2a8bd6648398a268a6"
890
+ },
891
+ {
892
+ "bytes": 247,
893
+ "git_blob_sha1": "f60dd7f558f734bd98bfd171e5c93be94bec4aa2",
894
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/python_factors/dev/multi_answer/state.json",
895
+ "sha256": "719a7b3ddac8a7309312fe43ecdf54eb5b2eec7f563e6414e5a1346de9beac21"
896
+ },
897
+ {
898
+ "bytes": 28,
899
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
900
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/python_factors/eval/dataset_dict.json",
901
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
902
+ },
903
+ {
904
+ "bytes": 481,
905
+ "git_blob_sha1": "5db33a5d461fde3365428ea1e1ebdee57e5e6d21",
906
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/python_factors/eval/multi_answer/dataset_info.json",
907
+ "sha256": "937ede6f568e39159d9ec7906776651b4a8ef82983246f2a8bd6648398a268a6"
908
+ },
909
+ {
910
+ "bytes": 247,
911
+ "git_blob_sha1": "94162f8b5becda0cda0dfb472195b45009c247ec",
912
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/python_factors/eval/multi_answer/state.json",
913
+ "sha256": "eb72c5a66e49f1185ae8472ce438d526719e3326e88e149c7cc4be305941a4a4"
914
+ },
915
+ {
916
+ "bytes": 21,
917
+ "git_blob_sha1": "40d5c04b431649b5c469de1fd03044ba97b6fded",
918
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/python_factors/train/dataset_dict.json",
919
+ "sha256": "c172eebfc28c1400d6be4338ce7d00191507ffb4ae64c315f039585c894df5b7"
920
+ },
921
+ {
922
+ "bytes": 481,
923
+ "git_blob_sha1": "5db33a5d461fde3365428ea1e1ebdee57e5e6d21",
924
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/python_factors/train/train/dataset_info.json",
925
+ "sha256": "937ede6f568e39159d9ec7906776651b4a8ef82983246f2a8bd6648398a268a6"
926
+ },
927
+ {
928
+ "bytes": 247,
929
+ "git_blob_sha1": "37ecf9aaf2c6d8be06624ef8bc36840849da9dab",
930
+ "path_in_repo": "provenance/source_data/modebench_harder_v2_matched_r5/python_factors/train/train/state.json",
931
+ "sha256": "df0a77b8727e4bb1c0ac7d161cf9a5d33473554f7c45996122a62053791dba88"
932
+ },
933
+ {
934
+ "bytes": 102087,
935
+ "git_blob_sha1": "21cd00aab665038806cd9e00ac5caf776531d6e9",
936
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/admission_fairness_report.json",
937
+ "sha256": "890d7697af7789e0ae53c803586ec7f722685b7eb2239643175a1933fa45650d"
938
+ },
939
+ {
940
+ "bytes": 28,
941
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
942
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/countdown/dev/dataset_dict.json",
943
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
944
+ },
945
+ {
946
+ "bytes": 1013,
947
+ "git_blob_sha1": "a31abca2d2dd2beeaca558871acae8b52e8233b4",
948
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/countdown/dev/multi_answer/dataset_info.json",
949
+ "sha256": "3a6594fd03a6bc8adb72c5a7cc5f6a10821d8ac9bf8a65a1256ccef94dd5c2a5"
950
+ },
951
+ {
952
+ "bytes": 247,
953
+ "git_blob_sha1": "99a749166f451b1b8c92523828f246943bed5dd5",
954
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/countdown/dev/multi_answer/state.json",
955
+ "sha256": "f0b8587eaff77ff83a51fe26ddc5b4b7d58696860614f8f43efa33a44fda17af"
956
+ },
957
+ {
958
+ "bytes": 28,
959
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
960
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/countdown/eval/dataset_dict.json",
961
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
962
+ },
963
+ {
964
+ "bytes": 1013,
965
+ "git_blob_sha1": "2ef7fbf7ffc815c374b1f5660095e2715eddbab9",
966
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/countdown/eval/multi_answer/dataset_info.json",
967
+ "sha256": "8f85bc4c3ca0dcf5c19d780d9a121e49060b05c72e651f660c4c3680d06204d7"
968
+ },
969
+ {
970
+ "bytes": 247,
971
+ "git_blob_sha1": "53a4b0b1dfac15f4af186b83094c62e7dcf3d15b",
972
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/countdown/eval/multi_answer/state.json",
973
+ "sha256": "b2cf11211c950d6f983c9d532f6916e47873c239d70f7d5760417bc401085b8a"
974
+ },
975
+ {
976
+ "bytes": 21,
977
+ "git_blob_sha1": "40d5c04b431649b5c469de1fd03044ba97b6fded",
978
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/countdown/train/dataset_dict.json",
979
+ "sha256": "c172eebfc28c1400d6be4338ce7d00191507ffb4ae64c315f039585c894df5b7"
980
+ },
981
+ {
982
+ "bytes": 1013,
983
+ "git_blob_sha1": "2ef7fbf7ffc815c374b1f5660095e2715eddbab9",
984
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/countdown/train/train/dataset_info.json",
985
+ "sha256": "8f85bc4c3ca0dcf5c19d780d9a121e49060b05c72e651f660c4c3680d06204d7"
986
+ },
987
+ {
988
+ "bytes": 247,
989
+ "git_blob_sha1": "5067e602c1c2a0d029d43b61b7d0f2eb48f10283",
990
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/countdown/train/train/state.json",
991
+ "sha256": "ffdd91ceff679028c06c29124fae71d9bfb0ff0afecd46bb1fc48278723e9c1d"
992
+ },
993
+ {
994
+ "bytes": 2665,
995
+ "git_blob_sha1": "4ba06edc313683ce0193d71a14332671c4d77eee",
996
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/frozen_recipes.json",
997
+ "sha256": "acad4298da776476717753fab0ab8e97f106c8fcafeea08e5ad8af028fe7247c"
998
+ },
999
+ {
1000
+ "bytes": 28,
1001
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
1002
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/graph_coloring/dev/dataset_dict.json",
1003
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
1004
+ },
1005
+ {
1006
+ "bytes": 808,
1007
+ "git_blob_sha1": "2549bb8086e6de5007fb4a21b072fb4529777963",
1008
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/graph_coloring/dev/multi_answer/dataset_info.json",
1009
+ "sha256": "f3356c6d172e8d1f0772c9462d90dc00734f9a89ebb661bdf5b73347f5cb71be"
1010
+ },
1011
+ {
1012
+ "bytes": 247,
1013
+ "git_blob_sha1": "aec3f600965d0ad6c2153d292c502eec5b6b2644",
1014
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/graph_coloring/dev/multi_answer/state.json",
1015
+ "sha256": "0b60273ca14cfeeff2f722b4521bdd749799ec255a9b946cfac840559661ddce"
1016
+ },
1017
+ {
1018
+ "bytes": 28,
1019
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
1020
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/graph_coloring/eval/dataset_dict.json",
1021
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
1022
+ },
1023
+ {
1024
+ "bytes": 808,
1025
+ "git_blob_sha1": "429507300ad281830bc2c3022e8c8fc1da4a3f21",
1026
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/graph_coloring/eval/multi_answer/dataset_info.json",
1027
+ "sha256": "ed0ebe33c51bf50ebac45608e82474d41763e6a4c232c71c92c959ad62299c50"
1028
+ },
1029
+ {
1030
+ "bytes": 247,
1031
+ "git_blob_sha1": "e82447841c89d73d5e3fc811bbc709547c4bfa22",
1032
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/graph_coloring/eval/multi_answer/state.json",
1033
+ "sha256": "583c1b187bcb3dee13ba83505bfac970da96ad675eb92827a2d7f066872b4baf"
1034
+ },
1035
+ {
1036
+ "bytes": 21,
1037
+ "git_blob_sha1": "40d5c04b431649b5c469de1fd03044ba97b6fded",
1038
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/graph_coloring/train/dataset_dict.json",
1039
+ "sha256": "c172eebfc28c1400d6be4338ce7d00191507ffb4ae64c315f039585c894df5b7"
1040
+ },
1041
+ {
1042
+ "bytes": 808,
1043
+ "git_blob_sha1": "429507300ad281830bc2c3022e8c8fc1da4a3f21",
1044
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/graph_coloring/train/train/dataset_info.json",
1045
+ "sha256": "ed0ebe33c51bf50ebac45608e82474d41763e6a4c232c71c92c959ad62299c50"
1046
+ },
1047
+ {
1048
+ "bytes": 247,
1049
+ "git_blob_sha1": "e0e953d2b1d99712aa9187f3d45d37aeb8d0280e",
1050
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/graph_coloring/train/train/state.json",
1051
+ "sha256": "4f733150d04da4617e14dcd2344a7fe1a21d0044eea709b5aaf46d5f06345c25"
1052
+ },
1053
+ {
1054
+ "bytes": 102087,
1055
+ "git_blob_sha1": "21cd00aab665038806cd9e00ac5caf776531d6e9",
1056
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/identity.json",
1057
+ "sha256": "890d7697af7789e0ae53c803586ec7f722685b7eb2239643175a1933fa45650d"
1058
+ },
1059
+ {
1060
+ "bytes": 28,
1061
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
1062
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/mathir/dev/dataset_dict.json",
1063
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
1064
+ },
1065
+ {
1066
+ "bytes": 811,
1067
+ "git_blob_sha1": "8a5fb1f670166a00a4c492ee97ec8b42acea981d",
1068
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/mathir/dev/multi_answer/dataset_info.json",
1069
+ "sha256": "7de7a201f0c27522ef0306f466caabeebf42476d76b9ba5d4214ac0b9adfc8a7"
1070
+ },
1071
+ {
1072
+ "bytes": 247,
1073
+ "git_blob_sha1": "0cb87778ad2fd52944bf5343ceaf236cd0c606b8",
1074
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/mathir/dev/multi_answer/state.json",
1075
+ "sha256": "a11e139eebb288c8b0b4503ef35ad3160593854592a53178d151118fcb0017b8"
1076
+ },
1077
+ {
1078
+ "bytes": 28,
1079
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
1080
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/mathir/eval/dataset_dict.json",
1081
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
1082
+ },
1083
+ {
1084
+ "bytes": 811,
1085
+ "git_blob_sha1": "b702a40b8ce2f6595b05c83af835c647d81c0746",
1086
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/mathir/eval/multi_answer/dataset_info.json",
1087
+ "sha256": "6503d6c0c800c1bc8396eade4e4ca6a19e6b5f1eea9f01961de8b410d67d42e3"
1088
+ },
1089
+ {
1090
+ "bytes": 247,
1091
+ "git_blob_sha1": "4e8f65debe54495b8bfd81dfdde0e8bb15de8beb",
1092
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/mathir/eval/multi_answer/state.json",
1093
+ "sha256": "4b5b80936c9edc263494c2534c4bdc53822ee949eaa2b87967b6e0ec1f0df5a8"
1094
+ },
1095
+ {
1096
+ "bytes": 21,
1097
+ "git_blob_sha1": "40d5c04b431649b5c469de1fd03044ba97b6fded",
1098
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/mathir/train/dataset_dict.json",
1099
+ "sha256": "c172eebfc28c1400d6be4338ce7d00191507ffb4ae64c315f039585c894df5b7"
1100
+ },
1101
+ {
1102
+ "bytes": 811,
1103
+ "git_blob_sha1": "b702a40b8ce2f6595b05c83af835c647d81c0746",
1104
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/mathir/train/train/dataset_info.json",
1105
+ "sha256": "6503d6c0c800c1bc8396eade4e4ca6a19e6b5f1eea9f01961de8b410d67d42e3"
1106
+ },
1107
+ {
1108
+ "bytes": 247,
1109
+ "git_blob_sha1": "3bce600ec9f6f4464d5a6efb1ea109be19af60ba",
1110
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/mathir/train/train/state.json",
1111
+ "sha256": "663064b7b9daa57b7cf4befb7b461c89b129bab6bface6c7798fc1f62b885437"
1112
+ },
1113
+ {
1114
+ "bytes": 28,
1115
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
1116
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/pantry/dev/dataset_dict.json",
1117
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
1118
+ },
1119
+ {
1120
+ "bytes": 919,
1121
+ "git_blob_sha1": "ca417d0ed8497acf8cfda32b2c2df9c7d645ea5b",
1122
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/pantry/dev/multi_answer/dataset_info.json",
1123
+ "sha256": "8841f8f126914011bc7e6d1d7657d87a65678798484494d69617b044dbd8d00b"
1124
+ },
1125
+ {
1126
+ "bytes": 247,
1127
+ "git_blob_sha1": "cb2b94436144906106aeaf4e8715b4f800eb6d1c",
1128
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/pantry/dev/multi_answer/state.json",
1129
+ "sha256": "cb5e971bf25432b52875b392ef05e5ebce2320eef1ac145c4fbc1bc1bca94b77"
1130
+ },
1131
+ {
1132
+ "bytes": 28,
1133
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
1134
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/pantry/eval/dataset_dict.json",
1135
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
1136
+ },
1137
+ {
1138
+ "bytes": 919,
1139
+ "git_blob_sha1": "faf81e7156ce692b6d3f6472b36acd15a48a1a2d",
1140
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/pantry/eval/multi_answer/dataset_info.json",
1141
+ "sha256": "0e2d9c04883f0dfcbcd85d164bcd35dc8a0d4fb48edc81cfb58c2fc4ae89bdf3"
1142
+ },
1143
+ {
1144
+ "bytes": 247,
1145
+ "git_blob_sha1": "5766e0623c5e450feccb6280d9154454fedf1b9b",
1146
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/pantry/eval/multi_answer/state.json",
1147
+ "sha256": "989fa13aa124ef795ff9dacc10ec73ac0cb0fc3a1fbb1b07da8d8fdbf4f3151c"
1148
+ },
1149
+ {
1150
+ "bytes": 21,
1151
+ "git_blob_sha1": "40d5c04b431649b5c469de1fd03044ba97b6fded",
1152
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/pantry/train/dataset_dict.json",
1153
+ "sha256": "c172eebfc28c1400d6be4338ce7d00191507ffb4ae64c315f039585c894df5b7"
1154
+ },
1155
+ {
1156
+ "bytes": 919,
1157
+ "git_blob_sha1": "faf81e7156ce692b6d3f6472b36acd15a48a1a2d",
1158
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/pantry/train/train/dataset_info.json",
1159
+ "sha256": "0e2d9c04883f0dfcbcd85d164bcd35dc8a0d4fb48edc81cfb58c2fc4ae89bdf3"
1160
+ },
1161
+ {
1162
+ "bytes": 247,
1163
+ "git_blob_sha1": "2301e2ed1c70126c0f6f6286aa603f2edcb519db",
1164
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/pantry/train/train/state.json",
1165
+ "sha256": "7c42b8ab5596c9f777aa680a0e48693e53a1bed2d44bc1bad2b6e3b7f764845f"
1166
+ },
1167
+ {
1168
+ "bytes": 28,
1169
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
1170
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/python_factors/dev/dataset_dict.json",
1171
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
1172
+ },
1173
+ {
1174
+ "bytes": 1358,
1175
+ "git_blob_sha1": "d741860906fe200c0868707574d339122f8b11a0",
1176
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/python_factors/dev/multi_answer/dataset_info.json",
1177
+ "sha256": "d447829bd7c2170b5bb5421c63d65fb5670a84ddba74901f258602aee8d41937"
1178
+ },
1179
+ {
1180
+ "bytes": 247,
1181
+ "git_blob_sha1": "40261b127ea8ae4d55f2abd836e9358a7bc5c549",
1182
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/python_factors/dev/multi_answer/state.json",
1183
+ "sha256": "e82dc482efcfb4887aa58864624324fc5daf3708389fbcfaaec1ca653b8dfa08"
1184
+ },
1185
+ {
1186
+ "bytes": 28,
1187
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
1188
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/python_factors/eval/dataset_dict.json",
1189
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
1190
+ },
1191
+ {
1192
+ "bytes": 1358,
1193
+ "git_blob_sha1": "0c325aaefe491ea7455c04854946a32c07ab5fe4",
1194
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/python_factors/eval/multi_answer/dataset_info.json",
1195
+ "sha256": "f580d477ab36046237210cb31bdf2538faed3fd4ecea7a7e6b4a31fdfe31d22d"
1196
+ },
1197
+ {
1198
+ "bytes": 247,
1199
+ "git_blob_sha1": "5ce160543ade3771f7c7a51184c2fa0c3cecc932",
1200
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/python_factors/eval/multi_answer/state.json",
1201
+ "sha256": "ac499fb4040a1643b309a259b880344749062c9c4f557e10021d35df411f8f8d"
1202
+ },
1203
+ {
1204
+ "bytes": 21,
1205
+ "git_blob_sha1": "40d5c04b431649b5c469de1fd03044ba97b6fded",
1206
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/python_factors/train/dataset_dict.json",
1207
+ "sha256": "c172eebfc28c1400d6be4338ce7d00191507ffb4ae64c315f039585c894df5b7"
1208
+ },
1209
+ {
1210
+ "bytes": 1358,
1211
+ "git_blob_sha1": "0c325aaefe491ea7455c04854946a32c07ab5fe4",
1212
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/python_factors/train/train/dataset_info.json",
1213
+ "sha256": "f580d477ab36046237210cb31bdf2538faed3fd4ecea7a7e6b4a31fdfe31d22d"
1214
+ },
1215
+ {
1216
+ "bytes": 247,
1217
+ "git_blob_sha1": "ee6a5faacb3b07faf1c3e121322c7a67a8c04c43",
1218
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/python_factors/train/train/state.json",
1219
+ "sha256": "35bf814813678296c63255ab4ea2eb42d3655b2c48a919aeeb063d88c020f751"
1220
+ },
1221
+ {
1222
+ "bytes": 46204,
1223
+ "git_blob_sha1": "04a922f4f87be6bd518786552f7718e0f04c171a",
1224
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/recipes/countdown.json",
1225
+ "sha256": "5db6913a1a7ed16e1eaca49f3fbd09f8494d46d118152f6b8f3a80a6d22f061e"
1226
+ },
1227
+ {
1228
+ "bytes": 890069,
1229
+ "git_blob_sha1": "c652b1e108c4ab80a608be8064715836a7a11d2d",
1230
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/recipes/graph_coloring.json",
1231
+ "sha256": "75121d937b5724489ab15077d4885c6cf4a0c98e73d68fdcf41cb236941cd47b"
1232
+ },
1233
+ {
1234
+ "bytes": 45940,
1235
+ "git_blob_sha1": "8da31797d7e6a6c2f8367889550f787c6d76968d",
1236
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/recipes/mathir.json",
1237
+ "sha256": "2ee513ecec4967478b7c88b8d5b87009efc50c9b6a1f73583975cf10d711e0cc"
1238
+ },
1239
+ {
1240
+ "bytes": 52273,
1241
+ "git_blob_sha1": "e1b3184c327ad284ca45a897bea7d44acb16e329",
1242
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/recipes/pantry.json",
1243
+ "sha256": "4d7ec52ec2ccb10fd57d0301baa83cb3856fe93cde5e98e4d4a06acbd29837c4"
1244
+ },
1245
+ {
1246
+ "bytes": 908705,
1247
+ "git_blob_sha1": "d376a9bbe6ee884311515f74392f874e8ff1508a",
1248
+ "path_in_repo": "provenance/source_data/modebench_level3_matched_v3/recipes/python_factors.json",
1249
+ "sha256": "fb009b8f27a9f7f2c99dc609625748c6f11dd9d1e83e3550397a31af23c4ca3a"
1250
+ },
1251
+ {
1252
+ "bytes": 28,
1253
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
1254
+ "path_in_repo": "provenance/source_data/pantry_plan_modebench_v2/dev/dataset_dict.json",
1255
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
1256
+ },
1257
+ {
1258
+ "bytes": 649,
1259
+ "git_blob_sha1": "424248b26b9785c58704f9c453d455f680b4adb7",
1260
+ "path_in_repo": "provenance/source_data/pantry_plan_modebench_v2/dev/multi_answer/dataset_info.json",
1261
+ "sha256": "321f2702833c5746cecdd10b289a15f8cc9396a4d5280e9126dc2ab83e8d2d4e"
1262
+ },
1263
+ {
1264
+ "bytes": 247,
1265
+ "git_blob_sha1": "697efcd52101a8d0c3645bf6b9ae65b09b678774",
1266
+ "path_in_repo": "provenance/source_data/pantry_plan_modebench_v2/dev/multi_answer/state.json",
1267
+ "sha256": "64d90969f24740cc2f85f01762105dc5f54c0639965ee54752b33c83e259fbb4"
1268
+ },
1269
+ {
1270
+ "bytes": 28,
1271
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
1272
+ "path_in_repo": "provenance/source_data/pantry_plan_modebench_v2/eval/dataset_dict.json",
1273
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
1274
+ },
1275
+ {
1276
+ "bytes": 649,
1277
+ "git_blob_sha1": "424248b26b9785c58704f9c453d455f680b4adb7",
1278
+ "path_in_repo": "provenance/source_data/pantry_plan_modebench_v2/eval/multi_answer/dataset_info.json",
1279
+ "sha256": "321f2702833c5746cecdd10b289a15f8cc9396a4d5280e9126dc2ab83e8d2d4e"
1280
+ },
1281
+ {
1282
+ "bytes": 247,
1283
+ "git_blob_sha1": "e84759f9b035b95e2e5af9a61af3f10756411a01",
1284
+ "path_in_repo": "provenance/source_data/pantry_plan_modebench_v2/eval/multi_answer/state.json",
1285
+ "sha256": "bd466f2256b86708821c529099e6fa280bdc8092cce8da1c8812428357128f92"
1286
+ },
1287
+ {
1288
+ "bytes": 1631,
1289
+ "git_blob_sha1": "ce4091317fe130b885351cc6be9fcc8c8a3e381e",
1290
+ "path_in_repo": "provenance/source_data/pantry_plan_modebench_v2/identity.json",
1291
+ "sha256": "865628033a7cdfc28e1c3c92172c93d1d34e40ce42eec094673b5b29dc3792b4"
1292
+ },
1293
+ {
1294
+ "bytes": 21,
1295
+ "git_blob_sha1": "40d5c04b431649b5c469de1fd03044ba97b6fded",
1296
+ "path_in_repo": "provenance/source_data/pantry_plan_modebench_v2/train/dataset_dict.json",
1297
+ "sha256": "c172eebfc28c1400d6be4338ce7d00191507ffb4ae64c315f039585c894df5b7"
1298
+ },
1299
+ {
1300
+ "bytes": 649,
1301
+ "git_blob_sha1": "424248b26b9785c58704f9c453d455f680b4adb7",
1302
+ "path_in_repo": "provenance/source_data/pantry_plan_modebench_v2/train/train/dataset_info.json",
1303
+ "sha256": "321f2702833c5746cecdd10b289a15f8cc9396a4d5280e9126dc2ab83e8d2d4e"
1304
+ },
1305
+ {
1306
+ "bytes": 247,
1307
+ "git_blob_sha1": "ffc6362a61b9b644cc6be0dbf6294bbffc1f5f11",
1308
+ "path_in_repo": "provenance/source_data/pantry_plan_modebench_v2/train/train/state.json",
1309
+ "sha256": "256dd6a5c3088c1e95d88cf65f09ffcafc34d3de543d18f551a441f7e382204a"
1310
+ },
1311
+ {
1312
+ "bytes": 28,
1313
+ "git_blob_sha1": "bec072a844d9c8b58cd512cdd5004f9b8c26ad64",
1314
+ "path_in_repo": "provenance/source_data/python_factor_modebench_v1/eval/dataset_dict.json",
1315
+ "sha256": "3d2b7908811384a988b8c5e66b0e3afd5ce44e25ba23bf829808c6dc8fd49caf"
1316
+ },
1317
+ {
1318
+ "bytes": 481,
1319
+ "git_blob_sha1": "5db33a5d461fde3365428ea1e1ebdee57e5e6d21",
1320
+ "path_in_repo": "provenance/source_data/python_factor_modebench_v1/eval/multi_answer/dataset_info.json",
1321
+ "sha256": "937ede6f568e39159d9ec7906776651b4a8ef82983246f2a8bd6648398a268a6"
1322
+ },
1323
+ {
1324
+ "bytes": 247,
1325
+ "git_blob_sha1": "f729e5879140fe617438ecb5f25fe1499ef00820",
1326
+ "path_in_repo": "provenance/source_data/python_factor_modebench_v1/eval/multi_answer/state.json",
1327
+ "sha256": "ebbbd75ff8373c9404d689185fbe40b065305e08e1555bd44fcd32ba37c6d4f4"
1328
+ },
1329
+ {
1330
+ "bytes": 475,
1331
+ "git_blob_sha1": "e67bbbe2e3eb15ff7bf594aac687b87485c8d3ea",
1332
+ "path_in_repo": "provenance/source_data/python_factor_modebench_v1/identity.json",
1333
+ "sha256": "d4c710b9b433555cacb081683fddb0cf1b18497262283b17ded9a71c8a2c6d39"
1334
+ },
1335
+ {
1336
+ "bytes": 21,
1337
+ "git_blob_sha1": "40d5c04b431649b5c469de1fd03044ba97b6fded",
1338
+ "path_in_repo": "provenance/source_data/python_factor_modebench_v1/train/dataset_dict.json",
1339
+ "sha256": "c172eebfc28c1400d6be4338ce7d00191507ffb4ae64c315f039585c894df5b7"
1340
+ },
1341
+ {
1342
+ "bytes": 481,
1343
+ "git_blob_sha1": "5db33a5d461fde3365428ea1e1ebdee57e5e6d21",
1344
+ "path_in_repo": "provenance/source_data/python_factor_modebench_v1/train/train/dataset_info.json",
1345
+ "sha256": "937ede6f568e39159d9ec7906776651b4a8ef82983246f2a8bd6648398a268a6"
1346
+ },
1347
+ {
1348
+ "bytes": 247,
1349
+ "git_blob_sha1": "08ea11c59c768d01f0a61a646139fccb01837157",
1350
+ "path_in_repo": "provenance/source_data/python_factor_modebench_v1/train/train/state.json",
1351
+ "sha256": "45718961de23f91262a751aaeb5d8c913cab2f84ccd817824d45924bb9a0a921"
1352
+ },
1353
+ {
1354
+ "bytes": 196,
1355
+ "git_blob_sha1": "0ea4603431bdcb719b3367b1768a6b4122ff5c25",
1356
+ "path_in_repo": "requirements-verifier.txt",
1357
+ "sha256": "a1a91a4f20d29765766368f050a7cf03c9557c08a6e5b303bb6a1dc7d83e7cd6"
1358
+ },
1359
+ {
1360
+ "bytes": 25024,
1361
+ "git_blob_sha1": "8b59c78a1fff1167b5e6b240319d3984251fbc6f",
1362
+ "path_in_repo": "tools/export_modebench_hf_release.py",
1363
+ "sha256": "23dbb20cd97e7c61c36f072bf1199738991f7dd09081c207ea6067733ed85715"
1364
+ },
1365
+ {
1366
+ "bytes": 3891,
1367
+ "git_blob_sha1": "882c196b214dfb07e4186b416759eab6176cb6a7",
1368
+ "path_in_repo": "tools/seal_modebench_hf_release.py",
1369
+ "sha256": "1de66a50152f995c6958f9f4e14709a6651bdfed72b5270590ed6af36324233c"
1370
+ }
1371
+ ],
1372
+ "files_count": 228,
1373
+ "schema": "modebench-public-content-manifest-v1",
1374
+ "self_excluded": "CONTENT_SHA256.json",
1375
+ "total_bytes": 5637784
1376
+ }
EVALUATION.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Executable verification and canonical identity
2
+
3
+ For responses already decoded to the task's verifier surface, the supplied `code/oat_drgrpo/math_grader.py` entry point is `validated_modebench_outcome_key(response, row["answer"])`. It returns a canonical key only when that same response passes the executable task verifier; invalid responses return `None`.
4
+
5
+ | Domain | Executable acceptance | Canonical identity |
6
+ | --- | --- | --- |
7
+ | Graph Coloring | Parse assignments; preserve fixed colors and satisfy every edge | Complete color vector |
8
+ | Countdown | Restricted arithmetic AST, exact operand multiplicities and exact target value | Normalized expression AST with registered commutative normalization |
9
+ | Python Factors | Restricted function AST executed in the bounded external worker on the specified cases | Executed return vector |
10
+ | MathIR | Restricted action menu expanded and executed using exact equation transformations | Executed normalized state trajectory |
11
+ | PantryPlan | Bounded ingredient quantities, serving steps, mass/nutrient constraints and dietary restrictions | Ingredient support |
12
+
13
+ Install the versioned dependencies recorded in `MANIFEST.json`/`requirements-verifier.txt`; prepend the release's `code` directory to Python's import path. The code is supplied as inspectable ordinary source, not automatically executed by the datasets loader.
14
+
15
+ ```python
16
+ import sys
17
+ sys.path.insert(0, "path/to/ModeBench/code")
18
+ from oat_drgrpo.math_grader import validated_modebench_outcome_key
19
+
20
+ key = validated_modebench_outcome_key(response, row["answer"])
21
+ verified = key is not None
22
+ ```
23
+
24
+ Policy action adapters must run before this grader when the registered interface uses them. In particular, Pantry's six-bit support mask is not an allocation string: use `decode_pantry_support_mask(mask, json.loads(row["answer"]))` from `oat_drgrpo.pantry_support_action`, then grade the returned allocation. The frozen adapter searches only the chosen support's registered quantity grid and returns an invalid sentinel when infeasible; it does not consult a gold support catalogue. `canonical_actions.py` preserves the other registered action-to-verifier adapters.
25
+
26
+ Python Factors retains its original separate, syntax-restricted worker. Use the supplied implementation for model outputs rather than evaluating arbitrary response strings in a notebook. The code also contains imported legacy task support needed by the original module; this release's dataset configurations contain only the five listed domains.
27
+
28
+ All copied verifier/template dependencies are authenticated against the completed Level-3 confirmation's source hashes. The release validation checks canonical *problem* identity uniqueness and disjointness, row/feature preservation, and the original structural/support-histogram records. It does not regenerate every exhaustive answer catalogue, retrain models, or claim a new model-admission result.
LICENSE_PROVENANCE.md ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Existing source terms
2
+
3
+ {
4
+ "dataset_specific_license": "No separate dataset license found in the frozen dataset roots; no new dataset license assigned by this export.",
5
+ "pantry_ingredient_source": {
6
+ "archive_name": "FoodData_Central_foundation_food_json_2026-04-30.zip",
7
+ "archive_sha256": "186e988ec542e913f51ef62b86a47758e8cdd0d1dc3889e7b055581f3c09c77a",
8
+ "dataset": "USDA FoodData Central Foundation Foods",
9
+ "food_object_rows": 363,
10
+ "license": "CC0 1.0 / U.S. public-domain data",
11
+ "null_placeholder_rows": 32,
12
+ "physical_rows": 395,
13
+ "release": "April 2026",
14
+ "url": "https://fdc.nal.usda.gov/download-datasets/"
15
+ },
16
+ "source_code": "Existing repository Apache-2.0 LICENSE copied verbatim; existing source copyright notices retained."
17
+ }
LOADER_VALIDATION.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "all_rows_compared": 9152,
3
+ "command": "PYTHONDONTWRITEBYTECODE=1 HF_DATASETS_OFFLINE=1 var/seed_paper_eval/paper310/bin/python -m pytest tests/test_modebench_hf_release.py -q --tb=short --basetemp=/tmp/modebench_release_tests_20260911",
4
+ "elapsed_seconds": 9.26,
5
+ "feature_schema_equal": true,
6
+ "network_required": false,
7
+ "original_sources_deleted": false,
8
+ "pantry_policy_adapter_verified": true,
9
+ "portable_verifier_domains": 5,
10
+ "row_order_equal": true,
11
+ "schema": "modebench-standard-loader-and-portable-verifier-validation-v1",
12
+ "separate_python_worker_verified": true,
13
+ "splits_compared_to_original": 42,
14
+ "standard_huggingface_config_loads": 16,
15
+ "status": "passed",
16
+ "test_source_sha256": "c944a8bcbbc171fbd4750c2a47fe3301df57388e5f6dbb04b4c114ed8d3d02c1",
17
+ "tests_passed": 18,
18
+ "validated_at_utc": "2026-09-11T07:40:45.457482+00:00"
19
+ }
MANIFEST.json ADDED
The diff for this file is too large to render. See raw diff
 
PROMPTS.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Prompt formatting
2
+
3
+ Every Parquet row preserves the original `problem` string and the original serialized `answer` specification. Send the problem through the selected model/experiment's frozen template; do not concatenate the answer specification or support metadata into the prompt.
4
+
5
+ For the original Qwen Level-1 training interface, Graph, Countdown, Python, and MathIR use `qwen_boxed`; Pantry uses `qwen_pantry_support_mask`. The copied `code/oat_drgrpo/templates.py` preserves the exact template text and Qwen/Falcon role markers. `provenance/source_code/ops/check_paper_domain_prompts.py` binds the original paper examples to those strings.
6
+
7
+ Level-2/Level-3 admission uses the versioned interface in `provenance/source_code/ops/evaluate_modebench_level2_viability.py` and `evaluate_modebench_level3.py`: Graph uses the direct boxed interface, while the other domains use the registered hybrid solver interface and their legal-output constraints. That admission interface and its model-native tokenizer rendering are distinct from a training experiment's fixed template. Copying a dataset alone does not reproduce a decoder or inference-engine configuration.
8
+
9
+ The original training and evaluation launchers remain the source of model-specific precision, length limits, guided-decoding profiles, draw seeds, and selected model checkpoints. The files here preserve the shared prompt/template implementation and the dataset rows; they do not silently standardize these experiment-specific choices.
README.md ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ task_categories:
5
+ - text-generation
6
+ tags:
7
+ - reasoning
8
+ - reinforcement-learning
9
+ - verifiable-rewards
10
+ - modebench
11
+ pretty_name: ModeBench
12
+ configs:
13
+ - config_name: level1_countdown
14
+ data_files:
15
+ - split: train
16
+ path: data/level1_countdown/train.parquet
17
+ - split: eval
18
+ path: data/level1_countdown/eval.parquet
19
+ - config_name: level1_graph_coloring
20
+ data_files:
21
+ - split: train
22
+ path: data/level1_graph_coloring/train.parquet
23
+ - split: eval
24
+ path: data/level1_graph_coloring/eval.parquet
25
+ - config_name: level1_graph_coloring_unique_answer
26
+ data_files:
27
+ - split: eval
28
+ path: data/level1_graph_coloring_unique_answer/eval.parquet
29
+ - config_name: level1_mathir
30
+ data_files:
31
+ - split: train
32
+ path: data/level1_mathir/train.parquet
33
+ - split: eval
34
+ path: data/level1_mathir/eval.parquet
35
+ - config_name: level1_pantry_plan
36
+ data_files:
37
+ - split: train
38
+ path: data/level1_pantry_plan/train.parquet
39
+ - split: dev
40
+ path: data/level1_pantry_plan/dev.parquet
41
+ - split: eval
42
+ path: data/level1_pantry_plan/eval.parquet
43
+ - config_name: level1_python_factors
44
+ data_files:
45
+ - split: train
46
+ path: data/level1_python_factors/train.parquet
47
+ - split: eval
48
+ path: data/level1_python_factors/eval.parquet
49
+ - config_name: level2_countdown
50
+ data_files:
51
+ - split: train
52
+ path: data/level2_countdown/train.parquet
53
+ - split: dev
54
+ path: data/level2_countdown/dev.parquet
55
+ - split: eval
56
+ path: data/level2_countdown/eval.parquet
57
+ - config_name: level2_graph_coloring
58
+ data_files:
59
+ - split: train
60
+ path: data/level2_graph_coloring/train.parquet
61
+ - split: dev
62
+ path: data/level2_graph_coloring/dev.parquet
63
+ - split: eval
64
+ path: data/level2_graph_coloring/eval.parquet
65
+ - config_name: level2_mathir
66
+ data_files:
67
+ - split: train
68
+ path: data/level2_mathir/train.parquet
69
+ - split: dev
70
+ path: data/level2_mathir/dev.parquet
71
+ - split: eval
72
+ path: data/level2_mathir/eval.parquet
73
+ - config_name: level2_pantry_plan
74
+ data_files:
75
+ - split: train
76
+ path: data/level2_pantry_plan/train.parquet
77
+ - split: dev
78
+ path: data/level2_pantry_plan/dev.parquet
79
+ - split: eval
80
+ path: data/level2_pantry_plan/eval.parquet
81
+ - config_name: level2_python_factors
82
+ data_files:
83
+ - split: train
84
+ path: data/level2_python_factors/train.parquet
85
+ - split: dev
86
+ path: data/level2_python_factors/dev.parquet
87
+ - split: eval
88
+ path: data/level2_python_factors/eval.parquet
89
+ - config_name: level3_countdown
90
+ data_files:
91
+ - split: train
92
+ path: data/level3_countdown/train.parquet
93
+ - split: dev
94
+ path: data/level3_countdown/dev.parquet
95
+ - split: eval
96
+ path: data/level3_countdown/eval.parquet
97
+ - config_name: level3_graph_coloring
98
+ data_files:
99
+ - split: train
100
+ path: data/level3_graph_coloring/train.parquet
101
+ - split: dev
102
+ path: data/level3_graph_coloring/dev.parquet
103
+ - split: eval
104
+ path: data/level3_graph_coloring/eval.parquet
105
+ - config_name: level3_mathir
106
+ data_files:
107
+ - split: train
108
+ path: data/level3_mathir/train.parquet
109
+ - split: dev
110
+ path: data/level3_mathir/dev.parquet
111
+ - split: eval
112
+ path: data/level3_mathir/eval.parquet
113
+ - config_name: level3_pantry_plan
114
+ data_files:
115
+ - split: train
116
+ path: data/level3_pantry_plan/train.parquet
117
+ - split: dev
118
+ path: data/level3_pantry_plan/dev.parquet
119
+ - split: eval
120
+ path: data/level3_pantry_plan/eval.parquet
121
+ - config_name: level3_python_factors
122
+ data_files:
123
+ - split: train
124
+ path: data/level3_python_factors/train.parquet
125
+ - split: dev
126
+ path: data/level3_python_factors/dev.parquet
127
+ - split: eval
128
+ path: data/level3_python_factors/eval.parquet
129
+ ---
130
+
131
+ # ModeBench
132
+
133
+ ModeBench measures both correctness and the variety of correct answers produced by language models. Each problem has an executable verifier and a canonical definition of answer identity, so distinct wording alone does not count as a new solution.
134
+
135
+ This release contains three frozen benchmark levels across **Graph Coloring, Countdown, Python Factors, MathIR, and PantryPlan**. It preserves every original feature, row, and row order. The `answer` field is a serialized executable specification, not a target answer to include in the model prompt.
136
+
137
+ [Level 1](#level-1) · [Level 2](#level-2) · [Level 3](#level-3) · [Loading](#loading) · [Evaluation](#evaluation) · [Manifest](MANIFEST.json) · [Validation](VALIDATION.json)
138
+
139
+ The accompanying [model and research-artifact archive](https://huggingface.co/od2961/maxent-grpo-models) contains experiment-specific model indexes and mappings to the paper results. Dataset publication does not imply completed Level-3 training results.
140
+
141
+ <a id="level-1"></a>
142
+ ## Level 1
143
+
144
+ The original benchmark uses 384 training problems and 128 primary evaluation problems per domain. PantryPlan additionally has its original 64-row development split. Graph Coloring also includes a separate 128-row `unique_answer` evaluation subset; it is published as the auxiliary `level1_graph_coloring_unique_answer` configuration and is not the primary multi-answer paper evaluation.
145
+
146
+ <a id="level-2"></a>
147
+ ## Level 2
148
+
149
+ Level 2 is the frozen `modebench_harder_v2_matched_r5` release. It changes problem structure while retaining the verifier and canonicalizer contracts. Each domain has 384 training, 128 development, and 128 evaluation rows. Support histograms follow the recorded matched reference construction; refer to the original identity manifest for the precise reference splits and scaling factors.
150
+
151
+ <a id="level-3"></a>
152
+ ## Level 3
153
+
154
+ Level 3 is the E122-frozen `modebench_level3_matched_v3` release, with 384 training, 128 development, and 128 evaluation rows per domain. It preserves Level-2 support histograms. Admission used adaptive second-round matching to fixed historical Level-1 measurements: Graph and Python have fresh v3 confirmation, while Countdown, MathIR, and Pantry retain prior split bytes and confirmation evidence. This is not a claim of statistical equivalence, or of five fresh same-round confirmations.
155
+
156
+ The original [identity manifest](provenance/source_data/modebench_level3_matched_v3/identity.json) still records `pending_fresh_candidate_confirmation`. That historical record is preserved verbatim. The later [confirmation report](provenance/confirmation_report.json) records `matched_fixed_reference` and binds that exact dataset identity. Neither record has been rewritten for publication.
157
+
158
+ <a id="loading"></a>
159
+ ## Loading
160
+
161
+ ```python
162
+ from datasets import load_dataset
163
+
164
+ ds = load_dataset("od2961/ModeBench", "level2_countdown")
165
+ train = ds["train"]
166
+ development = ds["dev"]
167
+ evaluation = ds["eval"]
168
+
169
+ # Raw problem text goes to the policy. Keep the executable answer spec private
170
+ # from the policy and use it only in the verifier.
171
+ problem = evaluation[0]["problem"]
172
+ reference_spec = evaluation[0]["answer"]
173
+ ```
174
+
175
+ Use `level1_`, `level2_`, or `level3_` followed by `graph_coloring`, `countdown`, `python_factors`, `mathir`, or `pantry_plan`. Only existing splits are exposed; Level 1 generally has no `dev` split. No `test` split is invented. The Parquet files load through the standard datasets loader without remote dataset code. Pin a dataset revision for reproducible experiments.
176
+
177
+ <a id="evaluation"></a>
178
+ ## Evaluation
179
+
180
+ Use the original held-out `eval` rows and the frozen prompt, decoding, and verifier settings for a stated comparison. Use `dev` only where the original release provides it. Do not fit prompts, choose checkpoints, or tune methods on evaluation outcomes; training, development, and evaluation roles remain separate after public release.
181
+
182
+ The same executable validation produces acceptance and canonical identity. Report correctness and distinct correct identities separately: with K sampled answers, pass@K is whether any answer verifies, and distinct@K counts unique verified canonical keys. The reported main benchmark uses K=8; the papers specify the seeds, draws, and training checkpoints. [Evaluation and prompt guide](EVALUATION.md) documents the supplied verifier interface and its versioned source.
183
+
184
+ The support-count metadata and reference specifications are for construction, checking, and analysis. Do not supply gold support catalogues or hidden evaluation references to the policy. Original prompt strings are retained; [prompt formatting](PROMPTS.md) distinguishes raw problems from the model-specific chat and decoding interfaces.
185
+
186
+ ## Files and provenance
187
+
188
+ `MANIFEST.json` records every source identity, feature schema, ordered-row digest, split mapping, and Parquet digest. `VALIDATION.json` records full row and feature round trips, unchanged source files, canonical problem-identity checks, and support matching. `code/oat_drgrpo/` preserves verifier and template source files byte for byte; `provenance/` preserves original identities and construction/admission records.
189
+
190
+ ## License provenance
191
+
192
+ The original repository's Apache-2.0 source-code license is preserved in [licenses/source_repository_APACHE_2.0.txt](licenses/source_repository_APACHE_2.0.txt), and copied source copyright notices remain intact. The frozen dataset roots contain no separate dataset-specific license declaration; this export does not invent new dataset license terms. PantryPlan ingredient provenance records USDA FoodData Central Foundation Foods under CC0/public-domain source terms in [pantry_ingredient_source.json](provenance/pantry_ingredient_source.json).
SPLITS.md ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Configurations and original split mappings
2
+
3
+ | Config | Split | Rows | Original serialized subset |
4
+ | --- | --- | ---: | --- |
5
+ | `level1_graph_coloring` | `train` | 384 | `train` |
6
+ | `level1_graph_coloring` | `eval` | 128 | `multi_answer` |
7
+ | `level1_graph_coloring_unique_answer` | `eval` | 128 | `unique_answer` |
8
+ | `level1_countdown` | `train` | 384 | `train` |
9
+ | `level1_countdown` | `eval` | 128 | `multi_answer` |
10
+ | `level1_python_factors` | `train` | 384 | `train` |
11
+ | `level1_python_factors` | `eval` | 128 | `multi_answer` |
12
+ | `level1_mathir` | `train` | 384 | `train` |
13
+ | `level1_mathir` | `eval` | 128 | `multi_answer` |
14
+ | `level1_pantry_plan` | `train` | 384 | `train` |
15
+ | `level1_pantry_plan` | `dev` | 64 | `multi_answer` |
16
+ | `level1_pantry_plan` | `eval` | 128 | `multi_answer` |
17
+ | `level2_graph_coloring` | `train` | 384 | `train` |
18
+ | `level2_graph_coloring` | `dev` | 128 | `multi_answer` |
19
+ | `level2_graph_coloring` | `eval` | 128 | `multi_answer` |
20
+ | `level2_countdown` | `train` | 384 | `train` |
21
+ | `level2_countdown` | `dev` | 128 | `multi_answer` |
22
+ | `level2_countdown` | `eval` | 128 | `multi_answer` |
23
+ | `level2_python_factors` | `train` | 384 | `train` |
24
+ | `level2_python_factors` | `dev` | 128 | `multi_answer` |
25
+ | `level2_python_factors` | `eval` | 128 | `multi_answer` |
26
+ | `level2_mathir` | `train` | 384 | `train` |
27
+ | `level2_mathir` | `dev` | 128 | `multi_answer` |
28
+ | `level2_mathir` | `eval` | 128 | `multi_answer` |
29
+ | `level2_pantry_plan` | `train` | 384 | `train` |
30
+ | `level2_pantry_plan` | `dev` | 128 | `multi_answer` |
31
+ | `level2_pantry_plan` | `eval` | 128 | `multi_answer` |
32
+ | `level3_graph_coloring` | `train` | 384 | `train` |
33
+ | `level3_graph_coloring` | `dev` | 128 | `multi_answer` |
34
+ | `level3_graph_coloring` | `eval` | 128 | `multi_answer` |
35
+ | `level3_countdown` | `train` | 384 | `train` |
36
+ | `level3_countdown` | `dev` | 128 | `multi_answer` |
37
+ | `level3_countdown` | `eval` | 128 | `multi_answer` |
38
+ | `level3_python_factors` | `train` | 384 | `train` |
39
+ | `level3_python_factors` | `dev` | 128 | `multi_answer` |
40
+ | `level3_python_factors` | `eval` | 128 | `multi_answer` |
41
+ | `level3_mathir` | `train` | 384 | `train` |
42
+ | `level3_mathir` | `dev` | 128 | `multi_answer` |
43
+ | `level3_mathir` | `eval` | 128 | `multi_answer` |
44
+ | `level3_pantry_plan` | `train` | 384 | `train` |
45
+ | `level3_pantry_plan` | `dev` | 128 | `multi_answer` |
46
+ | `level3_pantry_plan` | `eval` | 128 | `multi_answer` |
VALIDATION.json ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "all_L2_L3_support_histograms_equal": true,
3
+ "all_primary_problem_identities_disjoint_across_published_splits": true,
4
+ "all_source_files_unchanged": true,
5
+ "config_count": 16,
6
+ "limits": [
7
+ "Canonical problem identities and original structural checks are validated; this export does not regenerate every exhaustive answer catalogue or rerun model admission.",
8
+ "Original source split names and auxiliary Graph unique-answer rows are preserved; no test split is created."
9
+ ],
10
+ "row_count": 9152,
11
+ "schema": "modebench-hf-roundtrip-validation-v1",
12
+ "source_verifier_code_bound_to_completed_confirmation": true,
13
+ "split_count": 42,
14
+ "splits": [
15
+ {
16
+ "canonical_problem_identities_unique": true,
17
+ "config": "level1_graph_coloring",
18
+ "feature_schema_equal": true,
19
+ "frozen_row_digest_verified": false,
20
+ "row_order_equal": true,
21
+ "source_rows_equal_export_rows": true,
22
+ "split": "train"
23
+ },
24
+ {
25
+ "canonical_problem_identities_unique": true,
26
+ "config": "level1_graph_coloring",
27
+ "feature_schema_equal": true,
28
+ "frozen_row_digest_verified": false,
29
+ "row_order_equal": true,
30
+ "source_rows_equal_export_rows": true,
31
+ "split": "eval"
32
+ },
33
+ {
34
+ "canonical_problem_identities_unique": true,
35
+ "config": "level1_graph_coloring_unique_answer",
36
+ "feature_schema_equal": true,
37
+ "frozen_row_digest_verified": false,
38
+ "row_order_equal": true,
39
+ "source_rows_equal_export_rows": true,
40
+ "split": "eval"
41
+ },
42
+ {
43
+ "canonical_problem_identities_unique": true,
44
+ "config": "level1_countdown",
45
+ "feature_schema_equal": true,
46
+ "frozen_row_digest_verified": false,
47
+ "row_order_equal": true,
48
+ "source_rows_equal_export_rows": true,
49
+ "split": "train"
50
+ },
51
+ {
52
+ "canonical_problem_identities_unique": true,
53
+ "config": "level1_countdown",
54
+ "feature_schema_equal": true,
55
+ "frozen_row_digest_verified": false,
56
+ "row_order_equal": true,
57
+ "source_rows_equal_export_rows": true,
58
+ "split": "eval"
59
+ },
60
+ {
61
+ "canonical_problem_identities_unique": true,
62
+ "config": "level1_python_factors",
63
+ "feature_schema_equal": true,
64
+ "frozen_row_digest_verified": false,
65
+ "row_order_equal": true,
66
+ "source_rows_equal_export_rows": true,
67
+ "split": "train"
68
+ },
69
+ {
70
+ "canonical_problem_identities_unique": true,
71
+ "config": "level1_python_factors",
72
+ "feature_schema_equal": true,
73
+ "frozen_row_digest_verified": false,
74
+ "row_order_equal": true,
75
+ "source_rows_equal_export_rows": true,
76
+ "split": "eval"
77
+ },
78
+ {
79
+ "canonical_problem_identities_unique": true,
80
+ "config": "level1_mathir",
81
+ "feature_schema_equal": true,
82
+ "frozen_row_digest_verified": false,
83
+ "row_order_equal": true,
84
+ "source_rows_equal_export_rows": true,
85
+ "split": "train"
86
+ },
87
+ {
88
+ "canonical_problem_identities_unique": true,
89
+ "config": "level1_mathir",
90
+ "feature_schema_equal": true,
91
+ "frozen_row_digest_verified": false,
92
+ "row_order_equal": true,
93
+ "source_rows_equal_export_rows": true,
94
+ "split": "eval"
95
+ },
96
+ {
97
+ "canonical_problem_identities_unique": true,
98
+ "config": "level1_pantry_plan",
99
+ "feature_schema_equal": true,
100
+ "frozen_row_digest_verified": false,
101
+ "row_order_equal": true,
102
+ "source_rows_equal_export_rows": true,
103
+ "split": "train"
104
+ },
105
+ {
106
+ "canonical_problem_identities_unique": true,
107
+ "config": "level1_pantry_plan",
108
+ "feature_schema_equal": true,
109
+ "frozen_row_digest_verified": false,
110
+ "row_order_equal": true,
111
+ "source_rows_equal_export_rows": true,
112
+ "split": "dev"
113
+ },
114
+ {
115
+ "canonical_problem_identities_unique": true,
116
+ "config": "level1_pantry_plan",
117
+ "feature_schema_equal": true,
118
+ "frozen_row_digest_verified": false,
119
+ "row_order_equal": true,
120
+ "source_rows_equal_export_rows": true,
121
+ "split": "eval"
122
+ },
123
+ {
124
+ "canonical_problem_identities_unique": true,
125
+ "config": "level2_graph_coloring",
126
+ "feature_schema_equal": true,
127
+ "frozen_row_digest_verified": true,
128
+ "row_order_equal": true,
129
+ "source_rows_equal_export_rows": true,
130
+ "split": "train"
131
+ },
132
+ {
133
+ "canonical_problem_identities_unique": true,
134
+ "config": "level2_graph_coloring",
135
+ "feature_schema_equal": true,
136
+ "frozen_row_digest_verified": true,
137
+ "row_order_equal": true,
138
+ "source_rows_equal_export_rows": true,
139
+ "split": "dev"
140
+ },
141
+ {
142
+ "canonical_problem_identities_unique": true,
143
+ "config": "level2_graph_coloring",
144
+ "feature_schema_equal": true,
145
+ "frozen_row_digest_verified": true,
146
+ "row_order_equal": true,
147
+ "source_rows_equal_export_rows": true,
148
+ "split": "eval"
149
+ },
150
+ {
151
+ "canonical_problem_identities_unique": true,
152
+ "config": "level2_countdown",
153
+ "feature_schema_equal": true,
154
+ "frozen_row_digest_verified": true,
155
+ "row_order_equal": true,
156
+ "source_rows_equal_export_rows": true,
157
+ "split": "train"
158
+ },
159
+ {
160
+ "canonical_problem_identities_unique": true,
161
+ "config": "level2_countdown",
162
+ "feature_schema_equal": true,
163
+ "frozen_row_digest_verified": true,
164
+ "row_order_equal": true,
165
+ "source_rows_equal_export_rows": true,
166
+ "split": "dev"
167
+ },
168
+ {
169
+ "canonical_problem_identities_unique": true,
170
+ "config": "level2_countdown",
171
+ "feature_schema_equal": true,
172
+ "frozen_row_digest_verified": true,
173
+ "row_order_equal": true,
174
+ "source_rows_equal_export_rows": true,
175
+ "split": "eval"
176
+ },
177
+ {
178
+ "canonical_problem_identities_unique": true,
179
+ "config": "level2_python_factors",
180
+ "feature_schema_equal": true,
181
+ "frozen_row_digest_verified": true,
182
+ "row_order_equal": true,
183
+ "source_rows_equal_export_rows": true,
184
+ "split": "train"
185
+ },
186
+ {
187
+ "canonical_problem_identities_unique": true,
188
+ "config": "level2_python_factors",
189
+ "feature_schema_equal": true,
190
+ "frozen_row_digest_verified": true,
191
+ "row_order_equal": true,
192
+ "source_rows_equal_export_rows": true,
193
+ "split": "dev"
194
+ },
195
+ {
196
+ "canonical_problem_identities_unique": true,
197
+ "config": "level2_python_factors",
198
+ "feature_schema_equal": true,
199
+ "frozen_row_digest_verified": true,
200
+ "row_order_equal": true,
201
+ "source_rows_equal_export_rows": true,
202
+ "split": "eval"
203
+ },
204
+ {
205
+ "canonical_problem_identities_unique": true,
206
+ "config": "level2_mathir",
207
+ "feature_schema_equal": true,
208
+ "frozen_row_digest_verified": true,
209
+ "row_order_equal": true,
210
+ "source_rows_equal_export_rows": true,
211
+ "split": "train"
212
+ },
213
+ {
214
+ "canonical_problem_identities_unique": true,
215
+ "config": "level2_mathir",
216
+ "feature_schema_equal": true,
217
+ "frozen_row_digest_verified": true,
218
+ "row_order_equal": true,
219
+ "source_rows_equal_export_rows": true,
220
+ "split": "dev"
221
+ },
222
+ {
223
+ "canonical_problem_identities_unique": true,
224
+ "config": "level2_mathir",
225
+ "feature_schema_equal": true,
226
+ "frozen_row_digest_verified": true,
227
+ "row_order_equal": true,
228
+ "source_rows_equal_export_rows": true,
229
+ "split": "eval"
230
+ },
231
+ {
232
+ "canonical_problem_identities_unique": true,
233
+ "config": "level2_pantry_plan",
234
+ "feature_schema_equal": true,
235
+ "frozen_row_digest_verified": true,
236
+ "row_order_equal": true,
237
+ "source_rows_equal_export_rows": true,
238
+ "split": "train"
239
+ },
240
+ {
241
+ "canonical_problem_identities_unique": true,
242
+ "config": "level2_pantry_plan",
243
+ "feature_schema_equal": true,
244
+ "frozen_row_digest_verified": true,
245
+ "row_order_equal": true,
246
+ "source_rows_equal_export_rows": true,
247
+ "split": "dev"
248
+ },
249
+ {
250
+ "canonical_problem_identities_unique": true,
251
+ "config": "level2_pantry_plan",
252
+ "feature_schema_equal": true,
253
+ "frozen_row_digest_verified": true,
254
+ "row_order_equal": true,
255
+ "source_rows_equal_export_rows": true,
256
+ "split": "eval"
257
+ },
258
+ {
259
+ "canonical_problem_identities_unique": true,
260
+ "config": "level3_graph_coloring",
261
+ "feature_schema_equal": true,
262
+ "frozen_row_digest_verified": true,
263
+ "row_order_equal": true,
264
+ "source_rows_equal_export_rows": true,
265
+ "split": "train"
266
+ },
267
+ {
268
+ "canonical_problem_identities_unique": true,
269
+ "config": "level3_graph_coloring",
270
+ "feature_schema_equal": true,
271
+ "frozen_row_digest_verified": true,
272
+ "row_order_equal": true,
273
+ "source_rows_equal_export_rows": true,
274
+ "split": "dev"
275
+ },
276
+ {
277
+ "canonical_problem_identities_unique": true,
278
+ "config": "level3_graph_coloring",
279
+ "feature_schema_equal": true,
280
+ "frozen_row_digest_verified": true,
281
+ "row_order_equal": true,
282
+ "source_rows_equal_export_rows": true,
283
+ "split": "eval"
284
+ },
285
+ {
286
+ "canonical_problem_identities_unique": true,
287
+ "config": "level3_countdown",
288
+ "feature_schema_equal": true,
289
+ "frozen_row_digest_verified": true,
290
+ "row_order_equal": true,
291
+ "source_rows_equal_export_rows": true,
292
+ "split": "train"
293
+ },
294
+ {
295
+ "canonical_problem_identities_unique": true,
296
+ "config": "level3_countdown",
297
+ "feature_schema_equal": true,
298
+ "frozen_row_digest_verified": true,
299
+ "row_order_equal": true,
300
+ "source_rows_equal_export_rows": true,
301
+ "split": "dev"
302
+ },
303
+ {
304
+ "canonical_problem_identities_unique": true,
305
+ "config": "level3_countdown",
306
+ "feature_schema_equal": true,
307
+ "frozen_row_digest_verified": true,
308
+ "row_order_equal": true,
309
+ "source_rows_equal_export_rows": true,
310
+ "split": "eval"
311
+ },
312
+ {
313
+ "canonical_problem_identities_unique": true,
314
+ "config": "level3_python_factors",
315
+ "feature_schema_equal": true,
316
+ "frozen_row_digest_verified": true,
317
+ "row_order_equal": true,
318
+ "source_rows_equal_export_rows": true,
319
+ "split": "train"
320
+ },
321
+ {
322
+ "canonical_problem_identities_unique": true,
323
+ "config": "level3_python_factors",
324
+ "feature_schema_equal": true,
325
+ "frozen_row_digest_verified": true,
326
+ "row_order_equal": true,
327
+ "source_rows_equal_export_rows": true,
328
+ "split": "dev"
329
+ },
330
+ {
331
+ "canonical_problem_identities_unique": true,
332
+ "config": "level3_python_factors",
333
+ "feature_schema_equal": true,
334
+ "frozen_row_digest_verified": true,
335
+ "row_order_equal": true,
336
+ "source_rows_equal_export_rows": true,
337
+ "split": "eval"
338
+ },
339
+ {
340
+ "canonical_problem_identities_unique": true,
341
+ "config": "level3_mathir",
342
+ "feature_schema_equal": true,
343
+ "frozen_row_digest_verified": true,
344
+ "row_order_equal": true,
345
+ "source_rows_equal_export_rows": true,
346
+ "split": "train"
347
+ },
348
+ {
349
+ "canonical_problem_identities_unique": true,
350
+ "config": "level3_mathir",
351
+ "feature_schema_equal": true,
352
+ "frozen_row_digest_verified": true,
353
+ "row_order_equal": true,
354
+ "source_rows_equal_export_rows": true,
355
+ "split": "dev"
356
+ },
357
+ {
358
+ "canonical_problem_identities_unique": true,
359
+ "config": "level3_mathir",
360
+ "feature_schema_equal": true,
361
+ "frozen_row_digest_verified": true,
362
+ "row_order_equal": true,
363
+ "source_rows_equal_export_rows": true,
364
+ "split": "eval"
365
+ },
366
+ {
367
+ "canonical_problem_identities_unique": true,
368
+ "config": "level3_pantry_plan",
369
+ "feature_schema_equal": true,
370
+ "frozen_row_digest_verified": true,
371
+ "row_order_equal": true,
372
+ "source_rows_equal_export_rows": true,
373
+ "split": "train"
374
+ },
375
+ {
376
+ "canonical_problem_identities_unique": true,
377
+ "config": "level3_pantry_plan",
378
+ "feature_schema_equal": true,
379
+ "frozen_row_digest_verified": true,
380
+ "row_order_equal": true,
381
+ "source_rows_equal_export_rows": true,
382
+ "split": "dev"
383
+ },
384
+ {
385
+ "canonical_problem_identities_unique": true,
386
+ "config": "level3_pantry_plan",
387
+ "feature_schema_equal": true,
388
+ "frozen_row_digest_verified": true,
389
+ "row_order_equal": true,
390
+ "source_rows_equal_export_rows": true,
391
+ "split": "eval"
392
+ }
393
+ ],
394
+ "status": "passed",
395
+ "validated_at_utc": "2026-09-11T07:38:24.101092+00:00"
396
+ }
code/oat_drgrpo/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Direct MaxEnt-GRPO primitives and the landed xDr.GRPO surrogate."""
code/oat_drgrpo/ant_maze_worker_v10.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hash-bound AntMaze executor for the admitted v10 waypoint controller."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import math
8
+ import os
9
+ from pathlib import Path
10
+ from typing import Any, Mapping
11
+
12
+ from .maze_modebench import (
13
+ ANT_MAZE_VERIFIER,
14
+ parse_maze_action_program,
15
+ parse_maze_action_spec,
16
+ validate_maze_execution,
17
+ )
18
+ from .maze_runtime_identity import maze_runtime_identity
19
+
20
+
21
+ ROOT = Path(
22
+ os.environ.get("OAT_ZERO_REPO_ROOT", Path(__file__).resolve().parents[2])
23
+ ).resolve()
24
+ MODEL_PATH = ROOT / "var/maze_runtime/controllers/ant_waypoint_v10.zip"
25
+ RECEIPT_PATH = (
26
+ ROOT / "var/maze_runtime/controllers/ant_waypoint_v10.evaluation.json"
27
+ )
28
+ TRAINING_IDENTITY_PATH = (
29
+ ROOT / "var/artifacts/ant_waypoint_controller_v10_identity.json"
30
+ )
31
+ WAYPOINT_DISTANCE = 4.0
32
+ WAYPOINT_SUCCESS_THRESHOLD = 0.45
33
+ _MODEL = None
34
+
35
+
36
+ def _sha256(path: Path) -> str:
37
+ digest = hashlib.sha256()
38
+ with path.open("rb") as handle:
39
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
40
+ digest.update(chunk)
41
+ return digest.hexdigest()
42
+
43
+
44
+ def controller_receipt_sha256() -> str:
45
+ controller_identity()
46
+ return _sha256(RECEIPT_PATH)
47
+
48
+
49
+ def controller_identity() -> dict[str, Any]:
50
+ receipt_sha256 = _sha256(RECEIPT_PATH)
51
+ model_sha256 = _sha256(MODEL_PATH)
52
+ training_identity_sha256 = _sha256(TRAINING_IDENTITY_PATH)
53
+ receipt = json.loads(RECEIPT_PATH.read_text(encoding="utf-8"))
54
+ training_identity = json.loads(
55
+ TRAINING_IDENTITY_PATH.read_text(encoding="utf-8")
56
+ )
57
+ if (
58
+ receipt.get("status") != "pass"
59
+ or receipt.get("decision") != "admitted_to_fresh_maze_route_gate_v10"
60
+ ):
61
+ raise RuntimeError("Ant v10 controller is not admitted")
62
+ if receipt.get("seed") != 73010 or receipt.get("timesteps") != 2_000_000:
63
+ raise RuntimeError("Ant v10 receipt differs from its frozen training identity")
64
+ if (
65
+ training_identity.get("job_id") != 30193111
66
+ or training_identity.get("seed") != 73010
67
+ ):
68
+ raise RuntimeError("Ant v10 training identity is not the frozen job")
69
+ checks = receipt.get("checks", {})
70
+ required_checks = {
71
+ "episode_count",
72
+ "success_rate_at_least_0p90",
73
+ "minimum_heading_success_rate_at_least_0p75",
74
+ "minimum_map_success_rate_at_least_0p75",
75
+ "unhealthy_termination_rate_at_most_0p10",
76
+ "median_success_steps_at_most_300",
77
+ "all_metrics_finite",
78
+ }
79
+ if not isinstance(checks, dict) or not required_checks.issubset(checks) or not all(
80
+ checks[key] is True for key in required_checks
81
+ ):
82
+ raise RuntimeError("Ant v10 receipt contains a failed controller check")
83
+ if receipt.get("hashes", {}).get("model_sha256") != model_sha256:
84
+ raise RuntimeError("Ant v10 receipt does not bind the controller model")
85
+ if receipt.get("training_waypoint_distances") != [WAYPOINT_DISTANCE]:
86
+ raise RuntimeError("Ant v10 receipt has a different waypoint distance")
87
+ if receipt.get("waypoint_distance") != WAYPOINT_DISTANCE:
88
+ raise RuntimeError("Ant v10 receipt has a different executor distance")
89
+ if receipt.get("success_threshold") != WAYPOINT_SUCCESS_THRESHOLD:
90
+ raise RuntimeError("Ant v10 receipt has a different waypoint threshold")
91
+ route_identity_path = os.environ.get("OAT_ZERO_PROTOCOL_IDENTITY")
92
+ if route_identity_path:
93
+ route_identity = json.loads(
94
+ Path(route_identity_path).read_text(encoding="utf-8")
95
+ )
96
+ expected = {
97
+ "controller_receipt_sha256": receipt_sha256,
98
+ "controller_model_sha256": model_sha256,
99
+ "controller_training_identity_sha256": training_identity_sha256,
100
+ }
101
+ if route_identity.get("schema_version") != (
102
+ "ant-maze-v10-route-generation-identity-v1"
103
+ ):
104
+ raise RuntimeError("Ant v10 route identity schema mismatch")
105
+ if any(route_identity.get(key) != value for key, value in expected.items()):
106
+ raise RuntimeError("Ant v10 route identity does not bind the controller")
107
+ return receipt
108
+
109
+
110
+ def _model():
111
+ global _MODEL
112
+ controller_identity()
113
+ if _MODEL is None:
114
+ from stable_baselines3 import PPO
115
+
116
+ _MODEL = PPO.load(MODEL_PATH, device="cpu")
117
+ return _MODEL
118
+
119
+
120
+ def _heading(token: str):
121
+ import numpy as np
122
+
123
+ diagonal = 1.0 / math.sqrt(2.0)
124
+ values = {
125
+ "N": (0.0, 1.0), "NE": (diagonal, diagonal), "E": (1.0, 0.0),
126
+ "SE": (diagonal, -diagonal), "S": (0.0, -1.0),
127
+ "SW": (-diagonal, -diagonal), "W": (-1.0, 0.0),
128
+ "NW": (-diagonal, diagonal),
129
+ }
130
+ return np.asarray(values[token], dtype=np.float32)
131
+
132
+
133
+ def execute_ant_v10_raw(candidate: str, raw_spec: Mapping[str, Any]) -> dict[str, Any]:
134
+ import gymnasium as gym
135
+ import gymnasium_robotics
136
+ import numpy as np
137
+
138
+ gym.register_envs(gymnasium_robotics)
139
+ spec = parse_maze_action_spec(raw_spec)
140
+ if spec.verifier != ANT_MAZE_VERIFIER:
141
+ raise ValueError("AntMaze executor received a non-AntMaze spec")
142
+ runtime = maze_runtime_identity()
143
+ if spec.environment_sha256 != runtime["ant_environment_sha256"]:
144
+ raise ValueError("AntMaze environment hash differs from installed runtime")
145
+ if spec.controller_sha256 != controller_receipt_sha256():
146
+ raise ValueError("AntMaze controller hash differs from frozen v10 receipt")
147
+ tokens = parse_maze_action_program(candidate, spec)
148
+ model = _model()
149
+ env = gym.make(
150
+ spec.environment_id,
151
+ maze_map=[list(row) for row in spec.maze_map],
152
+ reward_type="sparse",
153
+ continuing_task=False,
154
+ reset_target=False,
155
+ max_episode_steps=len(tokens) * spec.action_repeat,
156
+ )
157
+ try:
158
+ env.unwrapped.position_noise_range = 0.0
159
+ observation, info = env.reset(
160
+ seed=spec.reset_seed,
161
+ options={"reset_cell": list(spec.reset_cell), "goal_cell": list(spec.goal_cell)},
162
+ )
163
+ trajectory = [observation["achieved_goal"].astype(float).tolist()]
164
+ success = bool(info.get("success", False))
165
+ simulator_steps = 0
166
+ terminated = truncated = False
167
+ for token in tokens:
168
+ current = np.asarray(env.unwrapped.data.qpos[:2], dtype=np.float32)
169
+ target = current + WAYPOINT_DISTANCE * _heading(token)
170
+ for _ in range(spec.action_repeat):
171
+ current = np.asarray(env.unwrapped.data.qpos[:2], dtype=np.float32)
172
+ relative = np.clip((target - current) / WAYPOINT_DISTANCE, -1.0, 1.0)
173
+ controller_input = np.concatenate([
174
+ np.asarray(observation["observation"], dtype=np.float32), relative,
175
+ ])
176
+ action, _ = model.predict(controller_input, deterministic=True)
177
+ observation, _reward, terminated, truncated, info = env.step(action)
178
+ simulator_steps += 1
179
+ trajectory.append(observation["achieved_goal"].astype(float).tolist())
180
+ success = bool(info.get("success", False))
181
+ current = np.asarray(env.unwrapped.data.qpos[:2], dtype=np.float32)
182
+ waypoint_reached = float(np.linalg.norm(target - current)) <= WAYPOINT_SUCCESS_THRESHOLD
183
+ if success or waypoint_reached or terminated or truncated:
184
+ break
185
+ if success or terminated or truncated:
186
+ break
187
+ distance = float(np.linalg.norm(
188
+ observation["achieved_goal"] - observation["desired_goal"]
189
+ ))
190
+ finally:
191
+ env.close()
192
+ return {
193
+ "environment_sha256": spec.environment_sha256,
194
+ "controller_sha256": spec.controller_sha256,
195
+ "spec_sha256": spec.spec_sha256,
196
+ "reset_seed": spec.reset_seed,
197
+ "action_tokens": list(tokens),
198
+ "success": success,
199
+ "final_goal_distance": distance,
200
+ "trajectory_xy": trajectory,
201
+ "simulator_steps": simulator_steps,
202
+ }
203
+
204
+
205
+ def execute_ant_v10(candidate: str, raw_spec: Mapping[str, Any]):
206
+ execution = execute_ant_v10_raw(candidate, raw_spec)
207
+ return validate_maze_execution(candidate, raw_spec, execution), execution
code/oat_drgrpo/ant_maze_worker_v11.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hash-bound AntMaze executor for the admitted v11 waypoint controller."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ from typing import Any, Mapping
10
+
11
+ from . import ant_maze_worker_v10 as base
12
+
13
+
14
+ ROOT = base.ROOT
15
+ MODEL_PATH = ROOT / "var/maze_runtime/controllers/ant_waypoint_v11.zip"
16
+ RECEIPT_PATH = ROOT / "var/maze_runtime/controllers/ant_waypoint_v11.evaluation.json"
17
+ TRAINING_IDENTITY_PATH = ROOT / "var/artifacts/ant_waypoint_controller_v11_identity.json"
18
+ WAYPOINT_DISTANCE = base.WAYPOINT_DISTANCE
19
+ WAYPOINT_SUCCESS_THRESHOLD = base.WAYPOINT_SUCCESS_THRESHOLD
20
+
21
+
22
+ def _sha256(path: Path) -> str:
23
+ digest = hashlib.sha256()
24
+ with path.open("rb") as handle:
25
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
26
+ digest.update(chunk)
27
+ return digest.hexdigest()
28
+
29
+
30
+ def controller_receipt_sha256() -> str:
31
+ controller_identity()
32
+ return _sha256(RECEIPT_PATH)
33
+
34
+
35
+ def controller_identity() -> dict[str, Any]:
36
+ receipt_sha256 = _sha256(RECEIPT_PATH)
37
+ model_sha256 = _sha256(MODEL_PATH)
38
+ training_identity_sha256 = _sha256(TRAINING_IDENTITY_PATH)
39
+ receipt = json.loads(RECEIPT_PATH.read_text(encoding="utf-8"))
40
+ training_identity = json.loads(TRAINING_IDENTITY_PATH.read_text(encoding="utf-8"))
41
+ if receipt.get("status") != "pass" or receipt.get("decision") != "admitted_to_fresh_maze_route_gate_v11":
42
+ raise RuntimeError("Ant v11 controller is not admitted")
43
+ if receipt.get("seed") != 73011 or receipt.get("timesteps") != 2_000_000:
44
+ raise RuntimeError("Ant v11 receipt differs from its frozen training identity")
45
+ if training_identity.get("job_id") != 30198291 or training_identity.get("seed") != 73011:
46
+ raise RuntimeError("Ant v11 training identity is not the frozen job")
47
+ checks = receipt.get("checks", {})
48
+ required_checks = {
49
+ "episode_count", "success_rate_at_least_0p90",
50
+ "minimum_heading_success_rate_at_least_0p75",
51
+ "minimum_map_success_rate_at_least_0p75",
52
+ "unhealthy_termination_rate_at_most_0p10",
53
+ "median_success_steps_at_most_300", "all_metrics_finite",
54
+ }
55
+ if not isinstance(checks, dict) or not required_checks.issubset(checks) or not all(checks[key] is True for key in required_checks):
56
+ raise RuntimeError("Ant v11 receipt contains a failed controller check")
57
+ if receipt.get("hashes", {}).get("model_sha256") != model_sha256:
58
+ raise RuntimeError("Ant v11 receipt does not bind the controller model")
59
+ if receipt.get("training_waypoint_distances") != [WAYPOINT_DISTANCE] or receipt.get("waypoint_distance") != WAYPOINT_DISTANCE:
60
+ raise RuntimeError("Ant v11 receipt has a different waypoint distance")
61
+ if receipt.get("success_threshold") != WAYPOINT_SUCCESS_THRESHOLD:
62
+ raise RuntimeError("Ant v11 receipt has a different waypoint threshold")
63
+ route_identity_path = os.environ.get("OAT_ZERO_PROTOCOL_IDENTITY")
64
+ if route_identity_path:
65
+ route_identity = json.loads(Path(route_identity_path).read_text(encoding="utf-8"))
66
+ expected = {
67
+ "controller_receipt_sha256": receipt_sha256,
68
+ "controller_model_sha256": model_sha256,
69
+ "controller_training_identity_sha256": training_identity_sha256,
70
+ }
71
+ if route_identity.get("schema_version") != "ant-maze-v11-route-generation-identity-v1":
72
+ raise RuntimeError("Ant v11 route identity schema mismatch")
73
+ if any(route_identity.get(key) != value for key, value in expected.items()):
74
+ raise RuntimeError("Ant v11 route identity does not bind the controller")
75
+ return receipt
76
+
77
+
78
+ base.MODEL_PATH = MODEL_PATH
79
+ base.RECEIPT_PATH = RECEIPT_PATH
80
+ base.TRAINING_IDENTITY_PATH = TRAINING_IDENTITY_PATH
81
+ base.controller_identity = controller_identity
82
+ base.controller_receipt_sha256 = controller_receipt_sha256
83
+ base._MODEL = None
84
+
85
+
86
+ def execute_ant_v11_raw(candidate: str, raw_spec: Mapping[str, Any]) -> dict[str, Any]:
87
+ return base.execute_ant_v10_raw(candidate, raw_spec)
88
+
89
+
90
+ def execute_ant_v11(candidate: str, raw_spec: Mapping[str, Any]):
91
+ return base.execute_ant_v10(candidate, raw_spec)
code/oat_drgrpo/ant_maze_worker_v12.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Grid-anchored AntMaze executor for the admitted v11 controller."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import math
8
+ import os
9
+ from pathlib import Path
10
+ from typing import Any, Mapping
11
+
12
+ from . import ant_maze_worker_v10 as executor
13
+ from .maze_modebench import (
14
+ ANT_MAZE_VERIFIER,
15
+ parse_maze_action_program,
16
+ parse_maze_action_spec,
17
+ validate_maze_execution,
18
+ )
19
+ from .maze_runtime_identity import maze_runtime_identity
20
+
21
+
22
+ ROOT = executor.ROOT
23
+ MODEL_PATH = ROOT / "var/maze_runtime/controllers/ant_waypoint_v11.zip"
24
+ RECEIPT_PATH = (
25
+ ROOT / "var/maze_runtime/controllers/ant_waypoint_v11.evaluation.json"
26
+ )
27
+ TRAINING_IDENTITY_PATH = (
28
+ ROOT / "var/artifacts/ant_waypoint_controller_v11_identity.json"
29
+ )
30
+ WAYPOINT_DISTANCE = 4.0
31
+ WAYPOINT_SUCCESS_THRESHOLD = 0.45
32
+ TARGETING_VERSION = "initial-grid-cumulative-v12"
33
+
34
+
35
+ def _sha256(path: Path) -> str:
36
+ digest = hashlib.sha256()
37
+ with path.open("rb") as handle:
38
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
39
+ digest.update(chunk)
40
+ return digest.hexdigest()
41
+
42
+
43
+ def _canonical_sha256(value: Any) -> str:
44
+ return hashlib.sha256(
45
+ json.dumps(
46
+ value,
47
+ allow_nan=False,
48
+ ensure_ascii=True,
49
+ separators=(",", ":"),
50
+ sort_keys=True,
51
+ ).encode("ascii")
52
+ ).hexdigest()
53
+
54
+
55
+ def _executor_identity() -> dict[str, Any]:
56
+ return {
57
+ "targeting_version": TARGETING_VERSION,
58
+ "worker_source_sha256": _sha256(Path(__file__)),
59
+ "controller_receipt_sha256": _sha256(RECEIPT_PATH),
60
+ "controller_model_sha256": _sha256(MODEL_PATH),
61
+ "controller_training_identity_sha256": _sha256(TRAINING_IDENTITY_PATH),
62
+ "waypoint_distance": WAYPOINT_DISTANCE,
63
+ "waypoint_success_threshold": WAYPOINT_SUCCESS_THRESHOLD,
64
+ }
65
+
66
+
67
+ def controller_receipt_sha256() -> str:
68
+ controller_identity()
69
+ return _canonical_sha256(_executor_identity())
70
+
71
+
72
+ def controller_identity() -> dict[str, Any]:
73
+ receipt = json.loads(RECEIPT_PATH.read_text(encoding="utf-8"))
74
+ training_identity = json.loads(
75
+ TRAINING_IDENTITY_PATH.read_text(encoding="utf-8")
76
+ )
77
+ if (
78
+ receipt.get("status") != "pass"
79
+ or receipt.get("decision") != "admitted_to_fresh_maze_route_gate_v11"
80
+ or receipt.get("seed") != 73011
81
+ or receipt.get("timesteps") != 2_000_000
82
+ ):
83
+ raise RuntimeError("Ant v12 requires the exact admitted v11 controller")
84
+ if (
85
+ training_identity.get("job_id") != 30198291
86
+ or training_identity.get("seed") != 73011
87
+ ):
88
+ raise RuntimeError("Ant v12 training identity differs from admitted v11")
89
+ checks = receipt.get("checks", {})
90
+ if not isinstance(checks, dict) or not checks or not all(
91
+ value is True for value in checks.values()
92
+ ):
93
+ raise RuntimeError("Ant v12 received a failed v11 controller check")
94
+ if receipt.get("hashes", {}).get("model_sha256") != _sha256(MODEL_PATH):
95
+ raise RuntimeError("Ant v12 receipt does not bind the v11 model")
96
+ if (
97
+ receipt.get("training_waypoint_distances") != [WAYPOINT_DISTANCE]
98
+ or receipt.get("waypoint_distance") != WAYPOINT_DISTANCE
99
+ or receipt.get("success_threshold") != WAYPOINT_SUCCESS_THRESHOLD
100
+ ):
101
+ raise RuntimeError("Ant v12 local waypoint contract drift")
102
+ route_identity_path = os.environ.get("OAT_ZERO_PROTOCOL_IDENTITY")
103
+ if route_identity_path:
104
+ route_identity = json.loads(
105
+ Path(route_identity_path).read_text(encoding="utf-8")
106
+ )
107
+ expected = _executor_identity()
108
+ if route_identity.get("schema_version") != (
109
+ "ant-maze-v12-route-generation-identity-v1"
110
+ ):
111
+ raise RuntimeError("Ant v12 route identity schema mismatch")
112
+ for key, value in expected.items():
113
+ if route_identity.get(key) != value:
114
+ raise RuntimeError(f"Ant v12 route identity does not bind {key}")
115
+ return receipt
116
+
117
+
118
+ def _model():
119
+ executor.MODEL_PATH = MODEL_PATH
120
+ executor.RECEIPT_PATH = RECEIPT_PATH
121
+ executor.TRAINING_IDENTITY_PATH = TRAINING_IDENTITY_PATH
122
+ executor.controller_identity = controller_identity
123
+ executor.controller_receipt_sha256 = controller_receipt_sha256
124
+ return executor._model()
125
+
126
+
127
+ def _heading(token: str):
128
+ import numpy as np
129
+
130
+ diagonal = 1.0 / math.sqrt(2.0)
131
+ return np.asarray(
132
+ {
133
+ "N": (0.0, 1.0),
134
+ "NE": (diagonal, diagonal),
135
+ "E": (1.0, 0.0),
136
+ "SE": (diagonal, -diagonal),
137
+ "S": (0.0, -1.0),
138
+ "SW": (-diagonal, -diagonal),
139
+ "W": (-1.0, 0.0),
140
+ "NW": (-diagonal, diagonal),
141
+ }[token],
142
+ dtype=np.float32,
143
+ )
144
+
145
+
146
+ def execute_ant_v12_raw(candidate: str, raw_spec: Mapping[str, Any]) -> dict[str, Any]:
147
+ import gymnasium as gym
148
+ import gymnasium_robotics
149
+ import numpy as np
150
+
151
+ gym.register_envs(gymnasium_robotics)
152
+ spec = parse_maze_action_spec(raw_spec)
153
+ if spec.verifier != ANT_MAZE_VERIFIER:
154
+ raise ValueError("AntMaze v12 received a non-AntMaze spec")
155
+ runtime = maze_runtime_identity()
156
+ if spec.environment_sha256 != runtime["ant_environment_sha256"]:
157
+ raise ValueError("AntMaze environment hash differs from installed runtime")
158
+ if spec.controller_sha256 != controller_receipt_sha256():
159
+ raise ValueError("AntMaze controller hash differs from frozen v12 executor")
160
+ tokens = parse_maze_action_program(candidate, spec)
161
+ model = _model()
162
+ env = gym.make(
163
+ spec.environment_id,
164
+ maze_map=[list(row) for row in spec.maze_map],
165
+ reward_type="sparse",
166
+ continuing_task=False,
167
+ reset_target=False,
168
+ max_episode_steps=len(tokens) * spec.action_repeat,
169
+ )
170
+ segment_steps = []
171
+ nominal_targets = []
172
+ try:
173
+ env.unwrapped.position_noise_range = 0.0
174
+ observation, info = env.reset(
175
+ seed=spec.reset_seed,
176
+ options={
177
+ "reset_cell": list(spec.reset_cell),
178
+ "goal_cell": list(spec.goal_cell),
179
+ },
180
+ )
181
+ initial = np.asarray(env.unwrapped.data.qpos[:2], dtype=np.float32).copy()
182
+ cumulative_heading = np.zeros(2, dtype=np.float32)
183
+ trajectory = [observation["achieved_goal"].astype(float).tolist()]
184
+ success = bool(info.get("success", False))
185
+ simulator_steps = 0
186
+ terminated = truncated = False
187
+ for token in tokens:
188
+ cumulative_heading += _heading(token)
189
+ target = initial + WAYPOINT_DISTANCE * cumulative_heading
190
+ nominal_targets.append(target.astype(float).tolist())
191
+ before_segment = simulator_steps
192
+ for _ in range(spec.action_repeat):
193
+ current = np.asarray(
194
+ env.unwrapped.data.qpos[:2], dtype=np.float32
195
+ )
196
+ relative = np.clip(
197
+ (target - current) / WAYPOINT_DISTANCE, -1.0, 1.0
198
+ )
199
+ controller_input = np.concatenate(
200
+ [
201
+ np.asarray(observation["observation"], dtype=np.float32),
202
+ relative,
203
+ ]
204
+ )
205
+ action, _ = model.predict(controller_input, deterministic=True)
206
+ observation, _reward, terminated, truncated, info = env.step(action)
207
+ simulator_steps += 1
208
+ trajectory.append(
209
+ observation["achieved_goal"].astype(float).tolist()
210
+ )
211
+ success = bool(info.get("success", False))
212
+ current = np.asarray(
213
+ env.unwrapped.data.qpos[:2], dtype=np.float32
214
+ )
215
+ waypoint_reached = float(np.linalg.norm(target - current)) <= (
216
+ WAYPOINT_SUCCESS_THRESHOLD
217
+ )
218
+ if success or waypoint_reached or terminated or truncated:
219
+ break
220
+ segment_steps.append(simulator_steps - before_segment)
221
+ if success or terminated or truncated:
222
+ break
223
+ distance = float(
224
+ np.linalg.norm(
225
+ observation["achieved_goal"] - observation["desired_goal"]
226
+ )
227
+ )
228
+ finally:
229
+ env.close()
230
+ return {
231
+ "environment_sha256": spec.environment_sha256,
232
+ "controller_sha256": spec.controller_sha256,
233
+ "spec_sha256": spec.spec_sha256,
234
+ "reset_seed": spec.reset_seed,
235
+ "action_tokens": list(tokens),
236
+ "targeting_version": TARGETING_VERSION,
237
+ "nominal_targets_xy": nominal_targets,
238
+ "segment_steps": segment_steps,
239
+ "success": success,
240
+ "final_goal_distance": distance,
241
+ "trajectory_xy": trajectory,
242
+ "simulator_steps": simulator_steps,
243
+ }
244
+
245
+
246
+ def execute_ant_v12(candidate: str, raw_spec: Mapping[str, Any]):
247
+ execution = execute_ant_v12_raw(candidate, raw_spec)
248
+ return validate_maze_execution(candidate, raw_spec, execution), execution
code/oat_drgrpo/ant_maze_worker_v5.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hash-bound AntMaze executor for the admitted v5 macro controller."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ from typing import Any, Mapping
10
+
11
+ from .maze_modebench import (
12
+ ANT_MAZE_VERIFIER,
13
+ parse_maze_action_program,
14
+ parse_maze_action_spec,
15
+ validate_maze_execution,
16
+ )
17
+ from .maze_runtime_identity import maze_runtime_identity
18
+
19
+
20
+ ROOT = Path(
21
+ os.environ.get("OAT_ZERO_REPO_ROOT", Path(__file__).resolve().parents[2])
22
+ ).resolve()
23
+ MODEL_PATH = ROOT / "var/maze_runtime/controllers/ant_heading_v1.zip"
24
+ RECEIPT_PATH = ROOT / "var/maze_runtime/controllers/ant_heading_v5.evaluation.json"
25
+ RECEIPT_SHA256 = (
26
+ "324d3301b8e21b4dbbfcc2e6b9a87aba479bd2da5aa3a040cff24adebaf8828e"
27
+ )
28
+ MODEL_SHA256 = (
29
+ "526b669bb14cf8a07b44a1c725f94411632a3ac8a8e84966db09336cc96e4b0f"
30
+ )
31
+ _MODEL = None
32
+
33
+
34
+ def _sha256(path: Path) -> str:
35
+ digest = hashlib.sha256()
36
+ with path.open("rb") as handle:
37
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
38
+ digest.update(chunk)
39
+ return digest.hexdigest()
40
+
41
+
42
+ def controller_identity() -> dict[str, Any]:
43
+ """Load and verify the immutable v5 controller receipt."""
44
+
45
+ if _sha256(RECEIPT_PATH) != RECEIPT_SHA256:
46
+ raise RuntimeError("Ant v5 controller receipt hash mismatch")
47
+ receipt = json.loads(RECEIPT_PATH.read_text(encoding="utf-8"))
48
+ if receipt.get("status") != "pass":
49
+ raise RuntimeError("Ant v5 controller is not admitted")
50
+ if _sha256(MODEL_PATH) != MODEL_SHA256:
51
+ raise RuntimeError("Ant v5 controller model hash mismatch")
52
+ if receipt.get("hashes", {}).get("model_sha256") != MODEL_SHA256:
53
+ raise RuntimeError("Ant v5 receipt does not bind the controller model")
54
+ return receipt
55
+
56
+
57
+ def _model():
58
+ global _MODEL
59
+ receipt = controller_identity()
60
+ if _MODEL is None:
61
+ from stable_baselines3 import PPO
62
+
63
+ _MODEL = PPO.load(MODEL_PATH, device="cpu")
64
+ return _MODEL, receipt["macro_identity"]
65
+
66
+
67
+ def execute_ant_v5_raw(
68
+ candidate: str,
69
+ raw_spec: Mapping[str, Any],
70
+ ) -> dict[str, Any]:
71
+ """Execute one program and retain its raw record even on goal failure."""
72
+
73
+ import gymnasium as gym
74
+ import gymnasium_robotics
75
+ import numpy as np
76
+
77
+ gym.register_envs(gymnasium_robotics)
78
+ spec = parse_maze_action_spec(raw_spec)
79
+ if spec.verifier != ANT_MAZE_VERIFIER:
80
+ raise ValueError("AntMaze executor received a non-AntMaze spec")
81
+ runtime = maze_runtime_identity()
82
+ if spec.environment_sha256 != runtime["ant_environment_sha256"]:
83
+ raise ValueError("AntMaze environment hash differs from installed runtime")
84
+ if spec.controller_sha256 != RECEIPT_SHA256:
85
+ raise ValueError("AntMaze controller hash differs from frozen v5 receipt")
86
+ tokens = parse_maze_action_program(candidate, spec)
87
+ model, identity = _model()
88
+ names = tuple(str(value) for value in identity["command_names"])
89
+ commands = np.asarray(identity["commands"], dtype=np.float32)
90
+ macros = tuple(
91
+ tuple(int(index) for index in macro) for macro in identity["macros"]
92
+ )
93
+ token_to_index = {name: index for index, name in enumerate(names)}
94
+ if tuple(token_to_index) != spec.action_tokens:
95
+ raise RuntimeError("Ant v5 macro alphabet differs from the maze spec")
96
+
97
+ env = gym.make(
98
+ spec.environment_id,
99
+ maze_map=[list(row) for row in spec.maze_map],
100
+ reward_type="sparse",
101
+ continuing_task=False,
102
+ reset_target=False,
103
+ max_episode_steps=len(tokens) * spec.action_repeat,
104
+ )
105
+ try:
106
+ env.unwrapped.position_noise_range = 0.0
107
+ observation, info = env.reset(
108
+ seed=spec.reset_seed,
109
+ options={
110
+ "reset_cell": list(spec.reset_cell),
111
+ "goal_cell": list(spec.goal_cell),
112
+ },
113
+ )
114
+ trajectory = [observation["achieved_goal"].astype(float).tolist()]
115
+ success = bool(info.get("success", False))
116
+ simulator_steps = 0
117
+ terminated = truncated = False
118
+ for token in tokens:
119
+ macro = macros[token_to_index[token]]
120
+ for primitive_step in range(spec.action_repeat):
121
+ segment = min(
122
+ primitive_step * len(macro) // spec.action_repeat,
123
+ len(macro) - 1,
124
+ )
125
+ command = commands[macro[segment]]
126
+ controller_input = np.concatenate(
127
+ [
128
+ np.asarray(observation["observation"], dtype=np.float32),
129
+ command,
130
+ ]
131
+ )
132
+ action, _ = model.predict(controller_input, deterministic=True)
133
+ observation, _reward, terminated, truncated, info = env.step(
134
+ action
135
+ )
136
+ simulator_steps += 1
137
+ trajectory.append(
138
+ observation["achieved_goal"].astype(float).tolist()
139
+ )
140
+ success = bool(info.get("success", False))
141
+ if success or terminated or truncated:
142
+ break
143
+ if success or terminated or truncated:
144
+ break
145
+ distance = float(
146
+ np.linalg.norm(
147
+ observation["achieved_goal"] - observation["desired_goal"]
148
+ )
149
+ )
150
+ finally:
151
+ env.close()
152
+ execution = {
153
+ "environment_sha256": spec.environment_sha256,
154
+ "controller_sha256": spec.controller_sha256,
155
+ "spec_sha256": spec.spec_sha256,
156
+ "reset_seed": spec.reset_seed,
157
+ "action_tokens": list(tokens),
158
+ "success": success,
159
+ "final_goal_distance": distance,
160
+ "trajectory_xy": trajectory,
161
+ "simulator_steps": simulator_steps,
162
+ }
163
+ return execution
164
+
165
+
166
+ def execute_ant_v5(candidate: str, raw_spec: Mapping[str, Any]):
167
+ """Execute and validate one program in the pinned AntMaze runtime."""
168
+
169
+ execution = execute_ant_v5_raw(candidate, raw_spec)
170
+ return validate_maze_execution(candidate, raw_spec, execution), execution
code/oat_drgrpo/ant_maze_worker_v8.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hash-bound AntMaze executor for the admitted v8 waypoint controller."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import math
8
+ import os
9
+ from pathlib import Path
10
+ from typing import Any, Mapping
11
+
12
+ from .maze_modebench import (
13
+ ANT_MAZE_VERIFIER,
14
+ parse_maze_action_program,
15
+ parse_maze_action_spec,
16
+ validate_maze_execution,
17
+ )
18
+ from .maze_runtime_identity import maze_runtime_identity
19
+
20
+
21
+ ROOT = Path(
22
+ os.environ.get("OAT_ZERO_REPO_ROOT", Path(__file__).resolve().parents[2])
23
+ ).resolve()
24
+ MODEL_PATH = ROOT / "var/maze_runtime/controllers/ant_waypoint_v8.zip"
25
+ RECEIPT_PATH = (
26
+ ROOT / "var/maze_runtime/controllers/ant_waypoint_v8.evaluation.json"
27
+ )
28
+ RECEIPT_SHA256 = (
29
+ "fc2961d74a1fdfc8f3d2c1936ea61041cff65333ada0e6ebcd571b44919b18f1"
30
+ )
31
+ MODEL_SHA256 = (
32
+ "77e780dfff1147bc2f542c1761f6efeaa2305fd5ddb625244ebf8e82b3fa871d"
33
+ )
34
+ WAYPOINT_DISTANCE = 4.0
35
+ WAYPOINT_SUCCESS_THRESHOLD = 0.45
36
+ _MODEL = None
37
+
38
+
39
+ def _sha256(path: Path) -> str:
40
+ digest = hashlib.sha256()
41
+ with path.open("rb") as handle:
42
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
43
+ digest.update(chunk)
44
+ return digest.hexdigest()
45
+
46
+
47
+ def controller_identity() -> dict[str, Any]:
48
+ """Load and verify the immutable v8 controller receipt and model."""
49
+
50
+ if _sha256(RECEIPT_PATH) != RECEIPT_SHA256:
51
+ raise RuntimeError("Ant v8 controller receipt hash mismatch")
52
+ receipt = json.loads(RECEIPT_PATH.read_text(encoding="utf-8"))
53
+ if (
54
+ receipt.get("status") != "pass"
55
+ or receipt.get("decision") != "admitted_to_fresh_maze_route_gate_v8"
56
+ ):
57
+ raise RuntimeError("Ant v8 controller is not admitted")
58
+ if _sha256(MODEL_PATH) != MODEL_SHA256:
59
+ raise RuntimeError("Ant v8 controller model hash mismatch")
60
+ if receipt.get("hashes", {}).get("model_sha256") != MODEL_SHA256:
61
+ raise RuntimeError("Ant v8 receipt does not bind the controller model")
62
+ if receipt.get("training_waypoint_distances") != [WAYPOINT_DISTANCE]:
63
+ raise RuntimeError("Ant v8 receipt has a different waypoint distance")
64
+ if receipt.get("success_threshold") != WAYPOINT_SUCCESS_THRESHOLD:
65
+ raise RuntimeError("Ant v8 receipt has a different waypoint threshold")
66
+ return receipt
67
+
68
+
69
+ def _model():
70
+ global _MODEL
71
+ controller_identity()
72
+ if _MODEL is None:
73
+ from stable_baselines3 import PPO
74
+
75
+ _MODEL = PPO.load(MODEL_PATH, device="cpu")
76
+ return _MODEL
77
+
78
+
79
+ def _heading(token: str):
80
+ import numpy as np
81
+
82
+ diagonal = 1.0 / math.sqrt(2.0)
83
+ values = {
84
+ "N": (0.0, 1.0),
85
+ "NE": (diagonal, diagonal),
86
+ "E": (1.0, 0.0),
87
+ "SE": (diagonal, -diagonal),
88
+ "S": (0.0, -1.0),
89
+ "SW": (-diagonal, -diagonal),
90
+ "W": (-1.0, 0.0),
91
+ "NW": (-diagonal, diagonal),
92
+ }
93
+ return np.asarray(values[token], dtype=np.float32)
94
+
95
+
96
+ def execute_ant_v8_raw(
97
+ candidate: str,
98
+ raw_spec: Mapping[str, Any],
99
+ ) -> dict[str, Any]:
100
+ """Execute commands as successive four-unit relative waypoint targets."""
101
+
102
+ import gymnasium as gym
103
+ import gymnasium_robotics
104
+ import numpy as np
105
+
106
+ gym.register_envs(gymnasium_robotics)
107
+ spec = parse_maze_action_spec(raw_spec)
108
+ if spec.verifier != ANT_MAZE_VERIFIER:
109
+ raise ValueError("AntMaze executor received a non-AntMaze spec")
110
+ runtime = maze_runtime_identity()
111
+ if spec.environment_sha256 != runtime["ant_environment_sha256"]:
112
+ raise ValueError("AntMaze environment hash differs from installed runtime")
113
+ if spec.controller_sha256 != RECEIPT_SHA256:
114
+ raise ValueError("AntMaze controller hash differs from frozen v8 receipt")
115
+ tokens = parse_maze_action_program(candidate, spec)
116
+ model = _model()
117
+
118
+ env = gym.make(
119
+ spec.environment_id,
120
+ maze_map=[list(row) for row in spec.maze_map],
121
+ reward_type="sparse",
122
+ continuing_task=False,
123
+ reset_target=False,
124
+ max_episode_steps=len(tokens) * spec.action_repeat,
125
+ )
126
+ try:
127
+ env.unwrapped.position_noise_range = 0.0
128
+ observation, info = env.reset(
129
+ seed=spec.reset_seed,
130
+ options={
131
+ "reset_cell": list(spec.reset_cell),
132
+ "goal_cell": list(spec.goal_cell),
133
+ },
134
+ )
135
+ trajectory = [observation["achieved_goal"].astype(float).tolist()]
136
+ success = bool(info.get("success", False))
137
+ simulator_steps = 0
138
+ terminated = truncated = False
139
+ for token in tokens:
140
+ current = np.asarray(env.unwrapped.data.qpos[:2], dtype=np.float32)
141
+ target = current + WAYPOINT_DISTANCE * _heading(token)
142
+ waypoint_reached = False
143
+ for _ in range(spec.action_repeat):
144
+ current = np.asarray(env.unwrapped.data.qpos[:2], dtype=np.float32)
145
+ relative = np.clip(
146
+ (target - current) / WAYPOINT_DISTANCE,
147
+ -1.0,
148
+ 1.0,
149
+ )
150
+ controller_input = np.concatenate(
151
+ [
152
+ np.asarray(observation["observation"], dtype=np.float32),
153
+ relative,
154
+ ]
155
+ )
156
+ action, _ = model.predict(controller_input, deterministic=True)
157
+ observation, _reward, terminated, truncated, info = env.step(action)
158
+ simulator_steps += 1
159
+ trajectory.append(
160
+ observation["achieved_goal"].astype(float).tolist()
161
+ )
162
+ success = bool(info.get("success", False))
163
+ current = np.asarray(env.unwrapped.data.qpos[:2], dtype=np.float32)
164
+ waypoint_reached = (
165
+ float(np.linalg.norm(target - current))
166
+ <= WAYPOINT_SUCCESS_THRESHOLD
167
+ )
168
+ if success or waypoint_reached or terminated or truncated:
169
+ break
170
+ if success or terminated or truncated:
171
+ break
172
+ distance = float(
173
+ np.linalg.norm(
174
+ observation["achieved_goal"] - observation["desired_goal"]
175
+ )
176
+ )
177
+ finally:
178
+ env.close()
179
+ return {
180
+ "environment_sha256": spec.environment_sha256,
181
+ "controller_sha256": spec.controller_sha256,
182
+ "spec_sha256": spec.spec_sha256,
183
+ "reset_seed": spec.reset_seed,
184
+ "action_tokens": list(tokens),
185
+ "success": success,
186
+ "final_goal_distance": distance,
187
+ "trajectory_xy": trajectory,
188
+ "simulator_steps": simulator_steps,
189
+ }
190
+
191
+
192
+ def execute_ant_v8(candidate: str, raw_spec: Mapping[str, Any]):
193
+ """Execute and validate one v8 program in the pinned AntMaze runtime."""
194
+
195
+ execution = execute_ant_v8_raw(candidate, raw_spec)
196
+ return validate_maze_execution(candidate, raw_spec, execution), execution
code/oat_drgrpo/ant_maze_worker_v9.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hash-bound AntMaze executor for the admitted v9 waypoint controller."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import math
8
+ import os
9
+ from pathlib import Path
10
+ from typing import Any, Mapping
11
+
12
+ from .maze_modebench import (
13
+ ANT_MAZE_VERIFIER,
14
+ parse_maze_action_program,
15
+ parse_maze_action_spec,
16
+ validate_maze_execution,
17
+ )
18
+ from .maze_runtime_identity import maze_runtime_identity
19
+
20
+
21
+ ROOT = Path(
22
+ os.environ.get("OAT_ZERO_REPO_ROOT", Path(__file__).resolve().parents[2])
23
+ ).resolve()
24
+ MODEL_PATH = ROOT / "var/maze_runtime/controllers/ant_waypoint_v9.zip"
25
+ RECEIPT_PATH = (
26
+ ROOT / "var/maze_runtime/controllers/ant_waypoint_v9.evaluation.json"
27
+ )
28
+ TRAINING_IDENTITY_PATH = (
29
+ ROOT / "var/artifacts/ant_waypoint_controller_v9_identity.json"
30
+ )
31
+ WAYPOINT_DISTANCE = 4.0
32
+ WAYPOINT_SUCCESS_THRESHOLD = 0.45
33
+ _MODEL = None
34
+
35
+
36
+ def _sha256(path: Path) -> str:
37
+ digest = hashlib.sha256()
38
+ with path.open("rb") as handle:
39
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
40
+ digest.update(chunk)
41
+ return digest.hexdigest()
42
+
43
+
44
+ def controller_receipt_sha256() -> str:
45
+ """Return the exact v9 receipt identity after validating admission."""
46
+
47
+ controller_identity()
48
+ return _sha256(RECEIPT_PATH)
49
+
50
+
51
+ def controller_identity() -> dict[str, Any]:
52
+ """Load and verify the terminal v9 receipt and model as one identity."""
53
+
54
+ receipt_sha256 = _sha256(RECEIPT_PATH)
55
+ model_sha256 = _sha256(MODEL_PATH)
56
+ training_identity_sha256 = _sha256(TRAINING_IDENTITY_PATH)
57
+ receipt = json.loads(RECEIPT_PATH.read_text(encoding="utf-8"))
58
+ training_identity = json.loads(
59
+ TRAINING_IDENTITY_PATH.read_text(encoding="utf-8")
60
+ )
61
+ if (
62
+ receipt.get("status") != "pass"
63
+ or receipt.get("decision") != "admitted_to_fresh_maze_route_gate_v9"
64
+ ):
65
+ raise RuntimeError("Ant v9 controller is not admitted")
66
+ if receipt.get("seed") != 73009 or receipt.get("timesteps") != 5_000_000:
67
+ raise RuntimeError("Ant v9 receipt differs from its frozen training identity")
68
+ if (
69
+ training_identity.get("job_id") != 30192731
70
+ or training_identity.get("seed") != 73009
71
+ ):
72
+ raise RuntimeError("Ant v9 training identity is not the frozen job")
73
+ checks = receipt.get("checks", {})
74
+ required_checks = {
75
+ "episode_count",
76
+ "success_rate_at_least_0p90",
77
+ "minimum_heading_success_rate_at_least_0p75",
78
+ "minimum_map_success_rate_at_least_0p75",
79
+ "unhealthy_termination_rate_at_most_0p10",
80
+ "median_success_steps_at_most_300",
81
+ "all_metrics_finite",
82
+ }
83
+ if not isinstance(checks, dict) or not required_checks.issubset(checks) or not all(
84
+ checks[key] is True for key in required_checks
85
+ ):
86
+ raise RuntimeError("Ant v9 receipt contains a failed controller check")
87
+ if receipt.get("hashes", {}).get("model_sha256") != model_sha256:
88
+ raise RuntimeError("Ant v9 receipt does not bind the controller model")
89
+ if receipt.get("training_waypoint_distances") != [WAYPOINT_DISTANCE]:
90
+ raise RuntimeError("Ant v9 receipt has a different waypoint distance")
91
+ if receipt.get("waypoint_distance") != WAYPOINT_DISTANCE:
92
+ raise RuntimeError("Ant v9 receipt has a different executor distance")
93
+ if receipt.get("success_threshold") != WAYPOINT_SUCCESS_THRESHOLD:
94
+ raise RuntimeError("Ant v9 receipt has a different waypoint threshold")
95
+ route_identity_path = os.environ.get("OAT_ZERO_PROTOCOL_IDENTITY")
96
+ if route_identity_path:
97
+ route_identity = json.loads(
98
+ Path(route_identity_path).read_text(encoding="utf-8")
99
+ )
100
+ expected = {
101
+ "controller_receipt_sha256": receipt_sha256,
102
+ "controller_model_sha256": model_sha256,
103
+ "controller_training_identity_sha256": training_identity_sha256,
104
+ }
105
+ if route_identity.get("schema_version") != (
106
+ "ant-maze-v9-route-generation-identity-v1"
107
+ ):
108
+ raise RuntimeError("Ant v9 route identity schema mismatch")
109
+ if any(route_identity.get(key) != value for key, value in expected.items()):
110
+ raise RuntimeError("Ant v9 route identity does not bind the controller")
111
+ return receipt
112
+
113
+
114
+ def _model():
115
+ global _MODEL
116
+ controller_identity()
117
+ if _MODEL is None:
118
+ from stable_baselines3 import PPO
119
+
120
+ _MODEL = PPO.load(MODEL_PATH, device="cpu")
121
+ return _MODEL
122
+
123
+
124
+ def _heading(token: str):
125
+ import numpy as np
126
+
127
+ diagonal = 1.0 / math.sqrt(2.0)
128
+ values = {
129
+ "N": (0.0, 1.0),
130
+ "NE": (diagonal, diagonal),
131
+ "E": (1.0, 0.0),
132
+ "SE": (diagonal, -diagonal),
133
+ "S": (0.0, -1.0),
134
+ "SW": (-diagonal, -diagonal),
135
+ "W": (-1.0, 0.0),
136
+ "NW": (-diagonal, diagonal),
137
+ }
138
+ return np.asarray(values[token], dtype=np.float32)
139
+
140
+
141
+ def execute_ant_v9_raw(
142
+ candidate: str,
143
+ raw_spec: Mapping[str, Any],
144
+ ) -> dict[str, Any]:
145
+ """Execute commands as successive four-unit relative waypoint targets."""
146
+
147
+ import gymnasium as gym
148
+ import gymnasium_robotics
149
+ import numpy as np
150
+
151
+ gym.register_envs(gymnasium_robotics)
152
+ spec = parse_maze_action_spec(raw_spec)
153
+ if spec.verifier != ANT_MAZE_VERIFIER:
154
+ raise ValueError("AntMaze executor received a non-AntMaze spec")
155
+ runtime = maze_runtime_identity()
156
+ if spec.environment_sha256 != runtime["ant_environment_sha256"]:
157
+ raise ValueError("AntMaze environment hash differs from installed runtime")
158
+ if spec.controller_sha256 != controller_receipt_sha256():
159
+ raise ValueError("AntMaze controller hash differs from frozen v9 receipt")
160
+ tokens = parse_maze_action_program(candidate, spec)
161
+ model = _model()
162
+
163
+ env = gym.make(
164
+ spec.environment_id,
165
+ maze_map=[list(row) for row in spec.maze_map],
166
+ reward_type="sparse",
167
+ continuing_task=False,
168
+ reset_target=False,
169
+ max_episode_steps=len(tokens) * spec.action_repeat,
170
+ )
171
+ try:
172
+ env.unwrapped.position_noise_range = 0.0
173
+ observation, info = env.reset(
174
+ seed=spec.reset_seed,
175
+ options={
176
+ "reset_cell": list(spec.reset_cell),
177
+ "goal_cell": list(spec.goal_cell),
178
+ },
179
+ )
180
+ trajectory = [observation["achieved_goal"].astype(float).tolist()]
181
+ success = bool(info.get("success", False))
182
+ simulator_steps = 0
183
+ terminated = truncated = False
184
+ for token in tokens:
185
+ current = np.asarray(env.unwrapped.data.qpos[:2], dtype=np.float32)
186
+ target = current + WAYPOINT_DISTANCE * _heading(token)
187
+ for _ in range(spec.action_repeat):
188
+ current = np.asarray(env.unwrapped.data.qpos[:2], dtype=np.float32)
189
+ relative = np.clip(
190
+ (target - current) / WAYPOINT_DISTANCE,
191
+ -1.0,
192
+ 1.0,
193
+ )
194
+ controller_input = np.concatenate(
195
+ [
196
+ np.asarray(observation["observation"], dtype=np.float32),
197
+ relative,
198
+ ]
199
+ )
200
+ action, _ = model.predict(controller_input, deterministic=True)
201
+ observation, _reward, terminated, truncated, info = env.step(action)
202
+ simulator_steps += 1
203
+ trajectory.append(
204
+ observation["achieved_goal"].astype(float).tolist()
205
+ )
206
+ success = bool(info.get("success", False))
207
+ current = np.asarray(env.unwrapped.data.qpos[:2], dtype=np.float32)
208
+ waypoint_reached = (
209
+ float(np.linalg.norm(target - current))
210
+ <= WAYPOINT_SUCCESS_THRESHOLD
211
+ )
212
+ if success or waypoint_reached or terminated or truncated:
213
+ break
214
+ if success or terminated or truncated:
215
+ break
216
+ distance = float(
217
+ np.linalg.norm(
218
+ observation["achieved_goal"] - observation["desired_goal"]
219
+ )
220
+ )
221
+ finally:
222
+ env.close()
223
+ return {
224
+ "environment_sha256": spec.environment_sha256,
225
+ "controller_sha256": spec.controller_sha256,
226
+ "spec_sha256": spec.spec_sha256,
227
+ "reset_seed": spec.reset_seed,
228
+ "action_tokens": list(tokens),
229
+ "success": success,
230
+ "final_goal_distance": distance,
231
+ "trajectory_xy": trajectory,
232
+ "simulator_steps": simulator_steps,
233
+ }
234
+
235
+
236
+ def execute_ant_v9(candidate: str, raw_spec: Mapping[str, Any]):
237
+ """Execute and validate one v9 program in the pinned AntMaze runtime."""
238
+
239
+ execution = execute_ant_v9_raw(candidate, raw_spec)
240
+ return validate_maze_execution(candidate, raw_spec, execution), execution
code/oat_drgrpo/canonical_actions.py ADDED
@@ -0,0 +1,915 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed-support canonical action policies for exact-answer experiments."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from dataclasses import dataclass
7
+ import itertools
8
+ import json
9
+ import math
10
+ from typing import Any
11
+
12
+ import torch
13
+
14
+ from .pantry_support_action import (
15
+ PANTRY_SUPPORT_MASK_TASK,
16
+ PANTRY_SUPPORT_MASK_WIDTH,
17
+ decode_pantry_support_mask,
18
+ pantry_support_mask_from_allocation,
19
+ )
20
+
21
+
22
+ GRAPH_COLOR_ACTIONS = ("1", "2", "3")
23
+ COUNTDOWN_ACTIONS_BY_POSITION = (
24
+ ("1", "2", "3", "4", "5", "6"),
25
+ ("1", "2", "3"),
26
+ ("1", "2", "3", "4", "5", "6"),
27
+ )
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class CanonicalActionSpace:
32
+ """A finite three-position action grammar resolved into tokenizer IDs."""
33
+
34
+ task: str
35
+ action_strings_by_position: tuple[tuple[str, ...], ...]
36
+ token_ids_by_position: tuple[tuple[int, ...], ...]
37
+
38
+ @property
39
+ def horizon(self) -> int:
40
+ return len(self.token_ids_by_position)
41
+
42
+ @property
43
+ def union_token_ids(self) -> tuple[int, ...]:
44
+ return tuple(
45
+ dict.fromkeys(
46
+ token_id
47
+ for support in self.token_ids_by_position
48
+ for token_id in support
49
+ )
50
+ )
51
+
52
+ @property
53
+ def sequence_count(self) -> int:
54
+ return math.prod(len(support) for support in self.token_ids_by_position)
55
+
56
+ @property
57
+ def max_sequence_entropy(self) -> float:
58
+ return math.log(self.sequence_count)
59
+
60
+
61
+ def canonical_action_strings_by_position(
62
+ task: str,
63
+ ) -> tuple[tuple[str, ...], ...]:
64
+ """Return the audited action grammar for a canonical benchmark task."""
65
+
66
+ if task == "graph_coloring":
67
+ return (GRAPH_COLOR_ACTIONS,) * 3
68
+ if task == "countdown":
69
+ return COUNTDOWN_ACTIONS_BY_POSITION
70
+ if task == PANTRY_SUPPORT_MASK_TASK:
71
+ return (("0", "1"),) * PANTRY_SUPPORT_MASK_WIDTH
72
+ raise ValueError(f"unsupported canonical action task: {task!r}")
73
+
74
+
75
+ def resolve_canonical_action_space(tokenizer: Any, task: str) -> CanonicalActionSpace:
76
+ """Resolve every grammar position while preserving its support order."""
77
+
78
+ action_strings = canonical_action_strings_by_position(task)
79
+ union_actions = tuple(
80
+ dict.fromkeys(action for support in action_strings for action in support)
81
+ )
82
+ union_ids = resolve_single_token_actions(tokenizer, union_actions)
83
+ action_to_id = dict(zip(union_actions, union_ids))
84
+ return CanonicalActionSpace(
85
+ task=task,
86
+ action_strings_by_position=action_strings,
87
+ token_ids_by_position=tuple(
88
+ tuple(action_to_id[action] for action in support)
89
+ for support in action_strings
90
+ ),
91
+ )
92
+
93
+
94
+ def enumerate_countdown_action_codes() -> tuple[str, ...]:
95
+ """Enumerate the 6 x 3 x 6 Countdown codes in lexical digit order."""
96
+
97
+ return tuple(
98
+ "".join(digits)
99
+ for digits in itertools.product(
100
+ COUNTDOWN_ACTIONS_BY_POSITION[0],
101
+ COUNTDOWN_ACTIONS_BY_POSITION[1],
102
+ COUNTDOWN_ACTIONS_BY_POSITION[2],
103
+ )
104
+ )
105
+
106
+
107
+ def decode_countdown_action_code(code: str, reference: str | dict[str, Any]) -> str:
108
+ """Decode one audited three-digit code into a full Countdown expression.
109
+
110
+ The singleton digit selects one operand in dataset order. The inner digit
111
+ combines the other two operands (also in dataset order), and the root
112
+ digit combines that pair with the singleton. No answer or target is used.
113
+ """
114
+
115
+ text = str(code).strip()
116
+ if (
117
+ len(text) != 3
118
+ or text[0] not in COUNTDOWN_ACTIONS_BY_POSITION[0]
119
+ or text[1] not in COUNTDOWN_ACTIONS_BY_POSITION[1]
120
+ or text[2] not in COUNTDOWN_ACTIONS_BY_POSITION[2]
121
+ ):
122
+ raise ValueError(f"invalid canonical Countdown action code: {code!r}")
123
+ try:
124
+ spec = json.loads(reference) if isinstance(reference, str) else reference
125
+ if not isinstance(spec, dict) or spec.get("verifier") != "countdown":
126
+ raise ValueError
127
+ numbers = tuple(int(value) for value in spec["numbers"])
128
+ except (KeyError, TypeError, ValueError, json.JSONDecodeError) as exc:
129
+ raise ValueError("canonical Countdown reference is malformed") from exc
130
+ if len(numbers) != 3 or len(set(numbers)) != 3:
131
+ raise ValueError(
132
+ "canonical Countdown requires exactly three distinct operands"
133
+ )
134
+
135
+ root_action, singleton_action, inner_action = (int(value) for value in text)
136
+ singleton_index = singleton_action - 1
137
+ singleton = numbers[singleton_index]
138
+ a, b = (
139
+ value for index, value in enumerate(numbers) if index != singleton_index
140
+ )
141
+ pair = {
142
+ 1: f"({a} + {b})",
143
+ 2: f"({a} * {b})",
144
+ 3: f"({a} - {b})",
145
+ 4: f"({b} - {a})",
146
+ 5: f"({a} / {b})",
147
+ 6: f"({b} / {a})",
148
+ }[inner_action]
149
+ return {
150
+ 1: f"({pair} + {singleton})",
151
+ 2: f"({pair} * {singleton})",
152
+ 3: f"({pair} - {singleton})",
153
+ 4: f"({singleton} - {pair})",
154
+ 5: f"({pair} / {singleton})",
155
+ 6: f"({singleton} / {pair})",
156
+ }[root_action]
157
+
158
+
159
+ def decode_canonical_action_response(
160
+ task: str, code: str, reference: str | dict[str, Any]
161
+ ) -> str:
162
+ """Map policy action tokens to the benchmark response seen by the grader."""
163
+
164
+ text = str(code).strip()
165
+ if task == "graph_coloring":
166
+ if len(text) != 3 or any(action not in GRAPH_COLOR_ACTIONS for action in text):
167
+ raise ValueError(f"invalid canonical graph action code: {code!r}")
168
+ return text
169
+ if task == "countdown":
170
+ return decode_countdown_action_code(text, reference)
171
+ if task == PANTRY_SUPPORT_MASK_TASK:
172
+ try:
173
+ spec = json.loads(reference) if isinstance(reference, str) else reference
174
+ except json.JSONDecodeError:
175
+ spec = {}
176
+ if not isinstance(spec, dict):
177
+ spec = {}
178
+ return decode_pantry_support_mask(text, spec)
179
+ raise ValueError(f"unsupported canonical action task: {task!r}")
180
+
181
+
182
+ def canonical_action_code_from_verified_response(
183
+ task: str,
184
+ response: str,
185
+ reference: str | dict[str, Any],
186
+ ) -> str:
187
+ """Represent a verified replay witness on its registered policy surface."""
188
+
189
+ text = str(response).strip()
190
+ if task == "graph_coloring":
191
+ decode_canonical_action_response(task, text, reference)
192
+ return text
193
+ if task == PANTRY_SUPPORT_MASK_TASK:
194
+ try:
195
+ spec = json.loads(reference) if isinstance(reference, str) else reference
196
+ except json.JSONDecodeError as exc:
197
+ raise ValueError("canonical Pantry reference is malformed") from exc
198
+ if not isinstance(spec, dict):
199
+ raise ValueError("canonical Pantry reference is malformed")
200
+ return pantry_support_mask_from_allocation(text, spec)
201
+ raise ValueError(
202
+ f"verified replay projection is unsupported for canonical task {task!r}"
203
+ )
204
+
205
+
206
+ def canonical_action_code_token_ids(
207
+ action_space: CanonicalActionSpace,
208
+ code: str,
209
+ ) -> tuple[int, ...]:
210
+ """Encode one canonical code as exactly one registered token per action."""
211
+
212
+ text = str(code).strip()
213
+ if len(text) != action_space.horizon:
214
+ raise ValueError(
215
+ f"canonical action code has length {len(text)}, expected "
216
+ f"{action_space.horizon}"
217
+ )
218
+ token_ids: list[int] = []
219
+ for position, action in enumerate(text):
220
+ actions = action_space.action_strings_by_position[position]
221
+ try:
222
+ action_index = actions.index(action)
223
+ except ValueError as exc:
224
+ raise ValueError(
225
+ f"canonical action {action!r} is outside position {position} support"
226
+ ) from exc
227
+ token_ids.append(action_space.token_ids_by_position[position][action_index])
228
+ return tuple(token_ids)
229
+
230
+
231
+ def _sample_canonical_actions_from_logits(
232
+ next_token_logits: torch.Tensor,
233
+ *,
234
+ allowed_token_ids: Sequence[int],
235
+ uniforms: torch.Tensor,
236
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
237
+ """Sample one categorical action per row from a fixed token support.
238
+
239
+ Explicit uniforms make the sampling stream reproducible independently of
240
+ CUDA generator implementation. The caller remains responsible for the
241
+ autoregressive loop: this helper samples exactly one next action.
242
+ """
243
+
244
+ if next_token_logits.ndim != 2:
245
+ raise ValueError("next_token_logits must have shape [batch, vocab]")
246
+ if next_token_logits.shape[0] <= 0:
247
+ raise ValueError("next_token_logits batch must be nonempty")
248
+ if uniforms.shape != (next_token_logits.shape[0],):
249
+ raise ValueError("uniforms must have shape [batch]")
250
+ ids = tuple(int(token_id) for token_id in allowed_token_ids)
251
+ if not ids or len(ids) != len(set(ids)):
252
+ raise ValueError("allowed_token_ids must be nonempty and unique")
253
+ if min(ids) < 0 or max(ids) >= int(next_token_logits.shape[-1]):
254
+ raise ValueError("allowed_token_ids must lie inside the model vocabulary")
255
+ if not bool(torch.isfinite(uniforms).all()) or not bool(
256
+ ((uniforms >= 0) & (uniforms < 1)).all()
257
+ ):
258
+ raise ValueError("uniforms must be finite values in [0, 1)")
259
+
260
+ allowed = torch.tensor(ids, dtype=torch.long, device=next_token_logits.device)
261
+ action_logits = next_token_logits.index_select(-1, allowed).float()
262
+ if not bool(torch.isfinite(action_logits).all()):
263
+ raise FloatingPointError("canonical next-action logits are nonfinite")
264
+ full_log_probs = torch.log_softmax(action_logits, dim=-1)
265
+ probabilities = torch.exp(full_log_probs)
266
+ cumulative = torch.cumsum(probabilities, dim=-1)
267
+ uniform_rows = uniforms.to(
268
+ device=next_token_logits.device, dtype=probabilities.dtype
269
+ )
270
+ sampled_indices = (uniform_rows.unsqueeze(-1) >= cumulative).sum(dim=-1)
271
+ sampled_indices = sampled_indices.clamp_max(len(ids) - 1)
272
+ token_ids = allowed[sampled_indices]
273
+ selected_log_probs = torch.gather(
274
+ full_log_probs, -1, sampled_indices.unsqueeze(-1)
275
+ ).squeeze(-1)
276
+ return (
277
+ token_ids.detach(),
278
+ selected_log_probs.detach(),
279
+ full_log_probs.detach(),
280
+ )
281
+
282
+
283
+ def resolve_single_token_actions(
284
+ tokenizer: Any,
285
+ actions: Sequence[str],
286
+ ) -> tuple[int, ...]:
287
+ """Resolve a one-token, one-to-one serialization for canonical actions."""
288
+
289
+ if not actions:
290
+ raise ValueError("canonical action support cannot be empty")
291
+ token_ids: list[int] = []
292
+ for action in actions:
293
+ encoded = list(tokenizer.encode(action, add_special_tokens=False))
294
+ if len(encoded) != 1:
295
+ raise ValueError(
296
+ f"canonical action {action!r} must encode to exactly one token; "
297
+ f"got {encoded}"
298
+ )
299
+ token_id = int(encoded[0])
300
+ decoded = str(
301
+ tokenizer.decode(
302
+ [token_id],
303
+ skip_special_tokens=False,
304
+ clean_up_tokenization_spaces=False,
305
+ )
306
+ )
307
+ if decoded != action:
308
+ raise ValueError(
309
+ f"canonical action {action!r} is not one-to-one: token "
310
+ f"{token_id} decodes as {decoded!r}"
311
+ )
312
+ token_ids.append(token_id)
313
+ if len(set(token_ids)) != len(token_ids):
314
+ raise ValueError("canonical actions must resolve to distinct token ids")
315
+ return tuple(token_ids)
316
+
317
+
318
+ def resolve_graph_color_action_token_ids(tokenizer: Any) -> tuple[int, ...]:
319
+ """Return the exact token ids for graph-color actions 1, 2, and 3."""
320
+
321
+ return resolve_single_token_actions(tokenizer, GRAPH_COLOR_ACTIONS)
322
+
323
+
324
+ def restricted_action_log_probs_entropy_and_distribution(
325
+ logits: torch.Tensor,
326
+ labels: torch.Tensor,
327
+ response_masks: torch.Tensor,
328
+ *,
329
+ allowed_token_ids: Sequence[int],
330
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
331
+ """Score a fixed-support autoregressive action policy.
332
+
333
+ ``logits`` and ``labels`` have the ordinary causal-LM sequence shapes.
334
+ Only active response labels must belong to ``allowed_token_ids``. Returned
335
+ tensors have the shifted ``[batch, sequence - 1]`` shape and are zero away
336
+ from response actions.
337
+ """
338
+
339
+ if logits.ndim != 3:
340
+ raise ValueError("logits must have shape [batch, sequence, vocab]")
341
+ if labels.shape != logits.shape[:-1]:
342
+ raise ValueError("labels must match logits batch/sequence dimensions")
343
+ if response_masks.shape != (logits.shape[0], logits.shape[1] - 1):
344
+ raise ValueError("response_masks must have shape [batch, sequence - 1]")
345
+ ids = tuple(int(token_id) for token_id in allowed_token_ids)
346
+ if not ids or len(set(ids)) != len(ids):
347
+ raise ValueError("allowed_token_ids must be nonempty and unique")
348
+ if min(ids) < 0 or max(ids) >= int(logits.shape[-1]):
349
+ raise ValueError("allowed_token_ids must lie inside the model vocabulary")
350
+
351
+ shifted_labels = labels[:, 1:]
352
+ active = response_masks.to(torch.bool)
353
+ allowed = torch.tensor(ids, dtype=torch.long, device=logits.device)
354
+ matches = shifted_labels.unsqueeze(-1).eq(allowed)
355
+ match_count = matches.sum(dim=-1)
356
+ invalid_active = active & match_count.ne(1)
357
+ if bool(invalid_active.any()):
358
+ invalid_ids = shifted_labels[invalid_active].detach().cpu().unique().tolist()
359
+ raise ValueError(
360
+ "canonical response contains token ids outside its action support: "
361
+ f"{invalid_ids}"
362
+ )
363
+
364
+ action_logits = logits[:, :-1, :].index_select(-1, allowed).float()
365
+ if not bool(torch.isfinite(action_logits[active]).all()):
366
+ raise FloatingPointError(
367
+ "canonical policy has nonfinite allowed-support logits on active actions"
368
+ )
369
+ action_log_probs = torch.log_softmax(action_logits, dim=-1)
370
+ selected_indices = matches.to(torch.int64).argmax(dim=-1)
371
+ selected = torch.gather(
372
+ action_log_probs, dim=-1, index=selected_indices.unsqueeze(-1)
373
+ ).squeeze(-1)
374
+ probabilities = torch.softmax(action_logits, dim=-1)
375
+ entropy = -(probabilities * action_log_probs).sum(dim=-1)
376
+ if not bool(torch.isfinite(selected[active]).all()):
377
+ raise FloatingPointError(
378
+ "canonical policy has nonfinite selected log probabilities"
379
+ )
380
+ if not bool(torch.isfinite(entropy[active]).all()):
381
+ raise FloatingPointError("canonical policy has nonfinite action entropy")
382
+ zeros = torch.zeros_like(selected)
383
+ masked_distribution = torch.where(
384
+ active.unsqueeze(-1), action_log_probs, torch.zeros_like(action_log_probs)
385
+ )
386
+ return (
387
+ torch.where(active, selected, zeros),
388
+ torch.where(active, entropy, zeros),
389
+ masked_distribution,
390
+ )
391
+
392
+
393
+ def restricted_action_log_probs_and_entropy(
394
+ logits: torch.Tensor,
395
+ labels: torch.Tensor,
396
+ response_masks: torch.Tensor,
397
+ *,
398
+ allowed_token_ids: Sequence[int],
399
+ ) -> tuple[torch.Tensor, torch.Tensor]:
400
+ """Backward-compatible two-output canonical-policy scorer."""
401
+
402
+ selected, entropy, _ = restricted_action_log_probs_entropy_and_distribution(
403
+ logits,
404
+ labels,
405
+ response_masks,
406
+ allowed_token_ids=allowed_token_ids,
407
+ )
408
+ return selected, entropy
409
+
410
+
411
+ def restricted_position_action_log_probs_entropy_and_distribution(
412
+ logits: torch.Tensor,
413
+ labels: torch.Tensor,
414
+ response_masks: torch.Tensor,
415
+ *,
416
+ allowed_token_ids_by_position: Sequence[Sequence[int]],
417
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
418
+ """Score a fixed-horizon policy with position-specific token supports.
419
+
420
+ The full distribution uses the ordered union vocabulary. Disallowed union
421
+ entries are ``-inf`` on active rows and accompanied by an explicit support
422
+ mask, so callers never treat a masked action as probability mass.
423
+ """
424
+
425
+ if logits.ndim != 3:
426
+ raise ValueError("logits must have shape [batch, sequence, vocab]")
427
+ if labels.shape != logits.shape[:-1]:
428
+ raise ValueError("labels must match logits batch/sequence dimensions")
429
+ if response_masks.shape != (logits.shape[0], logits.shape[1] - 1):
430
+ raise ValueError("response_masks must have shape [batch, sequence - 1]")
431
+ supports = tuple(
432
+ tuple(int(token_id) for token_id in support)
433
+ for support in allowed_token_ids_by_position
434
+ )
435
+ if not supports or any(
436
+ not support or len(support) != len(set(support)) for support in supports
437
+ ):
438
+ raise ValueError("every positional action support must be nonempty and unique")
439
+ union_ids = tuple(
440
+ dict.fromkeys(token_id for support in supports for token_id in support)
441
+ )
442
+ if min(union_ids) < 0 or max(union_ids) >= int(logits.shape[-1]):
443
+ raise ValueError("allowed_token_ids must lie inside the model vocabulary")
444
+
445
+ active = response_masks.to(torch.bool)
446
+ row_counts = active.sum(dim=-1)
447
+ if not bool(row_counts.eq(len(supports)).all()):
448
+ raise ValueError(
449
+ "canonical rows must contain exactly one action per positional support"
450
+ )
451
+ ordinals = active.to(torch.int64).cumsum(dim=-1) - 1
452
+ safe_ordinals = ordinals.clamp(min=0, max=len(supports) - 1)
453
+ union_allowed = torch.tensor(
454
+ [
455
+ [token_id in set(support) for token_id in union_ids]
456
+ for support in supports
457
+ ],
458
+ dtype=torch.bool,
459
+ device=logits.device,
460
+ )
461
+ support_mask = union_allowed[safe_ordinals] & active.unsqueeze(-1)
462
+ union = torch.tensor(union_ids, dtype=torch.long, device=logits.device)
463
+ action_logits = logits[:, :-1, :].index_select(-1, union).float()
464
+ if not bool(torch.isfinite(action_logits[support_mask]).all()):
465
+ raise FloatingPointError(
466
+ "canonical policy has nonfinite positional-support logits"
467
+ )
468
+ masked_logits = action_logits.masked_fill(~support_mask, -torch.inf)
469
+ # Inactive prompt/padding positions have no support by construction. Give
470
+ # those rows a harmless finite distribution before log-softmax; they are
471
+ # zeroed in every returned tensor below. This avoids all--inf softmax NaNs
472
+ # (and their gradients) outside the response mask.
473
+ masked_logits = torch.where(
474
+ active.unsqueeze(-1), masked_logits, torch.zeros_like(masked_logits)
475
+ )
476
+ action_log_probs = torch.log_softmax(masked_logits, dim=-1)
477
+
478
+ shifted_labels = labels[:, 1:]
479
+ matches = shifted_labels.unsqueeze(-1).eq(union)
480
+ valid_selected = (matches & support_mask).sum(dim=-1).eq(1)
481
+ if bool((active & ~valid_selected).any()):
482
+ invalid_ids = shifted_labels[active & ~valid_selected].unique().tolist()
483
+ raise ValueError(
484
+ "canonical response contains token ids outside its positional support: "
485
+ f"{invalid_ids}"
486
+ )
487
+ selected_indices = matches.to(torch.int64).argmax(dim=-1)
488
+ selected = torch.gather(
489
+ action_log_probs, dim=-1, index=selected_indices.unsqueeze(-1)
490
+ ).squeeze(-1)
491
+ probabilities = torch.exp(action_log_probs)
492
+ finite_log_probs = action_log_probs.masked_fill(~support_mask, 0.0)
493
+ entropy_terms = probabilities * finite_log_probs
494
+ entropy = -entropy_terms.sum(dim=-1)
495
+ if not bool(torch.isfinite(selected[active]).all()) or not bool(
496
+ torch.isfinite(entropy[active]).all()
497
+ ):
498
+ raise FloatingPointError("canonical positional policy scoring is nonfinite")
499
+ zeros = torch.zeros_like(selected)
500
+ return (
501
+ torch.where(active, selected, zeros),
502
+ torch.where(active, entropy, zeros),
503
+ torch.where(
504
+ active.unsqueeze(-1),
505
+ action_log_probs,
506
+ torch.zeros_like(action_log_probs),
507
+ ),
508
+ support_mask,
509
+ )
510
+
511
+
512
+ def materialize_position_canonical_behavior_policy(
513
+ shifted_labels: torch.Tensor,
514
+ response_masks: torch.Tensor,
515
+ *,
516
+ action_ids: Sequence[Sequence[int]],
517
+ selected_log_probs: Sequence[Sequence[float]],
518
+ full_log_probs: Sequence[Sequence[Sequence[float]]],
519
+ behavior_action_token_ids_by_position: Sequence[Sequence[Sequence[int]]],
520
+ allowed_token_ids_by_position: Sequence[Sequence[int]],
521
+ normalizer_atol: float = 1e-6,
522
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, float, float]:
523
+ """Align a ragged positional behavior trace into an ordered union tensor."""
524
+
525
+ if shifted_labels.shape != response_masks.shape:
526
+ raise ValueError("shifted_labels and response_masks must have equal shape")
527
+ if normalizer_atol < 0:
528
+ raise ValueError("normalizer_atol must be nonnegative")
529
+ supports = tuple(
530
+ tuple(int(token_id) for token_id in support)
531
+ for support in allowed_token_ids_by_position
532
+ )
533
+ union_ids = tuple(
534
+ dict.fromkeys(token_id for support in supports for token_id in support)
535
+ )
536
+ union_index = {token_id: index for index, token_id in enumerate(union_ids)}
537
+ batch_size, shifted_length = shifted_labels.shape
538
+ fields = {
539
+ "action_ids": action_ids,
540
+ "selected_log_probs": selected_log_probs,
541
+ "full_log_probs": full_log_probs,
542
+ "behavior_action_token_ids_by_position": (
543
+ behavior_action_token_ids_by_position
544
+ ),
545
+ }
546
+ for name, rows in fields.items():
547
+ if len(rows) != batch_size:
548
+ raise RuntimeError(
549
+ f"canonical behavior {name} has {len(rows)} rows; "
550
+ f"expected {batch_size}"
551
+ )
552
+
553
+ dtype = torch.float32
554
+ device = shifted_labels.device
555
+ selected = torch.zeros((batch_size, shifted_length), dtype=dtype, device=device)
556
+ full = torch.full(
557
+ (batch_size, shifted_length, len(union_ids)),
558
+ -torch.inf,
559
+ dtype=dtype,
560
+ device=device,
561
+ )
562
+ support_mask = torch.zeros_like(full, dtype=torch.bool)
563
+ active = response_masks.to(torch.bool)
564
+ normalization_error_max = 0.0
565
+ selected_echo_diff_max = 0.0
566
+
567
+ for row_index in range(batch_size):
568
+ positions = torch.where(active[row_index])[0]
569
+ row_actions = [int(value) for value in action_ids[row_index]]
570
+ row_selected = [float(value) for value in selected_log_probs[row_index]]
571
+ row_full = list(full_log_probs[row_index])
572
+ row_supports = tuple(
573
+ tuple(int(value) for value in support)
574
+ for support in behavior_action_token_ids_by_position[row_index]
575
+ )
576
+ if row_supports != supports:
577
+ raise RuntimeError(
578
+ "canonical behavior positional support mismatch at row "
579
+ f"{row_index}: expected={supports} observed={row_supports}"
580
+ )
581
+ if not (
582
+ len(positions)
583
+ == len(row_actions)
584
+ == len(row_selected)
585
+ == len(row_full)
586
+ == len(supports)
587
+ ):
588
+ raise RuntimeError(
589
+ f"canonical behavior trace length mismatch at row {row_index}"
590
+ )
591
+ active_labels = shifted_labels[row_index, positions].detach().cpu().tolist()
592
+ if row_actions != [int(value) for value in active_labels]:
593
+ raise RuntimeError(
594
+ "canonical behavior action IDs do not match shifted learner labels "
595
+ f"at row {row_index}"
596
+ )
597
+
598
+ for action_position, (position, action_id, support) in enumerate(
599
+ zip(positions.tolist(), row_actions, supports)
600
+ ):
601
+ if action_id not in support:
602
+ raise RuntimeError(
603
+ f"canonical behavior action {action_id} is outside support {support}"
604
+ )
605
+ values = torch.as_tensor(
606
+ row_full[action_position], dtype=dtype, device=device
607
+ )
608
+ selected_value = torch.as_tensor(
609
+ row_selected[action_position], dtype=dtype, device=device
610
+ )
611
+ if values.shape != (len(support),) or not bool(
612
+ torch.isfinite(values).all()
613
+ ) or not bool(torch.isfinite(selected_value)):
614
+ raise RuntimeError("canonical behavior trace is malformed or nonfinite")
615
+ log_normalizer = torch.logsumexp(values, dim=-1)
616
+ normalization_error = float(torch.abs(log_normalizer).cpu().item())
617
+ if normalization_error > normalizer_atol:
618
+ raise RuntimeError(
619
+ "canonical behavior probabilities are not normalized at "
620
+ f"row={row_index} position={action_position}: "
621
+ f"abs(logsumexp)={normalization_error:.6g}"
622
+ )
623
+ support_action_index = support.index(action_id)
624
+ echo_diff = float(
625
+ torch.abs(selected_value - values[support_action_index]).cpu().item()
626
+ )
627
+ if echo_diff > 1e-7:
628
+ raise RuntimeError(
629
+ "canonical selected behavior log probability does not match "
630
+ f"its positional row at row={row_index} "
631
+ f"position={action_position}: difference={echo_diff:.6g}"
632
+ )
633
+ normalized = values - log_normalizer
634
+ selected[row_index, position] = normalized[support_action_index]
635
+ union_indices = torch.tensor(
636
+ [union_index[token_id] for token_id in support],
637
+ dtype=torch.long,
638
+ device=device,
639
+ )
640
+ full[row_index, position, union_indices] = normalized
641
+ support_mask[row_index, position, union_indices] = True
642
+ normalization_error_max = max(
643
+ normalization_error_max, normalization_error
644
+ )
645
+ selected_echo_diff_max = max(selected_echo_diff_max, echo_diff)
646
+
647
+ return (
648
+ selected,
649
+ full,
650
+ support_mask,
651
+ normalization_error_max,
652
+ selected_echo_diff_max,
653
+ )
654
+
655
+
656
+ def materialize_canonical_behavior_policy(
657
+ shifted_labels: torch.Tensor,
658
+ response_masks: torch.Tensor,
659
+ *,
660
+ action_ids: Sequence[Sequence[int]],
661
+ selected_log_probs: Sequence[Sequence[float]],
662
+ full_log_probs: Sequence[Sequence[Sequence[float]]],
663
+ behavior_action_token_ids: Sequence[Sequence[int]],
664
+ allowed_token_ids: Sequence[int],
665
+ normalizer_atol: float = 1e-6,
666
+ ) -> tuple[torch.Tensor, torch.Tensor, float, float]:
667
+ """Align the exact actor behavior trace with shifted learner positions.
668
+
669
+ Returns selected behavior log probabilities, ordered full-support behavior
670
+ log probabilities, maximum normalization error, and maximum discrepancy
671
+ between the separately transported selected value and its full-row entry.
672
+ """
673
+
674
+ if shifted_labels.shape != response_masks.shape:
675
+ raise ValueError("shifted_labels and response_masks must have equal shape")
676
+ if normalizer_atol < 0:
677
+ raise ValueError("normalizer_atol must be nonnegative")
678
+ batch_size, shifted_length = shifted_labels.shape
679
+ ids = tuple(int(token_id) for token_id in allowed_token_ids)
680
+ if not ids or len(ids) != len(set(ids)):
681
+ raise ValueError("allowed_token_ids must be nonempty and unique")
682
+ fields = {
683
+ "action_ids": action_ids,
684
+ "selected_log_probs": selected_log_probs,
685
+ "full_log_probs": full_log_probs,
686
+ "behavior_action_token_ids": behavior_action_token_ids,
687
+ }
688
+ for name, rows in fields.items():
689
+ if len(rows) != batch_size:
690
+ raise RuntimeError(
691
+ f"canonical behavior {name} has {len(rows)} rows; "
692
+ f"expected {batch_size}"
693
+ )
694
+
695
+ dtype = torch.float32
696
+ device = shifted_labels.device
697
+ selected = torch.zeros((batch_size, shifted_length), dtype=dtype, device=device)
698
+ full = torch.zeros(
699
+ (batch_size, shifted_length, len(ids)), dtype=dtype, device=device
700
+ )
701
+ id_to_index = {token_id: index for index, token_id in enumerate(ids)}
702
+ normalization_error_max = 0.0
703
+ selected_echo_diff_max = 0.0
704
+ active = response_masks.to(torch.bool)
705
+
706
+ for row_index in range(batch_size):
707
+ positions = torch.where(active[row_index])[0]
708
+ expected_count = int(positions.numel())
709
+ row_actions = [int(value) for value in action_ids[row_index]]
710
+ row_selected = [float(value) for value in selected_log_probs[row_index]]
711
+ row_full = list(full_log_probs[row_index])
712
+ row_support = tuple(int(value) for value in behavior_action_token_ids[row_index])
713
+ if row_support != ids:
714
+ raise RuntimeError(
715
+ "canonical behavior support order mismatch at row "
716
+ f"{row_index}: expected={ids} observed={row_support}"
717
+ )
718
+ if not (
719
+ len(row_actions)
720
+ == len(row_selected)
721
+ == len(row_full)
722
+ == expected_count
723
+ ):
724
+ raise RuntimeError(
725
+ "canonical behavior trace length mismatch at row "
726
+ f"{row_index}: actions={len(row_actions)} "
727
+ f"selected={len(row_selected)} full={len(row_full)} "
728
+ f"active={expected_count}"
729
+ )
730
+ active_labels = shifted_labels[row_index, positions].detach().cpu().tolist()
731
+ if row_actions != [int(value) for value in active_labels]:
732
+ raise RuntimeError(
733
+ "canonical behavior action IDs do not match shifted learner labels "
734
+ f"at row {row_index}"
735
+ )
736
+
737
+ for trace_index, (position, action_id) in enumerate(
738
+ zip(positions.tolist(), row_actions)
739
+ ):
740
+ if action_id not in id_to_index:
741
+ raise RuntimeError(
742
+ f"canonical behavior action {action_id} is outside support {ids}"
743
+ )
744
+ values = torch.as_tensor(
745
+ row_full[trace_index], dtype=dtype, device=device
746
+ )
747
+ if values.shape != (len(ids),):
748
+ raise RuntimeError(
749
+ "canonical behavior full row has wrong shape at "
750
+ f"row={row_index} position={trace_index}: {tuple(values.shape)}"
751
+ )
752
+ selected_value = torch.as_tensor(
753
+ row_selected[trace_index], dtype=dtype, device=device
754
+ )
755
+ if not bool(torch.isfinite(values).all()) or not bool(
756
+ torch.isfinite(selected_value)
757
+ ):
758
+ raise RuntimeError("canonical behavior trace contains nonfinite values")
759
+ log_normalizer = torch.logsumexp(values, dim=-1)
760
+ normalization_error = float(
761
+ torch.abs(log_normalizer).detach().cpu().item()
762
+ )
763
+ if normalization_error > normalizer_atol:
764
+ raise RuntimeError(
765
+ "canonical behavior probabilities are not normalized at "
766
+ f"row={row_index} position={trace_index}: "
767
+ f"abs(logsumexp)={normalization_error:.6g}"
768
+ )
769
+ selected_from_full_raw = values[id_to_index[action_id]]
770
+ echo_diff = float(
771
+ torch.abs(selected_value - selected_from_full_raw)
772
+ .detach()
773
+ .cpu()
774
+ .item()
775
+ )
776
+ if echo_diff > 1e-7:
777
+ raise RuntimeError(
778
+ "canonical selected behavior log probability does not match "
779
+ f"its full row at row={row_index} position={trace_index}: "
780
+ f"difference={echo_diff:.6g}"
781
+ )
782
+ normalized_values = values - log_normalizer
783
+ selected[row_index, position] = normalized_values[id_to_index[action_id]]
784
+ full[row_index, position] = normalized_values
785
+ normalization_error_max = max(
786
+ normalization_error_max, normalization_error
787
+ )
788
+ selected_echo_diff_max = max(selected_echo_diff_max, echo_diff)
789
+
790
+ return selected, full, normalization_error_max, selected_echo_diff_max
791
+
792
+
793
+ def canonical_behavior_overlap_diagnostics(
794
+ behavior_selected_log_probs: torch.Tensor,
795
+ behavior_full_log_probs: torch.Tensor,
796
+ learner_selected_log_probs: torch.Tensor,
797
+ learner_full_log_probs: torch.Tensor,
798
+ response_masks: torch.Tensor,
799
+ support_mask: torch.Tensor | None = None,
800
+ ) -> dict[str, torch.Tensor]:
801
+ """Compute full-distribution overlap and horizon-three IS diagnostics."""
802
+
803
+ if behavior_selected_log_probs.shape != response_masks.shape:
804
+ raise ValueError("behavior selected log-probabilities have the wrong shape")
805
+ if learner_selected_log_probs.shape != response_masks.shape:
806
+ raise ValueError("learner selected log-probabilities have the wrong shape")
807
+ expected_full_shape = (*response_masks.shape, behavior_full_log_probs.shape[-1])
808
+ if behavior_full_log_probs.shape != expected_full_shape:
809
+ raise ValueError("behavior full log-probabilities have the wrong shape")
810
+ if learner_full_log_probs.shape != expected_full_shape:
811
+ raise ValueError("learner full log-probabilities have the wrong shape")
812
+ if support_mask is not None and support_mask.shape != expected_full_shape:
813
+ raise ValueError("canonical support mask has the wrong shape")
814
+
815
+ active = response_masks.to(torch.bool)
816
+ if not bool(active.any()):
817
+ raise ValueError("canonical behavior diagnostics require active actions")
818
+ behavior_rows = behavior_full_log_probs[active].double()
819
+ learner_rows = learner_full_log_probs[active].double()
820
+ active_support = (
821
+ torch.ones_like(behavior_rows, dtype=torch.bool)
822
+ if support_mask is None
823
+ else support_mask[active].to(torch.bool)
824
+ )
825
+ if not bool(active_support.any(dim=-1).all()):
826
+ raise ValueError("canonical behavior diagnostics found an empty support row")
827
+ if not bool(torch.isfinite(behavior_rows[active_support]).all()) or not bool(
828
+ torch.isfinite(learner_rows[active_support]).all()
829
+ ):
830
+ raise FloatingPointError("canonical behavior diagnostics are nonfinite")
831
+ behavior_rows = behavior_rows - torch.logsumexp(
832
+ behavior_rows.masked_fill(~active_support, -torch.inf),
833
+ dim=-1,
834
+ keepdim=True,
835
+ )
836
+ learner_rows = learner_rows - torch.logsumexp(
837
+ learner_rows.masked_fill(~active_support, -torch.inf),
838
+ dim=-1,
839
+ keepdim=True,
840
+ )
841
+
842
+ log_ratio_rows = torch.where(
843
+ active_support,
844
+ learner_rows - behavior_rows,
845
+ torch.zeros_like(learner_rows),
846
+ )
847
+ density_ratios = torch.exp(log_ratio_rows[active_support])
848
+ behavior_probabilities = torch.where(
849
+ active_support, torch.exp(behavior_rows), torch.zeros_like(behavior_rows)
850
+ )
851
+ learner_probabilities = torch.where(
852
+ active_support, torch.exp(learner_rows), torch.zeros_like(learner_rows)
853
+ )
854
+ tv = 0.5 * torch.abs(
855
+ learner_probabilities - behavior_probabilities
856
+ ).sum(dim=-1)
857
+ kl_actor_learner = (
858
+ torch.where(
859
+ active_support,
860
+ behavior_probabilities * (behavior_rows - learner_rows),
861
+ torch.zeros_like(behavior_probabilities),
862
+ )
863
+ ).sum(dim=-1)
864
+ kl_learner_actor = (
865
+ torch.where(
866
+ active_support,
867
+ learner_probabilities * (learner_rows - behavior_rows),
868
+ torch.zeros_like(learner_probabilities),
869
+ )
870
+ ).sum(dim=-1)
871
+
872
+ selected_log_ratio = (
873
+ learner_selected_log_probs.double() - behavior_selected_log_probs.double()
874
+ )
875
+ row_counts = active.sum(dim=-1)
876
+ if not bool(row_counts.eq(row_counts[0]).all()):
877
+ raise RuntimeError("canonical behavior rows have unequal horizons")
878
+ horizon = int(row_counts[0].item())
879
+ compact_log_ratio = torch.stack(
880
+ [selected_log_ratio[row][active[row]] for row in range(active.shape[0])]
881
+ )
882
+ inclusive_prefix_log_ratio = torch.cumsum(compact_log_ratio, dim=-1)
883
+ exclusive_prefix_log_ratio = torch.cat(
884
+ (
885
+ torch.zeros_like(inclusive_prefix_log_ratio[:, :1]),
886
+ inclusive_prefix_log_ratio[:, :-1],
887
+ ),
888
+ dim=-1,
889
+ )
890
+
891
+ def _ess_fraction(weights: torch.Tensor) -> torch.Tensor:
892
+ count = torch.tensor(
893
+ float(weights.numel()), dtype=weights.dtype, device=weights.device
894
+ )
895
+ return weights.sum().square() / weights.square().sum().clamp_min(1e-12) / count
896
+
897
+ prefix_ess = []
898
+ for depth in range(horizon):
899
+ prefix_ess.append(
900
+ _ess_fraction(torch.exp(exclusive_prefix_log_ratio[:, depth]))
901
+ )
902
+ sequence_weights = torch.exp(inclusive_prefix_log_ratio[:, horizon - 1])
903
+
904
+ return {
905
+ "canonical_behavior_ratio_min": density_ratios.min(),
906
+ "canonical_behavior_ratio_max": density_ratios.max(),
907
+ "canonical_behavior_tv_mean": tv.mean(),
908
+ "canonical_behavior_tv_max": tv.max(),
909
+ "canonical_behavior_kl_actor_learner_mean": kl_actor_learner.mean(),
910
+ "canonical_behavior_kl_actor_learner_max": kl_actor_learner.max(),
911
+ "canonical_behavior_kl_learner_actor_mean": kl_learner_actor.mean(),
912
+ "canonical_behavior_kl_learner_actor_max": kl_learner_actor.max(),
913
+ "canonical_behavior_sequence_ess_fraction": _ess_fraction(sequence_weights),
914
+ "canonical_behavior_prefix_ess_fraction_min": torch.stack(prefix_ess).min(),
915
+ }
code/oat_drgrpo/math_grader.py ADDED
@@ -0,0 +1,2141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Garena Online Private Limited
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Provides a math answer grading function with high recall.
16
+ Based on HF math_verify, verl, open reasoner zero, etc.
17
+ """
18
+
19
+ import ast
20
+ from dataclasses import dataclass
21
+ import functools
22
+ import json
23
+ from multiprocessing import TimeoutError as MultiprocessingTimeoutError
24
+ import queue
25
+ import re
26
+ import signal
27
+ import threading
28
+ from collections import Counter
29
+ from fractions import Fraction
30
+ from itertools import islice, zip_longest
31
+ from math import isclose
32
+ from typing import Any, Optional
33
+
34
+ import sympy
35
+ from latex2sympy2_extended import latex2sympy
36
+ from math_verify import ExprExtractionConfig, LatexExtractionConfig, parse, verify
37
+ from math_verify import grader as math_verify_grader
38
+ from math_verify import parser as math_verify_parser
39
+ from math_verify.errors import TimeoutException as MathVerifyTimeout
40
+ from math_verify.utils import timeout as math_verify_signal_timeout
41
+ from pylatexenc import latex2text
42
+ from sympy import N, simplify
43
+ from sympy.parsing import sympy_parser
44
+ from sympy.parsing.latex import parse_latex
45
+ from sympy.parsing.sympy_parser import parse_expr
46
+
47
+ from .maze_modebench import (
48
+ ANT_MAZE_VERIFIER,
49
+ POINT_MAZE_VERIFIER,
50
+ )
51
+ from .maze_modebench_process import validate_maze_action_program_external
52
+ from .mathir import (
53
+ MATHIR_MENU_VERIFIER,
54
+ MATHIR_VERIFIER,
55
+ validate_mathir_action_menu,
56
+ validate_mathir_algebra,
57
+ )
58
+ from .math_route import validate_math_route_response
59
+ from .pantry_plan import (
60
+ PANTRY_PLAN_VERIFIER,
61
+ validate_pantry_plan,
62
+ )
63
+ from .python_modebench import (
64
+ PYTHON_FACTOR_VERIFIER,
65
+ python_factor_route_signature,
66
+ )
67
+ from .python_modebench_process import validate_python_factor_function_external
68
+
69
+
70
+ def _thread_compatible_math_verify_timeout(timeout_seconds: int = 10):
71
+ """Keep math_verify bounded when grading runs in an actor worker thread.
72
+
73
+ math_verify's POSIX timeout installs SIGALRM. Python only permits signal
74
+ handler installation on the interpreter's main thread, while OAT grades
75
+ actor responses in a ThreadPool to avoid forking a CUDA/vLLM process. On
76
+ the main thread retain math_verify's native alarm. Else run the protected
77
+ operation in a daemon helper thread and bound the caller's wait.
78
+ """
79
+
80
+ seconds = int(timeout_seconds)
81
+ if seconds <= 0:
82
+ raise ValueError("timeout_seconds must be positive")
83
+
84
+ def decorator(func):
85
+ signal_wrapped = math_verify_signal_timeout(timeout_seconds=seconds)(func)
86
+
87
+ @functools.wraps(func)
88
+ def wrapper(*args, **kwargs):
89
+ if threading.current_thread() is threading.main_thread():
90
+ return signal_wrapped(*args, **kwargs)
91
+ result_queue: queue.Queue[tuple[bool, Any]] = queue.Queue(maxsize=1)
92
+
93
+ def run() -> None:
94
+ try:
95
+ result_queue.put((True, func(*args, **kwargs)))
96
+ except BaseException as error:
97
+ result_queue.put((False, error))
98
+
99
+ worker = threading.Thread(
100
+ target=run,
101
+ name="math-verify-timeout",
102
+ daemon=True,
103
+ )
104
+ worker.start()
105
+ worker.join(seconds)
106
+ if worker.is_alive():
107
+ raise MathVerifyTimeout("Operation timed out!")
108
+ succeeded, value = result_queue.get_nowait()
109
+ if succeeded:
110
+ return value
111
+ raise value
112
+
113
+ return wrapper
114
+
115
+ return decorator
116
+
117
+
118
+ # parse() and verify() resolve `timeout` from their defining module globals at
119
+ # call time. Install the actor-thread-safe policy without altering the external
120
+ # math_verify package or its grading semantics.
121
+ math_verify_parser.timeout = _thread_compatible_math_verify_timeout
122
+ math_verify_grader.timeout = _thread_compatible_math_verify_timeout
123
+
124
+
125
+ _math_verify_sympy_solve_and_compare = math_verify_grader.sympy_solve_and_compare
126
+
127
+
128
+ def _robust_math_verify_sympy_solve_and_compare(
129
+ gold,
130
+ pred,
131
+ float_rounding: int,
132
+ numeric_precision: int,
133
+ ):
134
+ """Repair math_verify's scalar ``solve(Eq)`` compatibility edge case.
135
+
136
+ Some SymPy versions return a list of scalar roots for ``solve(Eq, symbols)``
137
+ while math_verify assumes a list of dictionaries and calls ``.items()``.
138
+ Retry only that failing equality path with ``dict=True`` and preserve the
139
+ package's exact symbol-key and expression-comparison semantics.
140
+ """
141
+
142
+ try:
143
+ return _math_verify_sympy_solve_and_compare(
144
+ gold,
145
+ pred,
146
+ float_rounding,
147
+ numeric_precision,
148
+ )
149
+ except AttributeError as error:
150
+ if (
151
+ "items" not in str(error)
152
+ or not isinstance(gold, sympy.Eq)
153
+ or not isinstance(pred, sympy.Eq)
154
+ ):
155
+ raise
156
+
157
+ solved_gold = sympy.solve(
158
+ gold,
159
+ gold.free_symbols,
160
+ dict=True,
161
+ )
162
+ solved_pred = sympy.solve(
163
+ pred,
164
+ pred.free_symbols,
165
+ dict=True,
166
+ )
167
+ if not isinstance(solved_gold, list) or not isinstance(solved_pred, list):
168
+ return False
169
+ if len(solved_gold) != len(solved_pred):
170
+ return False
171
+
172
+ unmatched = list(solved_pred)
173
+ for gold_solution in solved_gold:
174
+ if not isinstance(gold_solution, dict):
175
+ return False
176
+ match_index = None
177
+ for index, pred_solution in enumerate(unmatched):
178
+ if (
179
+ isinstance(pred_solution, dict)
180
+ and set(gold_solution) == set(pred_solution)
181
+ and all(
182
+ math_verify_grader.sympy_expr_eq(
183
+ gold_solution[key],
184
+ pred_solution[key],
185
+ float_rounding,
186
+ numeric_precision,
187
+ )
188
+ for key in gold_solution
189
+ )
190
+ ):
191
+ match_index = index
192
+ break
193
+ if match_index is None:
194
+ return False
195
+ unmatched.pop(match_index)
196
+ return not unmatched
197
+
198
+
199
+ math_verify_grader.sympy_solve_and_compare = _robust_math_verify_sympy_solve_and_compare
200
+
201
+
202
+ def collect_threaded_math_rewards(
203
+ pool,
204
+ reward_fn,
205
+ responses,
206
+ references,
207
+ *,
208
+ timeout_seconds: float,
209
+ ):
210
+ """Grade a response batch concurrently with one bounded wait per result."""
211
+
212
+ pending = [
213
+ pool.apply_async(reward_fn, (response, reference))
214
+ for response, reference in zip(responses, references)
215
+ ]
216
+ rewards = []
217
+ infos = []
218
+ for result in pending:
219
+ try:
220
+ info, reward = result.get(timeout=timeout_seconds)
221
+ rewards.append(reward)
222
+ infos.append(info)
223
+ except MultiprocessingTimeoutError:
224
+ rewards.append(0.0)
225
+ infos.append({"formatted": False})
226
+ return rewards, infos
227
+
228
+
229
+ # Dan Hendrycks' code
230
+ def mathd_normalize_answer(answer: Optional[str]) -> Optional[str]:
231
+ if answer is None:
232
+ return None
233
+ answer = answer.strip()
234
+ try:
235
+ # Remove enclosing `\text{}`.
236
+ m = re.search(r"^\\text\{(?P<text>.+?)\}$", answer)
237
+ if m is not None:
238
+ answer = m.group("text").strip()
239
+ return _strip_string(answer)
240
+ except Exception:
241
+ return answer
242
+
243
+
244
+ # units mainly from MathQA
245
+ unit_texts = [
246
+ "east",
247
+ "degree",
248
+ "mph",
249
+ "kmph",
250
+ "ft",
251
+ "m sqaure",
252
+ " m east",
253
+ "sq m",
254
+ "deg",
255
+ "mile",
256
+ "q .",
257
+ "monkey",
258
+ "prime",
259
+ "ratio",
260
+ "profit of rs",
261
+ "rd",
262
+ "o",
263
+ "gm",
264
+ "p . m",
265
+ "lb",
266
+ "tile",
267
+ "per",
268
+ "dm",
269
+ "lt",
270
+ "gain",
271
+ "ab",
272
+ "way",
273
+ "west",
274
+ "a .",
275
+ "b .",
276
+ "c .",
277
+ "d .",
278
+ "e .",
279
+ "f .",
280
+ "g .",
281
+ "h .",
282
+ "t",
283
+ "a",
284
+ "h",
285
+ "no change",
286
+ "men",
287
+ "soldier",
288
+ "pie",
289
+ "bc",
290
+ "excess",
291
+ "st",
292
+ "inches",
293
+ "noon",
294
+ "percent",
295
+ "by",
296
+ "gal",
297
+ "kmh",
298
+ "c",
299
+ "acre",
300
+ "rise",
301
+ "a . m",
302
+ "th",
303
+ "π r 2",
304
+ "sq",
305
+ "mark",
306
+ "l",
307
+ "toy",
308
+ "coin",
309
+ "sq . m",
310
+ "gallon",
311
+ "° f",
312
+ "profit",
313
+ "minw",
314
+ "yr",
315
+ "women",
316
+ "feet",
317
+ "am",
318
+ "pm",
319
+ "hr",
320
+ "cu cm",
321
+ "square",
322
+ "v â € ™",
323
+ "are",
324
+ "rupee",
325
+ "rounds",
326
+ "cubic",
327
+ "cc",
328
+ "mtr",
329
+ "s",
330
+ "ohm",
331
+ "number",
332
+ "kmph",
333
+ "day",
334
+ "hour",
335
+ "minute",
336
+ "min",
337
+ "second",
338
+ "man",
339
+ "woman",
340
+ "sec",
341
+ "cube",
342
+ "mt",
343
+ "sq inch",
344
+ "mp",
345
+ "∏ cm ³",
346
+ "hectare",
347
+ "more",
348
+ "sec",
349
+ "unit",
350
+ "cu . m",
351
+ "cm 2",
352
+ "rs .",
353
+ "rs",
354
+ "kg",
355
+ "g",
356
+ "month",
357
+ "km",
358
+ "m",
359
+ "cm",
360
+ "mm",
361
+ "apple",
362
+ "liter",
363
+ "loss",
364
+ "yard",
365
+ "pure",
366
+ "year",
367
+ "increase",
368
+ "decrease",
369
+ "d",
370
+ "less",
371
+ "Surface",
372
+ "litre",
373
+ "pi sq m",
374
+ "s .",
375
+ "metre",
376
+ "meter",
377
+ "inch",
378
+ ]
379
+
380
+ unit_texts.extend([t + "s" for t in unit_texts])
381
+
382
+
383
+ def _strip_string(string):
384
+ def _fix_fracs(string):
385
+ substrs = string.split("\\frac")
386
+ new_str = substrs[0]
387
+ if len(substrs) > 1:
388
+ substrs = substrs[1:]
389
+ for substr in substrs:
390
+ new_str += "\\frac"
391
+ if substr[0] == "{":
392
+ new_str += substr
393
+ else:
394
+ try:
395
+ assert len(substr) >= 2
396
+ except Exception:
397
+ return string
398
+ a = substr[0]
399
+ b = substr[1]
400
+ if b != "{":
401
+ if len(substr) > 2:
402
+ post_substr = substr[2:]
403
+ new_str += "{" + a + "}{" + b + "}" + post_substr
404
+ else:
405
+ new_str += "{" + a + "}{" + b + "}"
406
+ else:
407
+ if len(substr) > 2:
408
+ post_substr = substr[2:]
409
+ new_str += "{" + a + "}" + b + post_substr
410
+ else:
411
+ new_str += "{" + a + "}" + b
412
+ string = new_str
413
+ return string
414
+
415
+ def _fix_a_slash_b(string):
416
+ if len(string.split("/")) != 2:
417
+ return string
418
+ a = string.split("/")[0]
419
+ b = string.split("/")[1]
420
+ try:
421
+ a = int(a)
422
+ b = int(b)
423
+ assert string == "{}/{}".format(a, b)
424
+ new_string = "\\frac{" + str(a) + "}{" + str(b) + "}"
425
+ return new_string
426
+ except Exception:
427
+ return string
428
+
429
+ def _remove_right_units(string):
430
+ # "\\text{ " only ever occurs (at least in the val set) when describing units
431
+ if "\\text{ " in string:
432
+ splits = string.split("\\text{ ")
433
+ assert len(splits) == 2
434
+ return splits[0]
435
+ else:
436
+ return string
437
+
438
+ def _fix_sqrt(string):
439
+ if "\\sqrt" not in string:
440
+ return string
441
+ splits = string.split("\\sqrt")
442
+ new_string = splits[0]
443
+ for split in splits[1:]:
444
+ if split[0] != "{":
445
+ a = split[0]
446
+ new_substr = "\\sqrt{" + a + "}" + split[1:]
447
+ else:
448
+ new_substr = "\\sqrt" + split
449
+ new_string += new_substr
450
+ return new_string
451
+
452
+ # linebreaks
453
+ string = string.replace("\n", "")
454
+ # print(string)
455
+
456
+ # remove inverse spaces
457
+ string = string.replace("\\!", "")
458
+ # print(string)
459
+
460
+ # replace \\ with \
461
+ string = string.replace("\\\\", "\\")
462
+ # print(string)
463
+
464
+ # matrix
465
+ string = re.sub(r"\\begin\{array\}\{.*?\}", r"\\begin{pmatrix}", string)
466
+ string = re.sub(r"\\end\{array\}", r"\\end{pmatrix}", string)
467
+ string = string.replace("bmatrix", "pmatrix")
468
+
469
+ # replace tfrac and dfrac with frac
470
+ string = string.replace("tfrac", "frac")
471
+ string = string.replace("dfrac", "frac")
472
+ string = (
473
+ string.replace("\\neq", "\\ne")
474
+ .replace("\\leq", "\\le")
475
+ .replace("\\geq", "\\ge")
476
+ )
477
+ # print(string)
478
+
479
+ # remove \left and \right
480
+ string = string.replace("\\left", "")
481
+ string = string.replace("\\right", "")
482
+ # print(string)
483
+
484
+ # Remove unit: miles, dollars if after is not none
485
+ _string = re.sub(r"\\text{.*?}$", "", string).strip()
486
+ if _string != "" and _string != string:
487
+ # print("Warning: unit not removed: '{}' -> '{}'".format(string, _string))
488
+ string = _string
489
+
490
+ # Remove unit: texts
491
+ for _ in range(2):
492
+ for unit_text in unit_texts:
493
+ # use regex, the prefix should be either the start of the string or a non-alphanumeric character
494
+ # the suffix should be either the end of the string or a non-alphanumeric character
495
+ _string = re.sub(r"(^|\W)" + unit_text + r"($|\W)", r"\1\2", string)
496
+ if _string != "":
497
+ string = _string
498
+
499
+ # Remove circ (degrees)
500
+ string = string.replace("^{\\circ}", "")
501
+ string = string.replace("^\\circ", "")
502
+
503
+ # remove dollar signs
504
+ string = string.replace("\\$", "")
505
+
506
+ # remove units (on the right)
507
+ string = _remove_right_units(string)
508
+
509
+ # remove percentage
510
+ string = string.replace("\\%", "")
511
+ string = string.replace(r"\%", "")
512
+
513
+ # " 0." equivalent to " ." and "{0." equivalent to "{." Alternatively, add "0" if "." is the start of the string
514
+ string = string.replace(" .", " 0.")
515
+ string = string.replace("{.", "{0.")
516
+ # if empty, return empty string
517
+ if len(string) == 0:
518
+ return string
519
+ if string[0] == ".":
520
+ string = "0" + string
521
+
522
+ # to consider: get rid of e.g. "k = " or "q = " at beginning
523
+ if len(string.split("=")) == 2:
524
+ if len(string.split("=")[0]) <= 2:
525
+ string = string.split("=")[1]
526
+
527
+ # fix sqrt3 --> sqrt{3}
528
+ string = _fix_sqrt(string)
529
+
530
+ # remove spaces
531
+ string = string.replace(" ", "")
532
+
533
+ # \frac1b or \frac12 --> \frac{1}{b} and \frac{1}{2}, etc. Even works with \frac1{72} (but not \frac{72}1). Also does a/b --> \\frac{a}{b}
534
+ string = _fix_fracs(string)
535
+
536
+ # manually change 0.5 --> \frac{1}{2}
537
+ if string == "0.5":
538
+ string = "\\frac{1}{2}"
539
+
540
+ # NOTE: X/Y changed to \frac{X}{Y} in dataset, but in simple cases fix in case the model output is X/Y
541
+ string = _fix_a_slash_b(string)
542
+
543
+ return string
544
+
545
+
546
+ SUBSTITUTIONS = [
547
+ ("an ", ""),
548
+ ("a ", ""),
549
+ (".$", "$"),
550
+ ("\\$", ""),
551
+ (r"\ ", ""),
552
+ (" ", ""),
553
+ ("mbox", "text"),
554
+ (",\\text{and}", ","),
555
+ ("\\text{and}", ","),
556
+ ("\\text{m}", "\\text{}"),
557
+ ]
558
+
559
+
560
+ REMOVED_EXPRESSIONS = [
561
+ "square",
562
+ "ways",
563
+ "integers",
564
+ "dollars",
565
+ "mph",
566
+ "inches",
567
+ "ft",
568
+ "hours",
569
+ "km",
570
+ "units",
571
+ "\\ldots",
572
+ "sue",
573
+ "points",
574
+ "feet",
575
+ "minutes",
576
+ "digits",
577
+ "cents",
578
+ "degrees",
579
+ "cm",
580
+ "gm",
581
+ "pounds",
582
+ "meters",
583
+ "meals",
584
+ "edges",
585
+ "students",
586
+ "childrentickets",
587
+ "multiples",
588
+ "\\text{s}",
589
+ "\\text{.}",
590
+ "\\text{\ns}",
591
+ "\\text{}^2",
592
+ "\\text{}^3",
593
+ "\\text{\n}",
594
+ "\\text{}",
595
+ r"\mathrm{th}",
596
+ r"^\circ",
597
+ r"^{\circ}",
598
+ r"\;",
599
+ r",\!",
600
+ "{,}",
601
+ '"',
602
+ "\\dots",
603
+ ]
604
+
605
+
606
+ def normalize_final_answer(final_answer: str) -> str:
607
+ """
608
+ Normalize a final answer to a quantitative reasoning question.
609
+ This code comes from https://arxiv.org/pdf/2206.14858.pdf, page18.
610
+ """
611
+ # final_answer = final_answer.split("=")[-1]
612
+
613
+ for before, after in SUBSTITUTIONS:
614
+ final_answer = final_answer.replace(before, after)
615
+ for expr in REMOVED_EXPRESSIONS:
616
+ final_answer = final_answer.replace(expr, "")
617
+
618
+ # Extract answer that is in LaTeX math, is bold,
619
+ # is surrounded by a box, etc.
620
+ final_answer = re.sub(r"(.*?)(\$)(.*?)(\$)(.*)", "$\\3$", final_answer)
621
+ final_answer = re.sub(r"(\\text\{)(.*?)(\})", "\\2", final_answer)
622
+ final_answer = re.sub(r"(\\textbf\{)(.*?)(\})", "\\2", final_answer)
623
+ final_answer = re.sub(r"(\\overline\{)(.*?)(\})", "\\2", final_answer)
624
+ final_answer = re.sub(r"(\\boxed\{)(.*)(\})", "\\2", final_answer)
625
+
626
+ # Normalize shorthand TeX:
627
+ # \fracab -> \frac{a}{b}
628
+ # \frac{abc}{bef} -> \frac{abc}{bef}
629
+ # \fracabc -> \frac{a}{b}c
630
+ # \sqrta -> \sqrt{a}
631
+ # \sqrtab -> sqrt{a}b
632
+ final_answer = re.sub(r"(frac)([^{])(.)", "frac{\\2}{\\3}", final_answer)
633
+ final_answer = re.sub(r"(sqrt)([^{])", "sqrt{\\2}", final_answer)
634
+ final_answer = final_answer.replace("$", "")
635
+
636
+ # Normalize 100,000 -> 100000
637
+ if final_answer.replace(",", "").isdigit():
638
+ final_answer = final_answer.replace(",", "")
639
+
640
+ return final_answer
641
+
642
+
643
+ def repeatness(s: str):
644
+ def ranks(values):
645
+ index = {v: i for i, v in enumerate(sorted(set(values)))}
646
+ return [index[v] for v in values]
647
+
648
+ def suffixArray(s):
649
+ line = ranks(s)
650
+ n, k, ans, sa = len(s), 1, line, [0] * len(s)
651
+ while k < n - 1:
652
+ line = ranks(list(zip_longest(line, islice(line, k, None), fillvalue=-1)))
653
+ ans, k = line, k << 1
654
+ for i, k in enumerate(ans):
655
+ sa[k] = i
656
+ return ans, sa
657
+
658
+ def lcp(arr, suffixArr, inv_suff):
659
+ n, ans, k = len(arr), [0] * len(arr), 0
660
+
661
+ for i in range(n):
662
+ if inv_suff[i] == n - 1:
663
+ k = 0
664
+ continue
665
+
666
+ j = suffixArr[inv_suff[i] + 1]
667
+ while i + k < n and j + k < n and arr[i + k] == arr[j + k]:
668
+ k += 1
669
+
670
+ ans[inv_suff[i]] = k
671
+ if k > 0:
672
+ k -= 1
673
+
674
+ return ans
675
+
676
+ arr = [ord(i) for i in s]
677
+ n = len(arr)
678
+ if n <= 1:
679
+ return 0
680
+ c, sa = suffixArray(arr)
681
+ cnt = sum(lcp(arr, sa, c))
682
+
683
+ return (cnt * 2 / (n * (n + 1))) > 0.2
684
+
685
+
686
+ class timeout:
687
+ def __init__(self, seconds=1, error_message="Timeout"):
688
+ self.seconds = seconds
689
+ self.error_message = error_message
690
+ self._armed = False
691
+ self._old_handler = None
692
+
693
+ def handle_timeout(self, signum, frame):
694
+ raise TimeoutError(self.error_message)
695
+
696
+ def __enter__(self):
697
+ if threading.current_thread() is not threading.main_thread():
698
+ return self
699
+ self._old_handler = signal.getsignal(signal.SIGALRM)
700
+ signal.signal(signal.SIGALRM, self.handle_timeout)
701
+ signal.alarm(self.seconds)
702
+ self._armed = True
703
+ return self
704
+
705
+ def __exit__(self, type, value, traceback):
706
+ if self._armed:
707
+ signal.alarm(0)
708
+ signal.signal(signal.SIGALRM, self._old_handler)
709
+ self._armed = False
710
+
711
+
712
+ def latex_eval(latex):
713
+ sym = parse_latex(latex)
714
+ val = sym.evalf()
715
+ return sym, val
716
+
717
+
718
+ def numeric_equal(prediction: float, reference: float):
719
+ # Note that relative tolerance has significant impact
720
+ # on the result of the synthesized GSM-Hard dataset
721
+ # if reference.is_integer():
722
+ # return isclose(reference, round(prediction), abs_tol=1e-4)
723
+ # else:
724
+ # prediction = round(prediction, len(str(reference).split(".")[-1]))
725
+ return isclose(reference, prediction, rel_tol=1e-4)
726
+
727
+
728
+ def symbolic_equal(a, b):
729
+ def _parse(s):
730
+ for f in [parse_latex, parse_expr, latex2sympy]:
731
+ try:
732
+ return f(s.replace("\\\\", "\\"))
733
+ except Exception:
734
+ try:
735
+ return f(s)
736
+ except Exception:
737
+ pass
738
+ return s
739
+
740
+ a = _parse(a)
741
+ b = _parse(b)
742
+
743
+ # direct equal
744
+ try:
745
+ if str(a) == str(b) or a == b:
746
+ return True
747
+ except Exception:
748
+ pass
749
+
750
+ # simplify equal
751
+ try:
752
+ if a.equals(b) or simplify(a - b) == 0:
753
+ return True
754
+ except Exception:
755
+ pass
756
+
757
+ # equation equal
758
+ try:
759
+ if (abs(a.lhs - a.rhs)).equals(abs(b.lhs - b.rhs)):
760
+ return True
761
+ except Exception:
762
+ pass
763
+
764
+ try:
765
+ if numeric_equal(float(N(a)), float(N(b))):
766
+ return True
767
+ except Exception:
768
+ pass
769
+
770
+ # matrix
771
+ try:
772
+ # if a and b are matrix
773
+ if a.shape == b.shape:
774
+ _a = a.applyfunc(lambda x: round(x, 3))
775
+ _b = b.applyfunc(lambda x: round(x, 3))
776
+ if _a.equals(_b):
777
+ return True
778
+ except Exception:
779
+ pass
780
+
781
+ return False
782
+
783
+
784
+ def _is_latex_equal(str1, str2):
785
+ try:
786
+ sym1, val1 = latex_eval(str1)
787
+ sym2, val2 = latex_eval(str2)
788
+ if sym1 == sym2 or val1 == val2:
789
+ return True
790
+ else:
791
+ raise ValueError
792
+ except Exception: # noqa
793
+ try:
794
+ norm1, norm2 = normalize_final_answer(str1), normalize_final_answer(str2)
795
+ sym1, val1 = latex_eval(norm1)
796
+ sym2, val2 = latex_eval(norm2)
797
+ if sym1 == sym2 or val1 == val2:
798
+ return True
799
+ except Exception: # noqa
800
+ return norm1 == norm2
801
+ return False
802
+
803
+
804
+ def is_latex_equal(given_answer: str, ground_truth: str) -> bool:
805
+ try:
806
+ with timeout(1):
807
+ try:
808
+ if (len(given_answer) > 128 and repeatness(given_answer)) or (
809
+ len(ground_truth) > 128 and repeatness(ground_truth)
810
+ ):
811
+ return False
812
+ # First conduct normalized string matching.
813
+ ground_truth_normalized = _normalize(ground_truth)
814
+ given_normalized = _normalize(given_answer)
815
+ if ground_truth_normalized is None:
816
+ return False
817
+ if ground_truth_normalized == given_normalized:
818
+ return True
819
+
820
+ # Next call math verify.
821
+ given_answer.replace("\n", "")
822
+ ground_truth.replace("\n", "")
823
+ if "$" not in given_answer:
824
+ given_answer = f"${given_answer}$"
825
+ if "$" not in ground_truth:
826
+ ground_truth = f"${ground_truth}$"
827
+ return verify(
828
+ parse(
829
+ ground_truth,
830
+ extraction_config=(
831
+ LatexExtractionConfig(boxed_match_priority=0),
832
+ ExprExtractionConfig(),
833
+ ),
834
+ fallback_mode="no_fallback",
835
+ extraction_mode=["first_match"],
836
+ parsing_timeout=1,
837
+ ),
838
+ parse(
839
+ given_answer,
840
+ extraction_config=(
841
+ LatexExtractionConfig(boxed_match_priority=0),
842
+ ExprExtractionConfig(),
843
+ ),
844
+ fallback_mode="no_fallback",
845
+ extraction_mode=["first_match"],
846
+ parsing_timeout=1,
847
+ ),
848
+ timeout_seconds=1,
849
+ )
850
+ # or symbolic_equal(ground_truth, given_answer)
851
+ except Exception:
852
+ return False
853
+ except TimeoutError:
854
+ return False
855
+
856
+
857
+ def is_value_equal(given_answer: str, ground_truth: str) -> bool:
858
+ assert ground_truth is not None
859
+ ground_truth_normalized_mathd = mathd_normalize_answer(ground_truth)
860
+ given_answer_normalized_mathd = mathd_normalize_answer(given_answer)
861
+
862
+ str_equal = ground_truth_normalized_mathd == given_answer_normalized_mathd
863
+ try:
864
+ number_equal = float(ground_truth_normalized_mathd) == float(
865
+ given_answer_normalized_mathd
866
+ )
867
+ return str_equal or number_equal
868
+ except Exception:
869
+ return str_equal
870
+
871
+
872
+ # sympy might hang -- we don't care about trying to be lenient in these cases
873
+ BAD_SUBSTRINGS = ["^{", "^("]
874
+ BAD_REGEXES = [r"\^[0-9]+\^", r"\^[0-9][0-9]+"]
875
+ TUPLE_CHARS = "()[]"
876
+
877
+
878
+ def _sympy_parse(expr: str):
879
+ """Parses an expression with sympy."""
880
+ py_expr = expr.replace("^", "**")
881
+ return sympy_parser.parse_expr(
882
+ py_expr,
883
+ transformations=(
884
+ sympy_parser.standard_transformations
885
+ + (sympy_parser.implicit_multiplication_application,)
886
+ ),
887
+ )
888
+
889
+
890
+ def _parse_latex(expr: str) -> str:
891
+ """Attempts to parse latex to an expression sympy can read."""
892
+ expr = expr.replace("\\tfrac", "\\frac")
893
+ expr = expr.replace("\\dfrac", "\\frac")
894
+ expr = expr.replace("\\frac", " \\frac") # Play nice with mixed numbers.
895
+ expr = latex2text.LatexNodes2Text().latex_to_text(expr)
896
+
897
+ # Replace the specific characters that this parser uses.
898
+ expr = expr.replace("√", "sqrt")
899
+ expr = expr.replace("π", "pi")
900
+ expr = expr.replace("∞", "inf")
901
+ expr = expr.replace("∪", "U")
902
+ expr = expr.replace("·", "*")
903
+ expr = expr.replace("×", "*")
904
+
905
+ return expr.strip()
906
+
907
+
908
+ def _is_float(num: str) -> bool:
909
+ try:
910
+ float(num)
911
+ return True
912
+ except ValueError:
913
+ return False
914
+
915
+
916
+ def _is_int(x: float) -> bool:
917
+ try:
918
+ return abs(x - int(round(x))) <= 1e-7
919
+ except Exception:
920
+ return False
921
+
922
+
923
+ def _is_frac(expr: str) -> bool:
924
+ return bool(re.search(r"^-?[0-9]+.?/0*[1-9][0-9]*.?$", expr))
925
+
926
+
927
+ def _str_is_int(x: str) -> bool:
928
+ try:
929
+ x = _strip_properly_formatted_commas(x)
930
+ x = float(x)
931
+ return abs(x - int(round(x))) <= 1e-7
932
+ except Exception:
933
+ return False
934
+
935
+
936
+ def _str_to_int(x: str) -> bool:
937
+ x = x.replace(",", "")
938
+ x = float(x)
939
+ return int(x)
940
+
941
+
942
+ def _inject_implicit_mixed_number(step: str):
943
+ """
944
+ Automatically make a mixed number evalable
945
+ e.g. 7 3/4 => 7+3/4
946
+ """
947
+ p1 = re.compile("([0-9]) +([0-9])")
948
+ step = p1.sub("\\1+\\2", step) ## implicit mults
949
+ return step
950
+
951
+
952
+ def _strip_properly_formatted_commas(expr: str):
953
+ # We want to be careful because we don't want to strip tuple commas
954
+ p1 = re.compile(r"(\d)(,)(\d\d\d)($|\D)")
955
+ while True:
956
+ next_expr = p1.sub("\\1\\3\\4", expr)
957
+ if next_expr == expr:
958
+ break
959
+ expr = next_expr
960
+ return next_expr
961
+
962
+
963
+ def _normalize(expr: str) -> str:
964
+ """Normalize answer expressions."""
965
+ if expr is None:
966
+ return None
967
+
968
+ # Remove enclosing `\text{}`.
969
+ m = re.search(r"^\\text\{(?P<text>.+?)\}$", expr)
970
+ if m is not None:
971
+ expr = m.group("text")
972
+
973
+ expr = expr.replace("\\%", "%")
974
+ expr = expr.replace("\\$", "$")
975
+ expr = expr.replace("$", "")
976
+ expr = expr.replace("%", "")
977
+ expr = expr.replace(" or ", " , ")
978
+ expr = expr.replace(" and ", " , ")
979
+
980
+ expr = expr.replace("million", "*10^6")
981
+ expr = expr.replace("billion", "*10^9")
982
+ expr = expr.replace("trillion", "*10^12")
983
+
984
+ for unit in [
985
+ "degree",
986
+ "cm",
987
+ "centimeter",
988
+ "meter",
989
+ "mile",
990
+ "second",
991
+ "minute",
992
+ "hour",
993
+ "day",
994
+ "week",
995
+ "month",
996
+ "year",
997
+ "foot",
998
+ "feet",
999
+ "inch",
1000
+ "yard",
1001
+ ]:
1002
+ expr = re.sub(rf"{unit}(es)?(s)? *(\^[0-9]+)?", "", expr)
1003
+ expr = re.sub(r"\^ *\\\\circ", "", expr)
1004
+
1005
+ if len(expr) > 0 and expr[0] == "{" and expr[-1] == "}":
1006
+ expr = expr[1:-1]
1007
+
1008
+ expr = re.sub(",\\\\! *", "", expr)
1009
+ if _is_float(expr) and _is_int(float(expr)):
1010
+ expr = str(int(round(float(expr))))
1011
+ if "\\" in expr:
1012
+ try:
1013
+ expr = _parse_latex(expr)
1014
+ except Exception:
1015
+ pass
1016
+
1017
+ # edge case with mixed numbers and negative signs
1018
+ expr = re.sub("- *", "-", expr)
1019
+
1020
+ expr = _inject_implicit_mixed_number(expr)
1021
+ expr = expr.replace(" ", "")
1022
+
1023
+ # if we somehow still have latex braces here, just drop them
1024
+ expr = expr.replace("{", "")
1025
+ expr = expr.replace("}", "")
1026
+
1027
+ # don't be case sensitive for text answers
1028
+ expr = expr.lower()
1029
+
1030
+ if _str_is_int(expr):
1031
+ expr = str(_str_to_int(expr))
1032
+
1033
+ return expr
1034
+
1035
+
1036
+ def count_unknown_letters_in_expr(expr: str):
1037
+ expr = expr.replace("sqrt", "")
1038
+ expr = expr.replace("frac", "")
1039
+ letters_in_expr = set([x for x in expr if x.isalpha()])
1040
+ return len(letters_in_expr)
1041
+
1042
+
1043
+ def should_allow_eval(expr: str):
1044
+ # we don't want to try parsing unknown text or functions of more than two variables
1045
+ if count_unknown_letters_in_expr(expr) > 2:
1046
+ return False
1047
+
1048
+ for bad_string in BAD_SUBSTRINGS:
1049
+ if bad_string in expr:
1050
+ return False
1051
+
1052
+ for bad_regex in BAD_REGEXES:
1053
+ if re.search(bad_regex, expr) is not None:
1054
+ return False
1055
+
1056
+ return True
1057
+
1058
+
1059
+ def are_equal_under_sympy(ground_truth_normalized: str, given_normalized: str):
1060
+ are_equal = False
1061
+ try:
1062
+ expr = f"({ground_truth_normalized})-({given_normalized})"
1063
+ if should_allow_eval(expr):
1064
+ sympy_diff = _sympy_parse(expr)
1065
+ simplified = sympy.simplify(sympy_diff)
1066
+ if simplified == 0:
1067
+ are_equal = True
1068
+ except Exception:
1069
+ pass
1070
+ return are_equal
1071
+
1072
+
1073
+ def split_tuple(expr: str):
1074
+ """
1075
+ Split the elements in a tuple/interval, while handling well-formatted commas in large numbers
1076
+ """
1077
+ expr = _strip_properly_formatted_commas(expr)
1078
+ if len(expr) == 0:
1079
+ return []
1080
+ if (
1081
+ len(expr) > 2
1082
+ and expr[0] in TUPLE_CHARS
1083
+ and expr[-1] in TUPLE_CHARS
1084
+ and all([ch not in expr[1:-1] for ch in TUPLE_CHARS])
1085
+ ):
1086
+ elems = [elem.strip() for elem in expr[1:-1].split(",")]
1087
+ else:
1088
+ elems = [expr]
1089
+ return elems
1090
+
1091
+
1092
+ def last_boxed_only_string(string):
1093
+ idx = string.rfind("\\boxed")
1094
+ if idx < 0:
1095
+ idx = string.rfind("\\fbox")
1096
+ if idx < 0:
1097
+ return None
1098
+
1099
+ i = idx
1100
+ right_brace_idx = None
1101
+ num_left_braces_open = 0
1102
+ while i < len(string):
1103
+ if string[i] == "{":
1104
+ num_left_braces_open += 1
1105
+ if string[i] == "}":
1106
+ num_left_braces_open -= 1
1107
+ if num_left_braces_open == 0:
1108
+ right_brace_idx = i
1109
+ break
1110
+ i += 1
1111
+
1112
+ if right_brace_idx is None:
1113
+ retval = None
1114
+ else:
1115
+ retval = string[idx : right_brace_idx + 1]
1116
+
1117
+ return retval
1118
+
1119
+
1120
+ def remove_boxed(s):
1121
+ left = "\\boxed{"
1122
+ try:
1123
+ assert s[: len(left)] == left
1124
+ assert s[-1] == "}"
1125
+ return s[len(left) : -1]
1126
+ except Exception:
1127
+ return None
1128
+
1129
+
1130
+ def extract_boxed_answer(solution: str) -> str:
1131
+ """Extract the answer from inside a LaTeX \\boxed{} command"""
1132
+ solution = last_boxed_only_string(solution)
1133
+ solution = remove_boxed(solution)
1134
+ return solution
1135
+
1136
+
1137
+ def grade_answer_sympy(given_answer: str, ground_truth: str) -> bool:
1138
+ ground_truth_normalized = _normalize(ground_truth)
1139
+ given_normalized = _normalize(given_answer)
1140
+
1141
+ if ground_truth_normalized is None:
1142
+ return False
1143
+
1144
+ if ground_truth_normalized == given_normalized:
1145
+ return True
1146
+
1147
+ if len(given_normalized) == 0:
1148
+ return False
1149
+
1150
+ ground_truth_elems = split_tuple(ground_truth_normalized)
1151
+ given_elems = split_tuple(given_normalized)
1152
+
1153
+ if len(ground_truth_elems) > 1 and (
1154
+ ground_truth_normalized[0] != given_normalized[0]
1155
+ or ground_truth_normalized[-1] != given_normalized[-1]
1156
+ ):
1157
+ is_correct = False
1158
+ elif len(ground_truth_elems) != len(given_elems):
1159
+ is_correct = False
1160
+ else:
1161
+ for ground_truth_elem, given_elem in zip(ground_truth_elems, given_elems):
1162
+ if _is_frac(ground_truth_elem) and _is_frac(given_elem):
1163
+ # if fractions aren't reduced, then shouldn't be marked as correct
1164
+ # so, we don't want to allow sympy.simplify in this case
1165
+ is_correct = ground_truth_elem == given_elem
1166
+ elif _str_is_int(ground_truth_elem) != _str_is_int(given_elem):
1167
+ # if the ground truth answer is an integer, we require the given answer to be a strict match (no sympy.simplify)
1168
+ is_correct = False
1169
+ else:
1170
+ is_correct = are_equal_under_sympy(ground_truth_elem, given_elem)
1171
+ if not is_correct:
1172
+ break
1173
+
1174
+ return is_correct
1175
+
1176
+
1177
+ def grade_answer_mathd(given_answer: str, ground_truth: str) -> bool:
1178
+ ground_truth_normalized_mathd = mathd_normalize_answer(ground_truth)
1179
+ given_answer_normalized_mathd = mathd_normalize_answer(given_answer)
1180
+
1181
+ # be at least as lenient as mathd
1182
+ if ground_truth_normalized_mathd == given_answer_normalized_mathd:
1183
+ return True
1184
+ return False
1185
+
1186
+
1187
+ def extract_answer(passage: str) -> str:
1188
+ if "\\boxed" in passage:
1189
+ return extract_boxed_answer(passage)
1190
+ return None
1191
+
1192
+
1193
+ def _parse_modebench_spec(gt_answer: Any) -> dict[str, Any] | None:
1194
+ if isinstance(gt_answer, dict):
1195
+ spec = gt_answer
1196
+ elif isinstance(gt_answer, str):
1197
+ text = gt_answer.strip()
1198
+ if not (text.startswith("{") and text.endswith("}")):
1199
+ return None
1200
+ try:
1201
+ spec = json.loads(text)
1202
+ except Exception:
1203
+ return None
1204
+ else:
1205
+ return None
1206
+ verifier = spec.get("verifier")
1207
+ if verifier in {
1208
+ "graph_coloring",
1209
+ "countdown",
1210
+ MATHIR_VERIFIER,
1211
+ MATHIR_MENU_VERIFIER,
1212
+ PANTRY_PLAN_VERIFIER,
1213
+ PYTHON_FACTOR_VERIFIER,
1214
+ POINT_MAZE_VERIFIER,
1215
+ ANT_MAZE_VERIFIER,
1216
+ }:
1217
+ return spec
1218
+ return None
1219
+
1220
+
1221
+ PYTHON_FACTOR_RESPONSE_SURFACE_VERSION = (
1222
+ "python-factor-response-v2-latex-lambda"
1223
+ )
1224
+
1225
+
1226
+ def _normalize_python_factor_lambda_surface(candidate: str) -> str:
1227
+ """Normalize one formatting-only LaTeX spelling of ``lambda n:``."""
1228
+
1229
+ # Qwen's native boxed surface can typeset the Python keyword as the LaTeX
1230
+ # command ``\lambda``. Accept only the exact required signature (plus the
1231
+ # conventional ``\,`` spacing alias); the restricted AST parser and
1232
+ # isolated executable validator remain the authority.
1233
+ return re.sub(
1234
+ r"^\\lambda(?:\s+|\\,\s*)n\s*:\s*",
1235
+ "lambda n: ",
1236
+ str(candidate).strip(),
1237
+ count=1,
1238
+ ).strip()
1239
+
1240
+
1241
+ def _extract_modebench_candidate(model_response: str, gt_answer: Any) -> str | None:
1242
+ spec = _parse_modebench_spec(gt_answer)
1243
+ if spec is None:
1244
+ return None
1245
+ if "\\boxed" in str(model_response):
1246
+ candidate = extract_answer(str(model_response))
1247
+ if candidate is None:
1248
+ return None
1249
+ if str(spec.get("verifier")) == PYTHON_FACTOR_VERIFIER:
1250
+ candidate = _normalize_python_factor_lambda_surface(candidate)
1251
+ return candidate or None
1252
+ candidate = str(model_response).strip()
1253
+ if not candidate:
1254
+ return None
1255
+ if str(spec.get("verifier")) in {
1256
+ MATHIR_VERIFIER,
1257
+ MATHIR_MENU_VERIFIER,
1258
+ }:
1259
+ fenced = re.fullmatch(
1260
+ r"```(?:mathir)?\s*(.*?)\s*```",
1261
+ candidate,
1262
+ flags=re.IGNORECASE | re.DOTALL,
1263
+ )
1264
+ if fenced is not None:
1265
+ candidate = fenced.group(1).strip()
1266
+ if len(candidate) > 200 or "<" in candidate or ">" in candidate:
1267
+ return None
1268
+ # Whitespace, a terminal semicolon, and an all-program code fence are
1269
+ # formatting aliases. The restricted parser remains the authority.
1270
+ return candidate or None
1271
+ if str(spec.get("verifier")) == PYTHON_FACTOR_VERIFIER:
1272
+ fenced = re.fullmatch(
1273
+ r"```(?:python)?\s*(.*?)\s*```",
1274
+ candidate,
1275
+ flags=re.IGNORECASE | re.DOTALL,
1276
+ )
1277
+ if fenced is not None:
1278
+ candidate = fenced.group(1).strip()
1279
+ if (
1280
+ len(candidate) > 240
1281
+ or "\n" in candidate
1282
+ or "\r" in candidate
1283
+ or "<" in candidate
1284
+ or ">" in candidate
1285
+ ):
1286
+ return None
1287
+ candidate = re.sub(
1288
+ r"^\s*(?:the\s+)?(?:final\s+)?(?:answer|program|function)\s*"
1289
+ r"(?:is|=|:)\s*",
1290
+ "",
1291
+ candidate,
1292
+ flags=re.IGNORECASE,
1293
+ ).strip()
1294
+ candidate = _normalize_python_factor_lambda_surface(candidate)
1295
+ return candidate or None
1296
+ if str(spec.get("verifier")) in {
1297
+ POINT_MAZE_VERIFIER,
1298
+ ANT_MAZE_VERIFIER,
1299
+ }:
1300
+ fenced = re.fullmatch(
1301
+ r"```(?:actions?|plan)?\s*(.*?)\s*```",
1302
+ candidate,
1303
+ flags=re.IGNORECASE | re.DOTALL,
1304
+ )
1305
+ if fenced is not None:
1306
+ candidate = fenced.group(1).strip()
1307
+ if len(candidate) > 4096 or "<" in candidate or ">" in candidate:
1308
+ return None
1309
+ candidate = re.sub(
1310
+ r"^\s*(?:the\s+)?(?:final\s+)?(?:answer|plan|program|actions?)\s*"
1311
+ r"(?:is|=|:)\s*",
1312
+ "",
1313
+ candidate,
1314
+ flags=re.IGNORECASE,
1315
+ ).strip()
1316
+ return candidate or None
1317
+ if str(spec.get("verifier")) == PANTRY_PLAN_VERIFIER:
1318
+ if (
1319
+ len(candidate) > 512
1320
+ or "\n" in candidate
1321
+ or "\r" in candidate
1322
+ or "<" in candidate
1323
+ or ">" in candidate
1324
+ ):
1325
+ return None
1326
+ candidate = re.sub(
1327
+ r"^\s*(?:the\s+)?(?:final\s+)?(?:answer|plan|recipe)\s*"
1328
+ r"(?:is|=|:)\s*",
1329
+ "",
1330
+ candidate,
1331
+ flags=re.IGNORECASE,
1332
+ ).strip()
1333
+ return candidate or None
1334
+ if "\n" in candidate or "\r" in candidate or "<" in candidate or ">" in candidate:
1335
+ return None
1336
+ if len(candidate) > 160:
1337
+ return None
1338
+ candidate = re.sub(
1339
+ r"^\s*(?:the\s+)?(?:final\s+)?(?:answer|expression|coloring|program)\s*"
1340
+ r"(?:is|=|:)\s*",
1341
+ "",
1342
+ candidate,
1343
+ flags=re.IGNORECASE,
1344
+ ).strip()
1345
+ return candidate or None
1346
+
1347
+
1348
+ def _parse_graph_coloring_answer(candidate: str, n: int) -> list[int] | None:
1349
+ text = str(candidate).strip().lower()
1350
+ text = re.sub(r"^(?:coloring|answer)\s*(?:is|=|:)\s*", "", text).strip()
1351
+ compact = re.sub(r"[\s,;|\[\]\(\)\{\}:.-]+", "", text)
1352
+ if len(compact) == n and all(ch in "123" for ch in compact):
1353
+ return [int(ch) for ch in compact]
1354
+ tokens = re.findall(r"[123]", text)
1355
+ if len(tokens) == n:
1356
+ return [int(token) for token in tokens]
1357
+ return None
1358
+
1359
+
1360
+ def _parse_graph_digit_sequence(candidate: str, expected_len: int) -> list[int] | None:
1361
+ text = str(candidate).strip().lower()
1362
+ text = re.sub(
1363
+ r"^(?:missing\s+)?(?:colors?|digits?|answer)\s*(?:are|is|=|:)\s*",
1364
+ "",
1365
+ text,
1366
+ ).strip()
1367
+ compact = re.sub(r"[\s,;|\[\]\(\)\{\}:.-]+", "", text)
1368
+ if len(compact) == expected_len and all(ch in "123" for ch in compact):
1369
+ return [int(ch) for ch in compact]
1370
+ tokens = re.findall(r"[123]", text)
1371
+ if len(tokens) == expected_len:
1372
+ return [int(token) for token in tokens]
1373
+ return None
1374
+
1375
+
1376
+ def _verify_graph_coloring_colors(
1377
+ colors: list[int] | None,
1378
+ spec: dict[str, Any],
1379
+ ) -> bool:
1380
+ """Validate one already-parsed coloring object against its problem."""
1381
+
1382
+ try:
1383
+ n = int(spec["n"])
1384
+ edges = spec["edges"]
1385
+ except Exception:
1386
+ return False
1387
+ if colors is None or len(colors) != n:
1388
+ return False
1389
+ partial_colors = spec.get("partial_colors")
1390
+ if partial_colors is not None:
1391
+ try:
1392
+ if len(partial_colors) != n:
1393
+ return False
1394
+ for index, color in enumerate(partial_colors):
1395
+ if color is None:
1396
+ continue
1397
+ if colors[index] != int(color):
1398
+ return False
1399
+ except Exception:
1400
+ return False
1401
+ for edge in edges:
1402
+ try:
1403
+ u, v = int(edge[0]), int(edge[1])
1404
+ except Exception:
1405
+ return False
1406
+ if u < 1 or v < 1 or u > n or v > n:
1407
+ return False
1408
+ if colors[u - 1] == colors[v - 1]:
1409
+ return False
1410
+ return True
1411
+
1412
+
1413
+ def _verify_graph_coloring_answer(candidate: str, spec: dict[str, Any]) -> bool:
1414
+ colors = _graph_coloring_from_candidate(candidate, spec)
1415
+ return _verify_graph_coloring_colors(colors, spec)
1416
+
1417
+
1418
+ def _normalize_countdown_expression(candidate: str) -> str:
1419
+ text = str(candidate).strip()
1420
+ text = text.replace("\\times", "*").replace("\\cdot", "*")
1421
+ text = text.replace("\\div", "/").replace("÷", "/").replace("×", "*")
1422
+ text = text.replace("^", "**")
1423
+ text = re.sub(r"^\s*(?:expression|answer)\s*(?:is|=|:)\s*", "", text, flags=re.I)
1424
+ return text.strip()
1425
+
1426
+
1427
+ def _countdown_eval_and_numbers(node: ast.AST) -> tuple[Fraction, list[int]]:
1428
+ if isinstance(node, ast.Expression):
1429
+ return _countdown_eval_and_numbers(node.body)
1430
+ if isinstance(node, ast.Constant):
1431
+ if isinstance(node.value, bool) or not isinstance(node.value, int):
1432
+ raise ValueError("Countdown constants must be integers.")
1433
+ return Fraction(int(node.value), 1), [int(node.value)]
1434
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
1435
+ value, numbers = _countdown_eval_and_numbers(node.operand)
1436
+ if isinstance(node.op, ast.USub):
1437
+ value = -value
1438
+ return value, numbers
1439
+ if isinstance(node, ast.BinOp):
1440
+ left, left_numbers = _countdown_eval_and_numbers(node.left)
1441
+ right, right_numbers = _countdown_eval_and_numbers(node.right)
1442
+ if isinstance(node.op, ast.Add):
1443
+ value = left + right
1444
+ elif isinstance(node.op, ast.Sub):
1445
+ value = left - right
1446
+ elif isinstance(node.op, ast.Mult):
1447
+ value = left * right
1448
+ elif isinstance(node.op, ast.Div):
1449
+ if right == 0:
1450
+ raise ValueError("Countdown division by zero.")
1451
+ value = left / right
1452
+ else:
1453
+ raise ValueError("Unsupported Countdown operator.")
1454
+ return value, left_numbers + right_numbers
1455
+ raise ValueError("Unsupported Countdown expression.")
1456
+
1457
+
1458
+ def _verify_countdown_expression(candidate: str, spec: dict[str, Any]) -> bool:
1459
+ try:
1460
+ target = Fraction(int(spec["target"]), 1)
1461
+ expected_numbers = Counter(int(value) for value in spec["numbers"])
1462
+ except Exception:
1463
+ return False
1464
+ text = _normalize_countdown_expression(candidate)
1465
+ if not text:
1466
+ return False
1467
+ parts = [part.strip() for part in text.split("=") if part.strip()]
1468
+ if not parts:
1469
+ parts = [text]
1470
+ for part in parts:
1471
+ if not re.fullmatch(r"[0-9+\-*/().\s*]+", part):
1472
+ continue
1473
+ try:
1474
+ parsed = ast.parse(part, mode="eval")
1475
+ value, used_numbers = _countdown_eval_and_numbers(parsed)
1476
+ except Exception:
1477
+ continue
1478
+ if value == target and Counter(used_numbers) == expected_numbers:
1479
+ return True
1480
+ return False
1481
+
1482
+
1483
+ def _graph_coloring_from_candidate(
1484
+ candidate: str,
1485
+ spec: dict[str, Any],
1486
+ ) -> list[int] | None:
1487
+ try:
1488
+ n = int(spec["n"])
1489
+ except Exception:
1490
+ return None
1491
+ colors = _parse_graph_coloring_answer(candidate, n)
1492
+ partial_colors = spec.get("partial_colors")
1493
+ if colors is None and partial_colors is not None:
1494
+ try:
1495
+ hidden_positions = [
1496
+ index for index, color in enumerate(partial_colors) if color is None
1497
+ ]
1498
+ fill = _parse_graph_digit_sequence(candidate, len(hidden_positions))
1499
+ if fill is not None:
1500
+ colors = [
1501
+ int(color) if color is not None else 0 for color in partial_colors
1502
+ ]
1503
+ for index, color in zip(hidden_positions, fill):
1504
+ colors[index] = color
1505
+ except Exception:
1506
+ return None
1507
+ if colors is None or len(colors) != n:
1508
+ return None
1509
+ return colors
1510
+
1511
+
1512
+ def _canonical_countdown_ast(node: ast.AST) -> str:
1513
+ if isinstance(node, ast.Expression):
1514
+ return _canonical_countdown_ast(node.body)
1515
+ if isinstance(node, ast.Constant):
1516
+ if isinstance(node.value, bool) or not isinstance(node.value, int):
1517
+ raise ValueError("Countdown constants must be integers.")
1518
+ return str(int(node.value))
1519
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
1520
+ inner = _canonical_countdown_ast(node.operand)
1521
+ if isinstance(node.op, ast.USub):
1522
+ return f"neg({inner})"
1523
+ return inner
1524
+ if isinstance(node, ast.BinOp):
1525
+ left = _canonical_countdown_ast(node.left)
1526
+ right = _canonical_countdown_ast(node.right)
1527
+ if isinstance(node.op, ast.Add):
1528
+ parts = sorted([left, right])
1529
+ return f"add({parts[0]},{parts[1]})"
1530
+ if isinstance(node.op, ast.Mult):
1531
+ parts = sorted([left, right])
1532
+ return f"mul({parts[0]},{parts[1]})"
1533
+ if isinstance(node.op, ast.Sub):
1534
+ return f"sub({left},{right})"
1535
+ if isinstance(node.op, ast.Div):
1536
+ return f"div({left},{right})"
1537
+ raise ValueError("Unsupported Countdown expression.")
1538
+
1539
+
1540
+ def _canonical_countdown_route_ast(node: ast.AST) -> str:
1541
+ """Canonical operator/dependency skeleton with numeric leaves abstracted."""
1542
+
1543
+ if isinstance(node, ast.Expression):
1544
+ return _canonical_countdown_route_ast(node.body)
1545
+ if isinstance(node, ast.Constant):
1546
+ if isinstance(node.value, bool) or not isinstance(node.value, int):
1547
+ raise ValueError("Countdown constants must be integers.")
1548
+ return "input"
1549
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
1550
+ inner = _canonical_countdown_route_ast(node.operand)
1551
+ return f"neg({inner})" if isinstance(node.op, ast.USub) else inner
1552
+ if isinstance(node, ast.BinOp):
1553
+ left = _canonical_countdown_route_ast(node.left)
1554
+ right = _canonical_countdown_route_ast(node.right)
1555
+ if isinstance(node.op, ast.Add):
1556
+ parts = sorted([left, right])
1557
+ return f"add({parts[0]},{parts[1]})"
1558
+ if isinstance(node.op, ast.Mult):
1559
+ parts = sorted([left, right])
1560
+ return f"mul({parts[0]},{parts[1]})"
1561
+ if isinstance(node.op, ast.Sub):
1562
+ return f"sub({left},{right})"
1563
+ if isinstance(node.op, ast.Div):
1564
+ return f"div({left},{right})"
1565
+ raise ValueError("Unsupported Countdown route expression.")
1566
+
1567
+
1568
+ def _canonical_countdown_expression_key(
1569
+ candidate: str,
1570
+ spec: dict[str, Any],
1571
+ ) -> str | None:
1572
+ try:
1573
+ expected_numbers = Counter(int(value) for value in spec["numbers"])
1574
+ except Exception:
1575
+ return None
1576
+ text = _normalize_countdown_expression(candidate)
1577
+ if not text:
1578
+ return None
1579
+ parts = [part.strip() for part in text.split("=") if part.strip()] or [text]
1580
+ for part in parts:
1581
+ if not re.fullmatch(r"[0-9+\-*/().\s*]+", part):
1582
+ continue
1583
+ try:
1584
+ parsed = ast.parse(part, mode="eval")
1585
+ _, used_numbers = _countdown_eval_and_numbers(parsed)
1586
+ if Counter(used_numbers) != expected_numbers:
1587
+ continue
1588
+ return f"countdown:{_canonical_countdown_ast(parsed)}"
1589
+ except Exception:
1590
+ continue
1591
+ return None
1592
+
1593
+
1594
+ def _modebench_answer_key(
1595
+ model_response: str,
1596
+ gt_answer: Any,
1597
+ ) -> str | None:
1598
+ spec = _parse_modebench_spec(gt_answer)
1599
+ if spec is None:
1600
+ return None
1601
+ candidate = _extract_modebench_candidate(model_response, gt_answer)
1602
+ if candidate is None:
1603
+ return None
1604
+ verifier = str(spec.get("verifier"))
1605
+ if verifier == "graph_coloring":
1606
+ colors = _graph_coloring_from_candidate(candidate, spec)
1607
+ if colors is None:
1608
+ return None
1609
+ return "graph_coloring:" + "".join(str(int(color)) for color in colors)
1610
+ if verifier == "countdown":
1611
+ return _canonical_countdown_expression_key(candidate, spec)
1612
+ if verifier == MATHIR_VERIFIER:
1613
+ validation = validate_mathir_algebra(candidate, spec)
1614
+ return validation.canonical_key if validation is not None else None
1615
+ if verifier == MATHIR_MENU_VERIFIER:
1616
+ validation = validate_mathir_action_menu(candidate, spec)
1617
+ return validation.canonical_key if validation is not None else None
1618
+ if verifier == PYTHON_FACTOR_VERIFIER:
1619
+ validation = validate_python_factor_function_external(candidate, spec)
1620
+ return validation.canonical_key if validation is not None else None
1621
+ if verifier == PANTRY_PLAN_VERIFIER:
1622
+ validation = validate_pantry_plan(candidate, spec)
1623
+ return validation.canonical_key if validation is not None else None
1624
+ if verifier in {POINT_MAZE_VERIFIER, ANT_MAZE_VERIFIER}:
1625
+ validation = validate_maze_action_program_external(candidate, spec)
1626
+ return validation.canonical_key if validation is not None else None
1627
+ return None
1628
+
1629
+
1630
+ def validated_modebench_outcome_key(
1631
+ model_response: str,
1632
+ gt_answer: Any,
1633
+ ) -> str | None:
1634
+ """Return a canonical outcome only when that same response verifies.
1635
+
1636
+ This is the admission boundary for online canonical banks. It deliberately
1637
+ supports only ModeBench tasks with executable validators:
1638
+
1639
+ - graph colorings are parsed and checked against every graph edge;
1640
+ - Countdown expressions are parsed, checked for exact operand use, and
1641
+ executed against the requested target.
1642
+
1643
+ - MathIR algebra programs are parsed by a restricted grammar, executed as
1644
+ state transformations, exact-normalized, and accepted only when execution
1645
+ isolates the right solution. Their key comes from those executed states.
1646
+
1647
+ - Python factor functions are syntax-restricted and called in an isolated
1648
+ Python worker. Their key is the vector returned by those exact tool calls.
1649
+
1650
+ Ordinary MATH final-answer grading is not a proof/strategy verifier and is
1651
+ therefore rejected here rather than being mislabeled as canonical search.
1652
+ """
1653
+
1654
+ spec = _parse_modebench_spec(gt_answer)
1655
+ if spec is None:
1656
+ return None
1657
+ candidate = _extract_modebench_candidate(model_response, gt_answer)
1658
+ if candidate is None:
1659
+ return None
1660
+ verifier = str(spec.get("verifier"))
1661
+ if verifier == "graph_coloring":
1662
+ colors = _graph_coloring_from_candidate(candidate, spec)
1663
+ if not _verify_graph_coloring_colors(colors, spec):
1664
+ return None
1665
+ assert colors is not None
1666
+ return "graph_coloring:" + "".join(str(int(color)) for color in colors)
1667
+ if verifier == MATHIR_VERIFIER:
1668
+ validation = validate_mathir_algebra(candidate, spec)
1669
+ # The key is constructed from the exact normalized equation states
1670
+ # produced by the same interpreter execution that validated the answer.
1671
+ return validation.canonical_key if validation is not None else None
1672
+ if verifier == MATHIR_MENU_VERIFIER:
1673
+ validation = validate_mathir_action_menu(candidate, spec)
1674
+ # Menu labels are expanded first. Identity comes only from the exact
1675
+ # normalized states produced by executing those concrete operations.
1676
+ return validation.canonical_key if validation is not None else None
1677
+ if verifier == PYTHON_FACTOR_VERIFIER:
1678
+ validation = validate_python_factor_function_external(candidate, spec)
1679
+ return validation.canonical_key if validation is not None else None
1680
+ if verifier == PANTRY_PLAN_VERIFIER:
1681
+ validation = validate_pantry_plan(candidate, spec)
1682
+ return validation.canonical_key if validation is not None else None
1683
+ if verifier in {POINT_MAZE_VERIFIER, ANT_MAZE_VERIFIER}:
1684
+ validation = validate_maze_action_program_external(candidate, spec)
1685
+ return validation.canonical_key if validation is not None else None
1686
+ if verifier != "countdown":
1687
+ return None
1688
+ try:
1689
+ target = Fraction(int(spec["target"]), 1)
1690
+ expected_numbers = Counter(int(value) for value in spec["numbers"])
1691
+ except Exception:
1692
+ return None
1693
+ text = _normalize_countdown_expression(candidate)
1694
+ parts = [part.strip() for part in text.split("=") if part.strip()] or [text]
1695
+ for part in parts:
1696
+ if not re.fullmatch(r"[0-9+\-*/().\s*]+", part):
1697
+ continue
1698
+ try:
1699
+ parsed = ast.parse(part, mode="eval")
1700
+ value, used_numbers = _countdown_eval_and_numbers(parsed)
1701
+ if value != target or Counter(used_numbers) != expected_numbers:
1702
+ continue
1703
+ # The key is derived from the exact AST object that passed
1704
+ # execution and operand validation above.
1705
+ return f"countdown:{_canonical_countdown_ast(parsed)}"
1706
+ except Exception:
1707
+ continue
1708
+ return None
1709
+
1710
+
1711
+ @dataclass(frozen=True)
1712
+ class VerifiedExplorationIdentity:
1713
+ """Separate prompt-local endpoint and cross-prompt route identities."""
1714
+
1715
+ verifier: str
1716
+ endpoint_key: str
1717
+ route_signature: str | None
1718
+
1719
+
1720
+ def validated_modebench_exploration_identity(
1721
+ model_response: str,
1722
+ gt_answer: Any,
1723
+ ) -> VerifiedExplorationIdentity | None:
1724
+ """Return hierarchical identity only after exact executable validation."""
1725
+
1726
+ spec = _parse_modebench_spec(gt_answer)
1727
+ if spec is None:
1728
+ return None
1729
+ candidate = _extract_modebench_candidate(model_response, gt_answer)
1730
+ if candidate is None:
1731
+ return None
1732
+ verifier = str(spec.get("verifier"))
1733
+ if verifier == "graph_coloring":
1734
+ colors = _graph_coloring_from_candidate(candidate, spec)
1735
+ if not _verify_graph_coloring_colors(colors, spec):
1736
+ return None
1737
+ assert colors is not None
1738
+ endpoint = "graph_coloring:" + "".join(str(int(color)) for color in colors)
1739
+ return VerifiedExplorationIdentity(verifier, endpoint, None)
1740
+ if verifier == MATHIR_VERIFIER:
1741
+ validation = validate_mathir_algebra(candidate, spec)
1742
+ if validation is None:
1743
+ return None
1744
+ solution = validation.solution
1745
+ endpoint = f"mathir-solution:{solution.numerator}/{solution.denominator}"
1746
+ return VerifiedExplorationIdentity(
1747
+ verifier,
1748
+ endpoint,
1749
+ validation.route_signature,
1750
+ )
1751
+ if verifier == MATHIR_MENU_VERIFIER:
1752
+ validation = validate_mathir_action_menu(candidate, spec)
1753
+ if validation is None:
1754
+ return None
1755
+ solution = validation.solution
1756
+ endpoint = f"mathir-solution:{solution.numerator}/{solution.denominator}"
1757
+ return VerifiedExplorationIdentity(
1758
+ verifier,
1759
+ endpoint,
1760
+ validation.route_signature,
1761
+ )
1762
+ if verifier == PYTHON_FACTOR_VERIFIER:
1763
+ validation = validate_python_factor_function_external(candidate, spec)
1764
+ if validation is None:
1765
+ return None
1766
+ try:
1767
+ route = python_factor_route_signature(candidate)
1768
+ except Exception:
1769
+ return None
1770
+ return VerifiedExplorationIdentity(
1771
+ verifier,
1772
+ validation.canonical_key,
1773
+ route,
1774
+ )
1775
+ if verifier == PANTRY_PLAN_VERIFIER:
1776
+ validation = validate_pantry_plan(candidate, spec)
1777
+ if validation is None:
1778
+ return None
1779
+ return VerifiedExplorationIdentity(
1780
+ verifier,
1781
+ validation.canonical_key,
1782
+ None,
1783
+ )
1784
+ if verifier in {POINT_MAZE_VERIFIER, ANT_MAZE_VERIFIER}:
1785
+ validation = validate_maze_action_program_external(candidate, spec)
1786
+ if validation is None:
1787
+ return None
1788
+ return VerifiedExplorationIdentity(
1789
+ verifier,
1790
+ f"{verifier}:goal:{spec.get('map_id')}",
1791
+ validation.canonical_key,
1792
+ )
1793
+ if verifier != "countdown":
1794
+ return None
1795
+ try:
1796
+ target = Fraction(int(spec["target"]), 1)
1797
+ expected_numbers = Counter(int(value) for value in spec["numbers"])
1798
+ except Exception:
1799
+ return None
1800
+ text = _normalize_countdown_expression(candidate)
1801
+ parts = [part.strip() for part in text.split("=") if part.strip()] or [text]
1802
+ for part in parts:
1803
+ if not re.fullmatch(r"[0-9+\-*/().\s*]+", part):
1804
+ continue
1805
+ try:
1806
+ parsed = ast.parse(part, mode="eval")
1807
+ value, used_numbers = _countdown_eval_and_numbers(parsed)
1808
+ if value != target or Counter(used_numbers) != expected_numbers:
1809
+ continue
1810
+ endpoint = f"countdown-value:{value.numerator}/{value.denominator}"
1811
+ route = "countdown-route:v1:" + _canonical_countdown_route_ast(parsed)
1812
+ return VerifiedExplorationIdentity(verifier, endpoint, route)
1813
+ except Exception:
1814
+ continue
1815
+ return None
1816
+
1817
+
1818
+ def _grade_modebench_answer(model_answer: str, gt_answer: Any) -> bool | None:
1819
+ spec = _parse_modebench_spec(gt_answer)
1820
+ if spec is None:
1821
+ return None
1822
+ verifier = str(spec.get("verifier"))
1823
+ if verifier == "graph_coloring":
1824
+ return _verify_graph_coloring_answer(model_answer, spec)
1825
+ if verifier == "countdown":
1826
+ return _verify_countdown_expression(model_answer, spec)
1827
+ if verifier == MATHIR_VERIFIER:
1828
+ return validate_mathir_algebra(model_answer, spec) is not None
1829
+ if verifier == MATHIR_MENU_VERIFIER:
1830
+ return validate_mathir_action_menu(model_answer, spec) is not None
1831
+ if verifier == PYTHON_FACTOR_VERIFIER:
1832
+ return validate_python_factor_function_external(model_answer, spec) is not None
1833
+ if verifier == PANTRY_PLAN_VERIFIER:
1834
+ return validate_pantry_plan(model_answer, spec) is not None
1835
+ if verifier in {POINT_MAZE_VERIFIER, ANT_MAZE_VERIFIER}:
1836
+ return validate_maze_action_program_external(model_answer, spec) is not None
1837
+ return False
1838
+
1839
+
1840
+ def _clean_final_answer_candidate(candidate: str | None) -> str | None:
1841
+ """Return a compact final-answer candidate, or ``None`` for malformed text."""
1842
+
1843
+ if candidate is None:
1844
+ return None
1845
+ candidate = str(candidate).strip()
1846
+ if not candidate:
1847
+ return None
1848
+ # Answer identity is deliberately stricter than correctness grading: mode
1849
+ # metrics need one stable, compact key per formatted final answer.
1850
+ if "\n" in candidate or "\r" in candidate or "<" in candidate or ">" in candidate:
1851
+ return None
1852
+ if len(candidate) > 160:
1853
+ return None
1854
+ candidate = re.sub(
1855
+ r"^\s*(?:the\s+)?(?:final\s+)?answer\s*(?:is|=|:)\s*",
1856
+ "",
1857
+ candidate,
1858
+ flags=re.IGNORECASE,
1859
+ ).strip()
1860
+ return candidate or None
1861
+
1862
+
1863
+ def _extract_r1_reasoning_and_answer_sections(
1864
+ model_response: str,
1865
+ ) -> tuple[str | None, str | None]:
1866
+ """Return ``(<think> body, <answer> body)`` for an R1-style trace.
1867
+
1868
+ Training prompts already end inside an open ``<think>`` tag, so many model
1869
+ responses begin with reasoning text and only emit the closing ``</think>``
1870
+ before ``<answer>``. We accept both:
1871
+
1872
+ 1. full tagged traces containing ``<think>...</think><answer>...</answer>``
1873
+ 2. response-only continuations containing ``... </think> <answer>...</answer>``
1874
+ """
1875
+
1876
+ if "<answer>" not in model_response or "</answer>" not in model_response:
1877
+ return None, None
1878
+ try:
1879
+ prefix, answer_suffix = model_response.split("<answer>", 1)
1880
+ answer = answer_suffix.split("</answer>", 1)[0].strip()
1881
+ reasoning = None
1882
+ if "<think>" in prefix and "</think>" in prefix:
1883
+ reasoning = prefix.split("<think>", 1)[1].split("</think>", 1)[0].strip()
1884
+ elif "</think>" in prefix:
1885
+ reasoning = prefix.split("</think>", 1)[0].strip()
1886
+ else:
1887
+ return None, None
1888
+ answer = answer
1889
+ except Exception:
1890
+ return None, None
1891
+ return reasoning or None, answer or None
1892
+
1893
+
1894
+ def extract_normalized_final_answer(
1895
+ model_response: str, *, template: str = "r1", gt_answer: Any = None
1896
+ ) -> str | None:
1897
+ """Return a conservative canonical key for an answer or exact benchmark mode."""
1898
+
1899
+ try:
1900
+ if gt_answer is not None:
1901
+ if _parse_modebench_spec(gt_answer) is not None:
1902
+ return _modebench_answer_key(
1903
+ model_response,
1904
+ gt_answer,
1905
+ )
1906
+ modebench_key = _modebench_answer_key(
1907
+ model_response,
1908
+ gt_answer,
1909
+ )
1910
+ if modebench_key is not None:
1911
+ return modebench_key
1912
+ candidate = None
1913
+ if template == "r1":
1914
+ # Match the training reward's strict R1 formatting gate.
1915
+ _, candidate = _extract_r1_reasoning_and_answer_sections(model_response)
1916
+ if candidate is None:
1917
+ return None
1918
+ else:
1919
+ candidate = extract_answer(model_response)
1920
+ if candidate is None:
1921
+ return None
1922
+ extracted = extract_answer(candidate) if "\\boxed" in candidate else candidate
1923
+ extracted = _clean_final_answer_candidate(extracted)
1924
+ if extracted is None:
1925
+ return None
1926
+ normalized = normalize_final_answer(extracted)
1927
+ normalized = _normalize(normalized)
1928
+ if normalized is None:
1929
+ normalized = normalize_final_answer(extracted)
1930
+ if normalized is None:
1931
+ return None
1932
+ normalized = str(normalized).strip().lower()
1933
+ return normalized or None
1934
+ except Exception:
1935
+ return None
1936
+
1937
+
1938
+ def grade(model_answer: str, gt_answer: str, fast: bool = True):
1939
+ if "\\boxed" in gt_answer:
1940
+ gt_answer = extract_answer(gt_answer)
1941
+ correct = grade_answer_mathd(model_answer, gt_answer) or grade_answer_sympy(
1942
+ model_answer, gt_answer
1943
+ )
1944
+ if not fast:
1945
+ # This mode further uses math_verify to recall originally false positives.
1946
+ # Will be a bit slower, and sensitive to bad inputs.
1947
+ correct = correct or is_latex_equal(
1948
+ model_answer,
1949
+ gt_answer,
1950
+ )
1951
+ return correct
1952
+
1953
+
1954
+ def boxed_reward_fn(model_response, gt_answer, fast=False):
1955
+ model_answer = _extract_modebench_candidate(model_response, gt_answer)
1956
+ if model_answer is not None:
1957
+ modebench_correct = _grade_modebench_answer(model_answer, gt_answer)
1958
+ if modebench_correct is not None:
1959
+ return {"formatted": True}, 1.0 if modebench_correct else 0.0
1960
+ model_answer = extract_answer(model_response)
1961
+ if model_answer is None:
1962
+ return {"formatted": False}, 0.0 # Cannot even parse anything.
1963
+ modebench_correct = _grade_modebench_answer(model_answer, gt_answer)
1964
+ if modebench_correct is not None:
1965
+ return {"formatted": True}, 1.0 if modebench_correct else 0.0
1966
+ if isinstance(gt_answer, float) or isinstance(gt_answer, int):
1967
+ gt_answer = str(gt_answer)
1968
+ if isinstance(gt_answer, str):
1969
+ is_correct = grade(model_answer, gt_answer, fast)
1970
+ elif isinstance(gt_answer, list):
1971
+ is_correct = False
1972
+ for gt in gt_answer:
1973
+ is_correct |= grade(model_answer, gt, fast)
1974
+ if is_correct:
1975
+ return {"formatted": True}, 1.0 # Correctness reward.
1976
+ else:
1977
+ return {
1978
+ "formatted": True
1979
+ }, 0.0 # Formatted but wrong answer; no format reward to avoid hacking.
1980
+
1981
+
1982
+ def validated_math_route_signature(
1983
+ model_response: str,
1984
+ problem: str,
1985
+ gt_answer: Any,
1986
+ *,
1987
+ fast: bool = False,
1988
+ task_verified: bool | None = None,
1989
+ ) -> str | None:
1990
+ """Return an executable route identity only for a task-correct response.
1991
+
1992
+ Task correctness, route execution, and agreement between the trace terminal
1993
+ value and the response's boxed answer are independent fail-closed checks.
1994
+ A correct answer without a valid trace keeps its ordinary task reward but
1995
+ has no route identity.
1996
+ """
1997
+
1998
+ try:
1999
+ if task_verified is None:
2000
+ _info, reward = boxed_reward_fn(
2001
+ model_response,
2002
+ gt_answer,
2003
+ fast=fast,
2004
+ )
2005
+ task_verified = float(reward) > 0.0
2006
+ if not bool(task_verified):
2007
+ return None
2008
+ validation = validate_math_route_response(model_response, problem)
2009
+ if validation is None:
2010
+ return None
2011
+ model_answer = extract_answer(model_response)
2012
+ if model_answer is None:
2013
+ return None
2014
+ terminal_answer = sympy.latex(validation.terminal_value)
2015
+ if not grade(model_answer, terminal_answer, fast=fast):
2016
+ return None
2017
+ return validation.route_signature
2018
+ except Exception:
2019
+ return None
2020
+
2021
+
2022
+ def validated_exploration_identity(
2023
+ model_response: str,
2024
+ problem: str,
2025
+ gt_answer: Any,
2026
+ *,
2027
+ fast: bool = False,
2028
+ task_verified: bool | None = None,
2029
+ ) -> VerifiedExplorationIdentity | None:
2030
+ """Return the endpoint/route pair for ModeBench or free-form MATH.
2031
+
2032
+ ModeBench references always remain on their exact executable validator
2033
+ path. Free-form MATH may reuse the actor's already-computed task verdict,
2034
+ but route admission still independently executes the restricted trace and
2035
+ checks its terminal value against the boxed response. Thus a task-correct
2036
+ response without a valid route retains an endpoint identity and ordinary
2037
+ reward while contributing no route identity.
2038
+ """
2039
+
2040
+ if _parse_modebench_spec(gt_answer) is not None:
2041
+ return validated_modebench_exploration_identity(
2042
+ model_response,
2043
+ gt_answer,
2044
+ )
2045
+ try:
2046
+ if task_verified is None:
2047
+ _info, reward = boxed_reward_fn(
2048
+ model_response,
2049
+ gt_answer,
2050
+ fast=fast,
2051
+ )
2052
+ task_verified = float(reward) > 0.0
2053
+ if not bool(task_verified):
2054
+ return None
2055
+ endpoint = extract_normalized_final_answer(
2056
+ model_response,
2057
+ template="qwen_math_route",
2058
+ gt_answer=gt_answer,
2059
+ )
2060
+ if endpoint is None:
2061
+ return None
2062
+ route = validated_math_route_signature(
2063
+ model_response,
2064
+ problem,
2065
+ gt_answer,
2066
+ fast=fast,
2067
+ task_verified=True,
2068
+ )
2069
+ return VerifiedExplorationIdentity(
2070
+ verifier="math_verify",
2071
+ endpoint_key=f"math-answer:{endpoint}",
2072
+ route_signature=route,
2073
+ )
2074
+ except Exception:
2075
+ return None
2076
+
2077
+
2078
+ def answer_tag_reward_fn(model_response, gt_answer, fast=False):
2079
+ # We are strict about format to evaluate our models.
2080
+ if "</think> <answer>" in model_response and "</answer>" in model_response:
2081
+ model_answer = model_response.split("<answer>")[-1].replace("</answer>", "")
2082
+ if "\\boxed" in model_answer:
2083
+ model_answer = extract_answer(model_answer)
2084
+ if model_answer is None:
2085
+ return {"formatted": True}, 0.0
2086
+ modebench_plain_answer = _extract_modebench_candidate(model_answer, gt_answer)
2087
+ if modebench_plain_answer is not None:
2088
+ model_answer = modebench_plain_answer
2089
+ modebench_correct = _grade_modebench_answer(model_answer, gt_answer)
2090
+ if modebench_correct is not None:
2091
+ return {"formatted": True}, 1.0 if modebench_correct else 0.0
2092
+ if isinstance(gt_answer, float) or isinstance(gt_answer, int):
2093
+ gt_answer = str(gt_answer)
2094
+ if isinstance(gt_answer, str):
2095
+ is_correct = grade(model_answer, gt_answer, fast)
2096
+ elif isinstance(gt_answer, list):
2097
+ is_correct = False
2098
+ for gt in gt_answer:
2099
+ is_correct |= grade(model_answer, gt, fast)
2100
+ if is_correct:
2101
+ return {"formatted": True}, 1.0 # Correctness reward.
2102
+ else:
2103
+ return (
2104
+ {"formatted": True},
2105
+ 0.0,
2106
+ ) # Formatted but wrong answer; no format reward to avoid hacking.
2107
+ else:
2108
+ return {"formatted": False}, 0.0 # Unformatted.
2109
+
2110
+
2111
+ def answer_tag_reward_fn_for_orz(model_response, gt_answer, fast=False):
2112
+ # We are a bit less strict for baselines.
2113
+ if "<answer>" in model_response and "</answer>" in model_response:
2114
+ model_answer = model_response.split("<answer>")[-1].replace("</answer>", "")
2115
+ if "\\boxed" in model_answer:
2116
+ model_answer = extract_answer(model_answer)
2117
+ if model_answer is None:
2118
+ return {"formatted": True}, 0.0
2119
+ modebench_plain_answer = _extract_modebench_candidate(model_answer, gt_answer)
2120
+ if modebench_plain_answer is not None:
2121
+ model_answer = modebench_plain_answer
2122
+ modebench_correct = _grade_modebench_answer(model_answer, gt_answer)
2123
+ if modebench_correct is not None:
2124
+ return {"formatted": True}, 1.0 if modebench_correct else 0.0
2125
+ if isinstance(gt_answer, float) or isinstance(gt_answer, int):
2126
+ gt_answer = str(gt_answer)
2127
+ if isinstance(gt_answer, str):
2128
+ is_correct = grade(model_answer, gt_answer, fast)
2129
+ elif isinstance(gt_answer, list):
2130
+ is_correct = False
2131
+ for gt in gt_answer:
2132
+ is_correct |= grade(model_answer, gt, fast)
2133
+ if is_correct:
2134
+ return {"formatted": True}, 1.0 # Correctness reward.
2135
+ else:
2136
+ return (
2137
+ {"formatted": True},
2138
+ 0.0,
2139
+ ) # Formatted but wrong answer; no format reward to avoid hacking.
2140
+ else:
2141
+ return {"formatted": False}, 0.0 # Unformatted.
code/oat_drgrpo/math_route.py ADDED
@@ -0,0 +1,458 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fail-closed executable route traces for answer-verified free-form math.
2
+
3
+ The trace is deliberately separate from the natural-language derivation and
4
+ from the boxed answer. It contains only references and operations; it never
5
+ contains model-declared intermediate results. Numeric leaves must be grounded
6
+ in the problem text, every operation is executed exactly, and every trace node
7
+ must contribute to the terminal value.
8
+
9
+ This validator establishes a checkable computational route, not a proof that
10
+ the route's modeling assumptions follow from the prose problem. Ordinary MATH
11
+ answer verification remains a separate mandatory admission condition.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections import Counter
17
+ from dataclasses import dataclass
18
+ from fractions import Fraction
19
+ import json
20
+ import math
21
+ import re
22
+ from typing import Any, Mapping
23
+
24
+ import sympy
25
+
26
+
27
+ MATH_ROUTE_VERSION = "math-route-v1"
28
+ MATH_ROUTE_RPN_VERSION = "math-route-rpn-v2"
29
+ _MAX_TRACE_CHARS = 4_096
30
+ _MAX_STEPS = 20
31
+ _MAX_ARGS = 6
32
+ _MAX_INTEGER_BITS = 512
33
+ _ID_RE = re.compile(r"s[1-9][0-9]?")
34
+ _NUMBER_RE = re.compile(
35
+ r"(?<![\w.])-?\d+(?:,\d{3})*(?:\.\d+)?(?!\w)(?!\.\d)"
36
+ )
37
+ _SLASH_FRACTION_RE = re.compile(
38
+ r"(?<![\w.])(-?\d+(?:,\d{3})*)\s*/\s*(\d+(?:,\d{3})*)"
39
+ r"(?!\w)(?!\.\d)"
40
+ )
41
+ _LATEX_FRACTION_RE = re.compile(
42
+ r"\\(?:d?frac)\s*\{\s*(-?\d+(?:,\d{3})*)\s*\}"
43
+ r"\s*\{\s*(\d+(?:,\d{3})*)\s*\}"
44
+ )
45
+ _ROUTE_BLOCK_RE = re.compile(r"<route>(.*?)</route>", re.DOTALL)
46
+ _COMMUTATIVE_OPS = frozenset({"add", "mul", "gcd", "lcm", "min", "max"})
47
+ _UNARY_OPS = frozenset(
48
+ {"neg", "abs", "square", "cube", "sqrt", "factorial", "percent"}
49
+ )
50
+ _BINARY_OPS = frozenset(
51
+ {"sub", "div", "pow", "mod", "choose", "permute"}
52
+ )
53
+ _NARY_OPS = frozenset({"add", "mul", "gcd", "lcm", "min", "max", "average"})
54
+ _ALLOWED_TOP_LEVEL = frozenset({"version", "steps", "final"})
55
+ _ALLOWED_STEP_KEYS = frozenset({"id", "op", "args", "value"})
56
+ _RPN_UNARY_OPS = {
57
+ "neg": "neg",
58
+ "abs": "abs",
59
+ "square": "square",
60
+ "cube": "cube",
61
+ "sqrt": "sqrt",
62
+ "factorial": "factorial",
63
+ "percent": "percent",
64
+ }
65
+ _RPN_BINARY_OPS = {
66
+ "add": "add",
67
+ "mul": "mul",
68
+ "sub": "sub",
69
+ "div": "div",
70
+ "pow": "pow",
71
+ "mod": "mod",
72
+ "choose": "choose",
73
+ "permute": "permute",
74
+ "gcd": "gcd",
75
+ "lcm": "lcm",
76
+ "min": "min",
77
+ "max": "max",
78
+ "average": "average",
79
+ }
80
+
81
+
82
+ @dataclass(frozen=True)
83
+ class MathRouteValidation:
84
+ route_signature: str
85
+ terminal_value: sympy.Expr
86
+ operations: tuple[str, ...]
87
+ step_count: int
88
+ source_count: int
89
+
90
+
91
+ class MathRouteError(ValueError):
92
+ """Raised for a malformed, ungrounded, or non-executable trace."""
93
+
94
+
95
+ def _fraction(text: str) -> Fraction:
96
+ compact = str(text).replace(",", "").strip()
97
+ if re.fullmatch(r"-?\d+", compact):
98
+ return Fraction(int(compact), 1)
99
+ if re.fullmatch(r"-?\d+/\d+", compact):
100
+ numerator, denominator = compact.split("/", 1)
101
+ if int(denominator) == 0:
102
+ raise MathRouteError("zero denominator")
103
+ return Fraction(int(numerator), int(denominator))
104
+ if re.fullmatch(r"-?\d+\.\d+", compact):
105
+ return Fraction(compact)
106
+ raise MathRouteError("source values must be exact integers, decimals, or fractions")
107
+
108
+
109
+ def problem_number_inventory(problem: str) -> Counter[Fraction]:
110
+ """Return exact numeric leaves present in problem text, with multiplicity."""
111
+
112
+ text = str(problem)
113
+ inventory: Counter[Fraction] = Counter()
114
+
115
+ def consume_latex(match: re.Match[str]) -> str:
116
+ numerator, denominator = match.groups()
117
+ inventory[Fraction(int(numerator.replace(",", "")), int(denominator.replace(",", "")))] += 1
118
+ return " "
119
+
120
+ def consume_slash(match: re.Match[str]) -> str:
121
+ numerator, denominator = match.groups()
122
+ inventory[Fraction(int(numerator.replace(",", "")), int(denominator.replace(",", "")))] += 1
123
+ return " "
124
+
125
+ text = _LATEX_FRACTION_RE.sub(consume_latex, text)
126
+ text = _SLASH_FRACTION_RE.sub(consume_slash, text)
127
+ for match in _NUMBER_RE.finditer(text):
128
+ inventory[_fraction(match.group(0))] += 1
129
+ return inventory
130
+
131
+
132
+ def extract_math_route_block(model_response: str) -> str | None:
133
+ matches = _ROUTE_BLOCK_RE.findall(str(model_response))
134
+ if len(matches) != 1:
135
+ return None
136
+ block = matches[0].strip()
137
+ if not block or len(block) > _MAX_TRACE_CHARS:
138
+ return None
139
+ return block
140
+
141
+
142
+ def _exact_integer(value: sympy.Expr, *, name: str) -> int:
143
+ simplified = sympy.simplify(value)
144
+ if not simplified.is_Integer:
145
+ raise MathRouteError(f"{name} requires an exact integer")
146
+ integer = int(simplified)
147
+ if abs(integer).bit_length() > _MAX_INTEGER_BITS:
148
+ raise MathRouteError(f"{name} integer is too large")
149
+ return integer
150
+
151
+
152
+ def _bounded(value: sympy.Expr) -> sympy.Expr:
153
+ simplified = sympy.simplify(value)
154
+ if simplified.has(
155
+ sympy.nan,
156
+ sympy.zoo,
157
+ sympy.oo,
158
+ -sympy.oo,
159
+ sympy.I,
160
+ ):
161
+ raise MathRouteError("operation produced a non-finite or complex value")
162
+ if len(str(simplified)) > 1_024 or int(sympy.count_ops(simplified)) > 128:
163
+ raise MathRouteError("operation result is too large")
164
+ for atom in simplified.atoms(sympy.Integer):
165
+ if abs(int(atom)).bit_length() > _MAX_INTEGER_BITS:
166
+ raise MathRouteError("operation result integer is too large")
167
+ return simplified
168
+
169
+
170
+ def _execute_operation(op: str, arguments: tuple[sympy.Expr, ...]) -> sympy.Expr:
171
+ if op in _UNARY_OPS and len(arguments) != 1:
172
+ raise MathRouteError(f"{op} requires one argument")
173
+ if op in _BINARY_OPS and len(arguments) != 2:
174
+ raise MathRouteError(f"{op} requires two arguments")
175
+ if op in _NARY_OPS and not 2 <= len(arguments) <= _MAX_ARGS:
176
+ raise MathRouteError(f"{op} requires two to {_MAX_ARGS} arguments")
177
+ if op == "neg":
178
+ result = -arguments[0]
179
+ elif op == "abs":
180
+ result = sympy.Abs(arguments[0])
181
+ elif op == "square":
182
+ result = arguments[0] ** 2
183
+ elif op == "cube":
184
+ result = arguments[0] ** 3
185
+ elif op == "sqrt":
186
+ if arguments[0].is_nonnegative is not True:
187
+ raise MathRouteError("sqrt requires a provably nonnegative argument")
188
+ result = sympy.sqrt(arguments[0])
189
+ elif op == "factorial":
190
+ integer = _exact_integer(arguments[0], name=op)
191
+ if not 0 <= integer <= 100:
192
+ raise MathRouteError("factorial input is outside [0,100]")
193
+ result = sympy.factorial(integer)
194
+ elif op == "percent":
195
+ result = arguments[0] / 100
196
+ elif op == "add":
197
+ result = sum(arguments, sympy.Integer(0))
198
+ elif op == "mul":
199
+ result = math.prod(arguments, start=sympy.Integer(1))
200
+ elif op == "sub":
201
+ result = arguments[0] - arguments[1]
202
+ elif op == "div":
203
+ if sympy.simplify(arguments[1]) == 0:
204
+ raise MathRouteError("division by zero")
205
+ result = arguments[0] / arguments[1]
206
+ elif op == "pow":
207
+ exponent = _exact_integer(arguments[1], name=op)
208
+ if not -12 <= exponent <= 12:
209
+ raise MathRouteError("power exponent is outside [-12,12]")
210
+ if arguments[0] == 0 and exponent < 0:
211
+ raise MathRouteError("zero to a negative power")
212
+ result = arguments[0] ** exponent
213
+ elif op == "mod":
214
+ left = _exact_integer(arguments[0], name=op)
215
+ right = _exact_integer(arguments[1], name=op)
216
+ if right == 0:
217
+ raise MathRouteError("modulo by zero")
218
+ result = sympy.Integer(left % right)
219
+ elif op == "choose":
220
+ n = _exact_integer(arguments[0], name=op)
221
+ k = _exact_integer(arguments[1], name=op)
222
+ if not 0 <= k <= n <= 10_000:
223
+ raise MathRouteError("choose inputs are outside 0 <= k <= n <= 10000")
224
+ result = sympy.binomial(n, k)
225
+ elif op == "permute":
226
+ n = _exact_integer(arguments[0], name=op)
227
+ k = _exact_integer(arguments[1], name=op)
228
+ if not 0 <= k <= n <= 1_000:
229
+ raise MathRouteError("permute inputs are outside 0 <= k <= n <= 1000")
230
+ result = sympy.factorial(n) / sympy.factorial(n - k)
231
+ elif op in {"gcd", "lcm"}:
232
+ integers = [_exact_integer(argument, name=op) for argument in arguments]
233
+ function = math.gcd if op == "gcd" else math.lcm
234
+ result = sympy.Integer(function(*integers))
235
+ elif op == "min":
236
+ if not all(argument.is_real is True for argument in arguments):
237
+ raise MathRouteError("min requires real arguments")
238
+ result = sympy.Min(*arguments)
239
+ elif op == "max":
240
+ if not all(argument.is_real is True for argument in arguments):
241
+ raise MathRouteError("max requires real arguments")
242
+ result = sympy.Max(*arguments)
243
+ elif op == "average":
244
+ result = sum(arguments, sympy.Integer(0)) / len(arguments)
245
+ else:
246
+ raise MathRouteError(f"unsupported route operation {op!r}")
247
+ return _bounded(result)
248
+
249
+
250
+ def _signature(op: str, argument_signatures: tuple[str, ...]) -> str:
251
+ children = (
252
+ tuple(sorted(argument_signatures))
253
+ if op in _COMMUTATIVE_OPS
254
+ else argument_signatures
255
+ )
256
+ return f"{op}({','.join(children)})"
257
+
258
+
259
+ def validate_math_route_trace(
260
+ trace: str | Mapping[str, Any],
261
+ problem: str,
262
+ ) -> MathRouteValidation | None:
263
+ """Parse and execute a grounded route trace; return ``None`` on any failure."""
264
+
265
+ try:
266
+ parsed = json.loads(trace) if isinstance(trace, str) else dict(trace)
267
+ if not isinstance(parsed, dict) or set(parsed) != _ALLOWED_TOP_LEVEL:
268
+ raise MathRouteError("route object has missing or extra fields")
269
+ if parsed["version"] != MATH_ROUTE_VERSION:
270
+ raise MathRouteError("unsupported route version")
271
+ raw_steps = parsed["steps"]
272
+ if not isinstance(raw_steps, list) or not 2 <= len(raw_steps) <= _MAX_STEPS:
273
+ raise MathRouteError("route has an invalid number of steps")
274
+ final_id = str(parsed["final"])
275
+ if _ID_RE.fullmatch(final_id) is None:
276
+ raise MathRouteError("invalid final node ID")
277
+
278
+ inventory = problem_number_inventory(problem)
279
+ values: dict[str, sympy.Expr] = {}
280
+ signatures: dict[str, str] = {}
281
+ dependencies: dict[str, tuple[str, ...]] = {}
282
+ operations: list[str] = []
283
+ source_count = 0
284
+ non_source_count = 0
285
+ for expected_index, raw_step in enumerate(raw_steps, start=1):
286
+ if not isinstance(raw_step, dict):
287
+ raise MathRouteError("route step must be an object")
288
+ if not set(raw_step).issubset(_ALLOWED_STEP_KEYS):
289
+ raise MathRouteError("route step has extra fields")
290
+ step_id = str(raw_step.get("id", ""))
291
+ if step_id != f"s{expected_index}" or step_id in values:
292
+ raise MathRouteError("route node IDs must be contiguous and ordered")
293
+ op = str(raw_step.get("op", ""))
294
+ if op == "source":
295
+ if set(raw_step) != {"id", "op", "value"}:
296
+ raise MathRouteError("source step schema is invalid")
297
+ value = _fraction(str(raw_step["value"]))
298
+ if inventory[value] <= 0:
299
+ raise MathRouteError("source value is not available in the problem")
300
+ inventory[value] -= 1
301
+ values[step_id] = sympy.Rational(value.numerator, value.denominator)
302
+ signatures[step_id] = "input"
303
+ dependencies[step_id] = ()
304
+ source_count += 1
305
+ operations.append(op)
306
+ continue
307
+
308
+ if set(raw_step) != {"id", "op", "args"}:
309
+ raise MathRouteError("operation step schema is invalid")
310
+ raw_args = raw_step["args"]
311
+ if not isinstance(raw_args, list):
312
+ raise MathRouteError("operation args must be a list")
313
+ argument_ids = tuple(str(argument) for argument in raw_args)
314
+ if (
315
+ not argument_ids
316
+ or len(argument_ids) > _MAX_ARGS
317
+ or len(set(argument_ids)) != len(argument_ids)
318
+ or any(argument_id not in values for argument_id in argument_ids)
319
+ ):
320
+ raise MathRouteError("operation dependencies are invalid")
321
+ arguments = tuple(values[argument_id] for argument_id in argument_ids)
322
+ values[step_id] = _execute_operation(op, arguments)
323
+ signatures[step_id] = _signature(
324
+ op,
325
+ tuple(signatures[argument_id] for argument_id in argument_ids),
326
+ )
327
+ dependencies[step_id] = argument_ids
328
+ operations.append(op)
329
+ non_source_count += 1
330
+
331
+ if final_id not in values or non_source_count < 1 or source_count < 1:
332
+ raise MathRouteError("route lacks a computed terminal value")
333
+ reachable = {final_id}
334
+ frontier = [final_id]
335
+ while frontier:
336
+ node = frontier.pop()
337
+ for dependency in dependencies[node]:
338
+ if dependency not in reachable:
339
+ reachable.add(dependency)
340
+ frontier.append(dependency)
341
+ if reachable != set(values):
342
+ raise MathRouteError("every route node must contribute to the final value")
343
+ return MathRouteValidation(
344
+ route_signature=(
345
+ f"math-route:{MATH_ROUTE_VERSION}:{signatures[final_id]}"
346
+ ),
347
+ terminal_value=values[final_id],
348
+ operations=tuple(operations),
349
+ step_count=len(values),
350
+ source_count=source_count,
351
+ )
352
+ except Exception:
353
+ return None
354
+
355
+
356
+ def validate_math_route_rpn(
357
+ trace: str,
358
+ problem: str,
359
+ ) -> MathRouteValidation | None:
360
+ """Execute the compact v2 reverse-Polish route language.
361
+
362
+ Numeric tokens are grounded problem leaves. Unary and binary operator
363
+ tokens consume the stack, so a successful one-item terminal stack also
364
+ proves that every emitted token contributes to the final value. The
365
+ language has no result literals, variable names, prose, or code execution.
366
+ """
367
+
368
+ try:
369
+ compact = str(trace).strip()
370
+ if not compact or len(compact) > 1_024:
371
+ raise MathRouteError("RPN route is empty or too long")
372
+ tokens = compact.split()
373
+ if not tokens or tokens[0] not in {
374
+ "v2",
375
+ MATH_ROUTE_RPN_VERSION,
376
+ }:
377
+ raise MathRouteError("unsupported RPN route version")
378
+ tokens = tokens[1:]
379
+ if not 2 <= len(tokens) <= 40:
380
+ raise MathRouteError("RPN route has an invalid token count")
381
+
382
+ inventory = problem_number_inventory(problem)
383
+ stack: list[tuple[sympy.Expr, str]] = []
384
+ operations: list[str] = []
385
+ source_count = 0
386
+ operation_count = 0
387
+ for token in tokens:
388
+ if token in _RPN_UNARY_OPS:
389
+ if len(stack) < 1:
390
+ raise MathRouteError("RPN unary operation underflow")
391
+ argument_value, argument_signature = stack.pop()
392
+ op = _RPN_UNARY_OPS[token]
393
+ stack.append(
394
+ (
395
+ _execute_operation(op, (argument_value,)),
396
+ _signature(op, (argument_signature,)),
397
+ )
398
+ )
399
+ operations.append(op)
400
+ operation_count += 1
401
+ continue
402
+ if token in _RPN_BINARY_OPS:
403
+ if len(stack) < 2:
404
+ raise MathRouteError("RPN binary operation underflow")
405
+ right_value, right_signature = stack.pop()
406
+ left_value, left_signature = stack.pop()
407
+ op = _RPN_BINARY_OPS[token]
408
+ stack.append(
409
+ (
410
+ _execute_operation(op, (left_value, right_value)),
411
+ _signature(op, (left_signature, right_signature)),
412
+ )
413
+ )
414
+ operations.append(op)
415
+ operation_count += 1
416
+ continue
417
+
418
+ value = _fraction(token)
419
+ if inventory[value] <= 0:
420
+ raise MathRouteError("RPN source value is not available in the problem")
421
+ inventory[value] -= 1
422
+ stack.append(
423
+ (
424
+ sympy.Rational(value.numerator, value.denominator),
425
+ "input",
426
+ )
427
+ )
428
+ operations.append("source")
429
+ source_count += 1
430
+
431
+ if len(stack) != 1 or source_count < 1 or operation_count < 1:
432
+ raise MathRouteError("RPN route lacks one computed terminal value")
433
+ terminal_value, terminal_signature = stack[0]
434
+ return MathRouteValidation(
435
+ route_signature=(
436
+ f"math-route:{MATH_ROUTE_RPN_VERSION}:{terminal_signature}"
437
+ ),
438
+ terminal_value=terminal_value,
439
+ operations=tuple(operations),
440
+ step_count=len(tokens),
441
+ source_count=source_count,
442
+ )
443
+ except Exception:
444
+ return None
445
+
446
+
447
+ def validate_math_route_response(
448
+ model_response: str,
449
+ problem: str,
450
+ ) -> MathRouteValidation | None:
451
+ """Extract the response's unique route block and execute it."""
452
+
453
+ block = extract_math_route_block(model_response)
454
+ if block is None:
455
+ return None
456
+ if block.lstrip().startswith("{"):
457
+ return validate_math_route_trace(block, problem)
458
+ return validate_math_route_rpn(block, problem)
code/oat_drgrpo/mathir.py ADDED
@@ -0,0 +1,906 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A small, fail-closed executable algebra language for canonical search.
2
+
3
+ MathIR linear v0 is intentionally narrower than ordinary mathematical text.
4
+ The model emits a semicolon-separated sequence of equation transformations,
5
+ for example ``sub(b);div(a)``. Every command is applied to both sides of the
6
+ current equation and exact rational normalization happens after every step.
7
+
8
+ The validator and canonicalizer share one execution path: a canonical strategy
9
+ key is produced only from the normalized states created by a successful
10
+ execution. There is no parser for prose, LaTeX derivations, Python, or a
11
+ model-supplied final answer.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections import Counter
17
+ from dataclasses import dataclass
18
+ from fractions import Fraction
19
+ from itertools import permutations
20
+ import re
21
+ from typing import Any, Iterable, Mapping
22
+
23
+ import sympy
24
+
25
+
26
+ MATHIR_VERIFIER = "mathir_algebra"
27
+ MATHIR_VERSION = "linear-v0"
28
+ MATHIR_MENU_VERIFIER = "mathir_action_menu"
29
+ MATHIR_MENU_VERSION = "linear-menu-v1"
30
+ MATHIR_ROUTE_VERSION = "linear-route-v1"
31
+ _MAX_REFERENCE_SYMBOLS = 6
32
+ _MAX_PROGRAM_STEPS = 4
33
+ _MAX_PROGRAM_CHARS = 160
34
+ _MAX_ARGUMENT_NODES = 11
35
+ _MAX_ARGUMENT_DEPTH = 6
36
+ _MAX_MENU_ACTIONS = 8
37
+ _MODEL_OPERATORS = frozenset({"add", "sub", "mul", "div", "neg"})
38
+ _COMMANDS = frozenset({"add", "sub", "mul", "div"})
39
+ _TOKEN_RE = re.compile(r"[A-Za-z][A-Za-z0-9_]*|[(),;]")
40
+ _MENU_ACTION_RE = re.compile(r"[A-H]")
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class Expr:
45
+ """A bounded MathIR expression.
46
+
47
+ ``const`` nodes are interpreter-internal exact rationals. The model-side
48
+ parser never accepts numeric literals.
49
+ """
50
+
51
+ op: str
52
+ args: tuple["Expr", ...] = ()
53
+ value: str | Fraction | None = None
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class Command:
58
+ op: str
59
+ argument: Expr
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class EquationState:
64
+ lhs: Expr
65
+ rhs: Expr
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class MathIRValidation:
70
+ canonical_key: str
71
+ solution: Fraction
72
+ commands: tuple[Command, ...]
73
+ states: tuple[EquationState, ...]
74
+ action_ids: tuple[str, ...] = ()
75
+ route_signature: str = ""
76
+
77
+
78
+ class MathIRError(ValueError):
79
+ """Raised for a malformed or invalid MathIR program."""
80
+
81
+
82
+ class _ExpressionParser:
83
+ def __init__(
84
+ self,
85
+ tokens: list[str],
86
+ *,
87
+ allowed_symbols: frozenset[str],
88
+ allow_constants: bool,
89
+ ) -> None:
90
+ self.tokens = tokens
91
+ self.index = 0
92
+ self.allowed_symbols = allowed_symbols
93
+ self.allow_constants = bool(allow_constants)
94
+
95
+ def _take(self, expected: str | None = None) -> str:
96
+ if self.index >= len(self.tokens):
97
+ raise MathIRError("unexpected end of expression")
98
+ token = self.tokens[self.index]
99
+ if expected is not None and token != expected:
100
+ raise MathIRError(f"expected {expected!r}")
101
+ self.index += 1
102
+ return token
103
+
104
+ def parse(self, *, depth: int = 0) -> Expr:
105
+ if depth > _MAX_ARGUMENT_DEPTH:
106
+ raise MathIRError("expression nesting is too deep")
107
+ token = self._take()
108
+ if token in {"(", ")", ",", ";"}:
109
+ raise MathIRError("expected a symbol or operator")
110
+ if self.index < len(self.tokens) and self.tokens[self.index] == "(":
111
+ if token not in _MODEL_OPERATORS:
112
+ raise MathIRError(f"unsupported operator {token!r}")
113
+ self._take("(")
114
+ first = self.parse(depth=depth + 1)
115
+ if token == "neg":
116
+ self._take(")")
117
+ return Expr("neg", (first,))
118
+ self._take(",")
119
+ second = self.parse(depth=depth + 1)
120
+ self._take(")")
121
+ return Expr(token, (first, second))
122
+ if token in self.allowed_symbols:
123
+ return Expr("symbol", value=token)
124
+ if self.allow_constants and re.fullmatch(r"-?\d+(?:/\d+)?", token):
125
+ return Expr("const", value=Fraction(token))
126
+ raise MathIRError(f"unknown symbol {token!r}")
127
+
128
+
129
+ def _tokenize(text: str) -> list[str]:
130
+ compact = re.sub(r"\s+", "", str(text))
131
+ if not compact:
132
+ raise MathIRError("empty MathIR text")
133
+ tokens = _TOKEN_RE.findall(compact)
134
+ if "".join(tokens) != compact:
135
+ raise MathIRError("unsupported MathIR character or numeric literal")
136
+ return tokens
137
+
138
+
139
+ def parse_mathir_expression(
140
+ text: str,
141
+ *,
142
+ allowed_symbols: Iterable[str],
143
+ ) -> Expr:
144
+ """Parse one model-authored expression without using Python evaluation."""
145
+
146
+ tokens = _tokenize(text)
147
+ parser = _ExpressionParser(
148
+ tokens,
149
+ allowed_symbols=frozenset(str(symbol) for symbol in allowed_symbols),
150
+ allow_constants=False,
151
+ )
152
+ expression = parser.parse()
153
+ if parser.index != len(tokens):
154
+ raise MathIRError("trailing expression tokens")
155
+ if _expr_node_count(expression) > _MAX_ARGUMENT_NODES:
156
+ raise MathIRError("expression is too large")
157
+ return expression
158
+
159
+
160
+ def _parse_trusted_expression(
161
+ text: str,
162
+ *,
163
+ allowed_symbols: Iterable[str],
164
+ ) -> Expr:
165
+ """Parse a dataset-owned formal expression.
166
+
167
+ Dataset expressions currently use no constants, but this separate entry
168
+ point makes the trust boundary explicit and permits exact rationals if a
169
+ later, versioned reference schema needs them.
170
+ """
171
+
172
+ tokens = _tokenize(text)
173
+ parser = _ExpressionParser(
174
+ tokens,
175
+ allowed_symbols=frozenset(str(symbol) for symbol in allowed_symbols),
176
+ allow_constants=True,
177
+ )
178
+ expression = parser.parse()
179
+ if parser.index != len(tokens):
180
+ raise MathIRError("trailing trusted-expression tokens")
181
+ if _expr_node_count(expression) > 31:
182
+ raise MathIRError("trusted expression is too large")
183
+ return expression
184
+
185
+
186
+ def parse_mathir_program(
187
+ text: str,
188
+ *,
189
+ allowed_symbols: Iterable[str],
190
+ max_steps: int,
191
+ ) -> tuple[Command, ...]:
192
+ """Parse a bounded sequence such as ``sub(b);div(a)``."""
193
+
194
+ compact = re.sub(r"\s+", "", str(text))
195
+ if not compact or len(compact) > _MAX_PROGRAM_CHARS:
196
+ raise MathIRError("program is empty or too long")
197
+ # A final statement terminator is surface formatting, not a new action.
198
+ compact = compact[:-1] if compact.endswith(";") else compact
199
+ if not compact or compact.startswith(";") or ";;" in compact:
200
+ raise MathIRError("empty program command")
201
+ command_texts = compact.split(";")
202
+ if not 1 <= len(command_texts) <= int(max_steps):
203
+ raise MathIRError("program has an invalid number of commands")
204
+ commands: list[Command] = []
205
+ for command_text in command_texts:
206
+ match = re.fullmatch(r"([A-Za-z][A-Za-z0-9_]*)\((.*)\)", command_text)
207
+ if match is None:
208
+ raise MathIRError("commands must use op(expression) syntax")
209
+ op, argument_text = match.groups()
210
+ if op not in _COMMANDS:
211
+ raise MathIRError(f"unsupported command {op!r}")
212
+ argument = parse_mathir_expression(
213
+ argument_text,
214
+ allowed_symbols=allowed_symbols,
215
+ )
216
+ commands.append(Command(op, argument))
217
+ return tuple(commands)
218
+
219
+
220
+ def _expr_node_count(expression: Expr) -> int:
221
+ return 1 + sum(_expr_node_count(argument) for argument in expression.args)
222
+
223
+
224
+ def _expr_symbols(expression: Expr) -> set[str]:
225
+ if expression.op == "symbol":
226
+ assert isinstance(expression.value, str)
227
+ return {expression.value}
228
+ return set().union(*(_expr_symbols(argument) for argument in expression.args), set())
229
+
230
+
231
+ def _fraction_from_reference(value: Any) -> Fraction:
232
+ if isinstance(value, bool):
233
+ raise MathIRError("boolean binding")
234
+ if isinstance(value, int):
235
+ return Fraction(value, 1)
236
+ if isinstance(value, str) and re.fullmatch(r"-?\d+(?:/[1-9]\d*)?", value.strip()):
237
+ return Fraction(value.strip())
238
+ raise MathIRError("bindings must be exact integers or rational strings")
239
+
240
+
241
+ def _expr_to_sympy(expression: Expr) -> sympy.Expr:
242
+ if expression.op == "symbol":
243
+ assert isinstance(expression.value, str)
244
+ return sympy.Symbol(expression.value)
245
+ if expression.op == "const":
246
+ assert isinstance(expression.value, Fraction)
247
+ return sympy.Rational(expression.value.numerator, expression.value.denominator)
248
+ converted = tuple(_expr_to_sympy(argument) for argument in expression.args)
249
+ if expression.op == "add":
250
+ return converted[0] + converted[1]
251
+ if expression.op == "sub":
252
+ return converted[0] - converted[1]
253
+ if expression.op == "mul":
254
+ return converted[0] * converted[1]
255
+ if expression.op == "div":
256
+ return converted[0] / converted[1]
257
+ if expression.op == "neg":
258
+ return -converted[0]
259
+ if expression.op == "inv":
260
+ return sympy.Integer(1) / converted[0]
261
+ raise MathIRError(f"unsupported internal expression {expression.op!r}")
262
+
263
+
264
+ def _fold(op: str, arguments: tuple[Expr, ...]) -> Expr:
265
+ if not arguments:
266
+ return Expr("const", value=Fraction(0 if op == "add" else 1, 1))
267
+ result = arguments[0]
268
+ for argument in arguments[1:]:
269
+ result = Expr(op, (result, argument))
270
+ return result
271
+
272
+
273
+ def _expr_from_sympy(expression: sympy.Expr) -> Expr:
274
+ if expression.is_Symbol:
275
+ return Expr("symbol", value=str(expression))
276
+ if expression.is_Rational:
277
+ return Expr(
278
+ "const",
279
+ value=Fraction(int(expression.p), int(expression.q)),
280
+ )
281
+ if expression.is_Add:
282
+ return _fold(
283
+ "add",
284
+ tuple(_expr_from_sympy(argument) for argument in expression.args),
285
+ )
286
+ if expression.is_Mul:
287
+ return _fold(
288
+ "mul",
289
+ tuple(_expr_from_sympy(argument) for argument in expression.args),
290
+ )
291
+ if expression.is_Pow and expression.exp == -1:
292
+ return Expr("inv", (_expr_from_sympy(expression.base),))
293
+ raise MathIRError(f"normalizer produced unsupported expression {expression!r}")
294
+
295
+
296
+ def _normalize_expr(expression: Expr) -> Expr:
297
+ symbolic = _expr_to_sympy(expression)
298
+ normalized = sympy.cancel(symbolic)
299
+ return _expr_from_sympy(normalized)
300
+
301
+
302
+ def _canonical_parts(expression: Expr) -> tuple[str, ...]:
303
+ if expression.op not in {"add", "mul"}:
304
+ return (_canonical_expr(expression),)
305
+ parts: list[str] = []
306
+ for argument in expression.args:
307
+ converted = _canonicalized_expr(argument)
308
+ if converted.op == expression.op:
309
+ parts.extend(_canonical_parts(converted))
310
+ else:
311
+ parts.append(_canonical_expr(converted))
312
+ return tuple(sorted(parts))
313
+
314
+
315
+ def _canonicalized_expr(expression: Expr) -> Expr:
316
+ if expression.op == "sub":
317
+ return Expr(
318
+ "add",
319
+ (
320
+ _canonicalized_expr(expression.args[0]),
321
+ Expr("neg", (_canonicalized_expr(expression.args[1]),)),
322
+ ),
323
+ )
324
+ if expression.op == "div":
325
+ return Expr(
326
+ "mul",
327
+ (
328
+ _canonicalized_expr(expression.args[0]),
329
+ Expr("inv", (_canonicalized_expr(expression.args[1]),)),
330
+ ),
331
+ )
332
+ return Expr(
333
+ expression.op,
334
+ tuple(_canonicalized_expr(argument) for argument in expression.args),
335
+ expression.value,
336
+ )
337
+
338
+
339
+ def _canonical_expr(expression: Expr) -> str:
340
+ expression = _canonicalized_expr(expression)
341
+ if expression.op == "symbol":
342
+ assert isinstance(expression.value, str)
343
+ return expression.value
344
+ if expression.op == "const":
345
+ assert isinstance(expression.value, Fraction)
346
+ if expression.value.denominator == 1:
347
+ return str(expression.value.numerator)
348
+ return f"rat({expression.value.numerator},{expression.value.denominator})"
349
+ if expression.op in {"add", "mul"}:
350
+ return f"{expression.op}({','.join(_canonical_parts(expression))})"
351
+ if expression.op in {"neg", "inv"}:
352
+ return f"{expression.op}({_canonical_expr(expression.args[0])})"
353
+ raise MathIRError(f"cannot canonicalize {expression.op!r}")
354
+
355
+
356
+ def _canonical_state(state: EquationState) -> str:
357
+ return f"eq({_canonical_expr(state.lhs)},{_canonical_expr(state.rhs)})"
358
+
359
+
360
+ def _rename_expr_symbols(
361
+ expression: Expr,
362
+ symbol_map: Mapping[str, str],
363
+ ) -> Expr:
364
+ if expression.op == "symbol":
365
+ assert isinstance(expression.value, str)
366
+ return Expr(
367
+ "symbol",
368
+ value=symbol_map.get(expression.value, expression.value),
369
+ )
370
+ return Expr(
371
+ expression.op,
372
+ tuple(
373
+ _rename_expr_symbols(argument, symbol_map)
374
+ for argument in expression.args
375
+ ),
376
+ expression.value,
377
+ )
378
+
379
+
380
+ def _alpha_canonical_route(
381
+ initial_state: EquationState,
382
+ commands: tuple[Command, ...],
383
+ ) -> str:
384
+ """Canonicalize a verified route independently of coefficient names.
385
+
386
+ At most six coefficient symbols are allowed by the reference schema, so a
387
+ small exhaustive alpha-renaming is simpler and safer than relying on
388
+ symbol-name or traversal-order heuristics. Numeric binding values never
389
+ enter this representation.
390
+ """
391
+
392
+ symbols = sorted(
393
+ (
394
+ _expr_symbols(initial_state.lhs)
395
+ | _expr_symbols(initial_state.rhs)
396
+ | set().union(
397
+ *(_expr_symbols(command.argument) for command in commands),
398
+ set(),
399
+ )
400
+ )
401
+ - {"x"}
402
+ )
403
+ roles = tuple(f"c{index}" for index in range(len(symbols)))
404
+ candidates: list[str] = []
405
+ for assigned_symbols in permutations(symbols):
406
+ symbol_map = {
407
+ symbol: role for symbol, role in zip(assigned_symbols, roles)
408
+ }
409
+ renamed_initial = EquationState(
410
+ _rename_expr_symbols(initial_state.lhs, symbol_map),
411
+ _rename_expr_symbols(initial_state.rhs, symbol_map),
412
+ )
413
+ command_parts = []
414
+ for command in commands:
415
+ renamed_argument = _rename_expr_symbols(
416
+ command.argument,
417
+ symbol_map,
418
+ )
419
+ command_parts.append(
420
+ f"{command.op}({_canonical_expr(renamed_argument)})"
421
+ )
422
+ candidates.append(
423
+ f"init={_canonical_state(renamed_initial)}"
424
+ f"|commands={'>'.join(command_parts)}"
425
+ )
426
+ if not candidates:
427
+ candidates.append(
428
+ f"init={_canonical_state(initial_state)}"
429
+ f"|commands={'>'.join(command.op for command in commands)}"
430
+ )
431
+ return f"mathir-route:{MATHIR_ROUTE_VERSION}:{min(candidates)}"
432
+
433
+
434
+ def _validate_denominators(
435
+ expression: Expr,
436
+ *,
437
+ bindings: Mapping[str, Fraction],
438
+ ) -> None:
439
+ if expression.op == "div":
440
+ denominator = expression.args[1]
441
+ if "x" in _expr_symbols(denominator):
442
+ raise MathIRError("x-dependent denominators are not supported")
443
+ if _eval_fraction(denominator, bindings) == 0:
444
+ raise MathIRError("division by zero in command expression")
445
+ for argument in expression.args:
446
+ _validate_denominators(argument, bindings=bindings)
447
+
448
+
449
+ def _eval_fraction(
450
+ expression: Expr,
451
+ bindings: Mapping[str, Fraction],
452
+ ) -> Fraction:
453
+ if expression.op == "symbol":
454
+ assert isinstance(expression.value, str)
455
+ if expression.value not in bindings:
456
+ raise MathIRError("cannot evaluate an expression containing x")
457
+ return bindings[expression.value]
458
+ if expression.op == "const":
459
+ assert isinstance(expression.value, Fraction)
460
+ return expression.value
461
+ values = tuple(_eval_fraction(argument, bindings) for argument in expression.args)
462
+ if expression.op == "add":
463
+ return values[0] + values[1]
464
+ if expression.op == "sub":
465
+ return values[0] - values[1]
466
+ if expression.op == "mul":
467
+ return values[0] * values[1]
468
+ if expression.op == "div":
469
+ if values[1] == 0:
470
+ raise MathIRError("division by zero")
471
+ return values[0] / values[1]
472
+ if expression.op == "neg":
473
+ return -values[0]
474
+ if expression.op == "inv":
475
+ if values[0] == 0:
476
+ raise MathIRError("division by zero")
477
+ return Fraction(1, 1) / values[0]
478
+ raise MathIRError(f"cannot evaluate {expression.op!r}")
479
+
480
+
481
+ def _initial_solution(
482
+ state: EquationState,
483
+ *,
484
+ bindings: Mapping[str, Fraction],
485
+ ) -> Fraction:
486
+ x = sympy.Symbol("x")
487
+ substitutions = {
488
+ sympy.Symbol(name): sympy.Rational(value.numerator, value.denominator)
489
+ for name, value in bindings.items()
490
+ }
491
+ equation = sympy.cancel(
492
+ (_expr_to_sympy(state.lhs) - _expr_to_sympy(state.rhs)).subs(substitutions)
493
+ )
494
+ numerator, denominator = sympy.together(equation).as_numer_denom()
495
+ if x in denominator.free_symbols:
496
+ raise MathIRError("initial equation has an x-dependent denominator")
497
+ polynomial = sympy.Poly(sympy.expand(numerator), x)
498
+ if polynomial.degree() != 1:
499
+ raise MathIRError("initial equation is not uniquely linear")
500
+ coefficient = polynomial.coeff_monomial(x)
501
+ constant = polynomial.coeff_monomial(1)
502
+ if coefficient == 0:
503
+ raise MathIRError("initial equation has no unique solution")
504
+ solution = sympy.cancel(-constant / coefficient)
505
+ if not solution.is_Rational:
506
+ raise MathIRError("initial solution is not rational")
507
+ return Fraction(int(solution.p), int(solution.q))
508
+
509
+
510
+ def _apply_command(
511
+ state: EquationState,
512
+ command: Command,
513
+ *,
514
+ bindings: Mapping[str, Fraction],
515
+ ) -> EquationState:
516
+ _validate_denominators(command.argument, bindings=bindings)
517
+ argument_symbols = _expr_symbols(command.argument)
518
+ if command.op in {"mul", "div"}:
519
+ if "x" in argument_symbols:
520
+ raise MathIRError("multiplication and division by x are not reversible")
521
+ if _eval_fraction(command.argument, bindings) == 0:
522
+ raise MathIRError("multiplication and division require a nonzero argument")
523
+ if command.op == "add":
524
+ lhs = Expr("add", (state.lhs, command.argument))
525
+ rhs = Expr("add", (state.rhs, command.argument))
526
+ elif command.op == "sub":
527
+ lhs = Expr("sub", (state.lhs, command.argument))
528
+ rhs = Expr("sub", (state.rhs, command.argument))
529
+ elif command.op == "mul":
530
+ lhs = Expr("mul", (state.lhs, command.argument))
531
+ rhs = Expr("mul", (state.rhs, command.argument))
532
+ elif command.op == "div":
533
+ lhs = Expr("div", (state.lhs, command.argument))
534
+ rhs = Expr("div", (state.rhs, command.argument))
535
+ else:
536
+ raise MathIRError(f"unsupported command {command.op!r}")
537
+ # This exact normalizer is part of the interpreter semantics, rather than
538
+ # model-authored text which could claim a simplification without doing it.
539
+ return EquationState(_normalize_expr(lhs), _normalize_expr(rhs))
540
+
541
+
542
+ def _validated_reference(
543
+ spec: Mapping[str, Any],
544
+ ) -> tuple[EquationState, dict[str, Fraction], int]:
545
+ if spec.get("verifier") != MATHIR_VERIFIER:
546
+ raise MathIRError("wrong verifier")
547
+ if spec.get("mathir_version") != MATHIR_VERSION:
548
+ raise MathIRError("unsupported MathIR version")
549
+ raw_bindings = spec.get("bindings")
550
+ if not isinstance(raw_bindings, dict):
551
+ raise MathIRError("missing bindings")
552
+ if not 1 <= len(raw_bindings) <= _MAX_REFERENCE_SYMBOLS:
553
+ raise MathIRError("invalid number of bindings")
554
+ bindings: dict[str, Fraction] = {}
555
+ for raw_name, raw_value in raw_bindings.items():
556
+ name = str(raw_name)
557
+ if not re.fullmatch(r"[a-wyz]", name) or name == "x":
558
+ raise MathIRError("binding names must be single lowercase coefficient symbols")
559
+ bindings[name] = _fraction_from_reference(raw_value)
560
+ if len(bindings) != len(raw_bindings):
561
+ raise MathIRError("duplicate binding names")
562
+ max_steps = int(spec.get("max_steps", _MAX_PROGRAM_STEPS))
563
+ if not 1 <= max_steps <= _MAX_PROGRAM_STEPS:
564
+ raise MathIRError("invalid max_steps")
565
+ allowed_symbols = frozenset(bindings) | {"x"}
566
+ lhs = _parse_trusted_expression(
567
+ str(spec["initial_lhs"]),
568
+ allowed_symbols=allowed_symbols,
569
+ )
570
+ rhs = _parse_trusted_expression(
571
+ str(spec["initial_rhs"]),
572
+ allowed_symbols=allowed_symbols,
573
+ )
574
+ referenced_coefficients = (_expr_symbols(lhs) | _expr_symbols(rhs)) - {"x"}
575
+ if referenced_coefficients != set(bindings):
576
+ raise MathIRError("bindings and initial equation symbols disagree")
577
+ state = EquationState(_normalize_expr(lhs), _normalize_expr(rhs))
578
+ _initial_solution(state, bindings=bindings)
579
+ return state, bindings, max_steps
580
+
581
+
582
+ def _execute_mathir_commands(
583
+ *,
584
+ initial_state: EquationState,
585
+ bindings: Mapping[str, Fraction],
586
+ commands: tuple[Command, ...],
587
+ key_version: str,
588
+ action_ids: tuple[str, ...] = (),
589
+ ) -> MathIRValidation:
590
+ target_solution = _initial_solution(initial_state, bindings=bindings)
591
+ seen = {_canonical_state(initial_state)}
592
+ states: list[EquationState] = []
593
+ state = initial_state
594
+ for command in commands:
595
+ state = _apply_command(state, command, bindings=bindings)
596
+ state_key = _canonical_state(state)
597
+ if state_key in seen:
598
+ raise MathIRError("program revisits a previous equation state")
599
+ seen.add(state_key)
600
+ states.append(state)
601
+
602
+ if state.lhs == Expr("symbol", value="x"):
603
+ final_expression = state.rhs
604
+ elif state.rhs == Expr("symbol", value="x"):
605
+ final_expression = state.lhs
606
+ else:
607
+ raise MathIRError("program does not finish with x isolated")
608
+ if "x" in _expr_symbols(final_expression):
609
+ raise MathIRError("final expression still contains x")
610
+ solution = _eval_fraction(final_expression, bindings)
611
+ if solution != target_solution:
612
+ raise MathIRError("executed program has the wrong solution")
613
+ canonical_key = (
614
+ f"mathir:{key_version}:"
615
+ + ">".join(_canonical_state(executed_state) for executed_state in states)
616
+ )
617
+ route_signature = _alpha_canonical_route(initial_state, commands)
618
+ return MathIRValidation(
619
+ canonical_key=canonical_key,
620
+ solution=solution,
621
+ commands=commands,
622
+ states=tuple(states),
623
+ action_ids=action_ids,
624
+ route_signature=route_signature,
625
+ )
626
+
627
+
628
+ def validate_mathir_algebra(
629
+ program_text: str,
630
+ spec: Mapping[str, Any],
631
+ ) -> MathIRValidation | None:
632
+ """Execute and validate a MathIR program, returning its canonical path.
633
+
634
+ All failures return ``None``. This function is the single admission
635
+ boundary used by both task reward and the online canonical bank.
636
+ """
637
+
638
+ try:
639
+ initial_state, bindings, max_steps = _validated_reference(spec)
640
+ allowed_symbols = frozenset(bindings) | {"x"}
641
+ commands = parse_mathir_program(
642
+ program_text,
643
+ allowed_symbols=allowed_symbols,
644
+ max_steps=max_steps,
645
+ )
646
+ return _execute_mathir_commands(
647
+ initial_state=initial_state,
648
+ bindings=bindings,
649
+ commands=commands,
650
+ key_version=MATHIR_VERSION,
651
+ )
652
+ except Exception:
653
+ return None
654
+
655
+
656
+ def _validated_menu_reference(
657
+ spec: Mapping[str, Any],
658
+ ) -> tuple[
659
+ EquationState,
660
+ dict[str, Fraction],
661
+ int,
662
+ dict[str, Command],
663
+ ]:
664
+ if spec.get("verifier") != MATHIR_MENU_VERIFIER:
665
+ raise MathIRError("wrong menu verifier")
666
+ if spec.get("mathir_version") != MATHIR_MENU_VERSION:
667
+ raise MathIRError("unsupported menu MathIR version")
668
+ base_spec = dict(spec)
669
+ base_spec["verifier"] = MATHIR_VERIFIER
670
+ base_spec["mathir_version"] = MATHIR_VERSION
671
+ initial_state, bindings, max_steps = _validated_reference(base_spec)
672
+ raw_actions = spec.get("actions")
673
+ if not isinstance(raw_actions, dict):
674
+ raise MathIRError("missing action menu")
675
+ if not 2 <= len(raw_actions) <= _MAX_MENU_ACTIONS:
676
+ raise MathIRError("invalid action menu size")
677
+ expected_ids = [chr(ord("A") + index) for index in range(len(raw_actions))]
678
+ if list(raw_actions) != expected_ids:
679
+ raise MathIRError("action IDs must be contiguous and ordered")
680
+ allowed_symbols = frozenset(bindings) | {"x"}
681
+ actions: dict[str, Command] = {}
682
+ normalized_programs: set[str] = set()
683
+ for action_id, raw_program in raw_actions.items():
684
+ if _MENU_ACTION_RE.fullmatch(str(action_id)) is None:
685
+ raise MathIRError("invalid action ID")
686
+ program = re.sub(r"\s+", "", str(raw_program))
687
+ if program in normalized_programs:
688
+ raise MathIRError("duplicate action semantics")
689
+ parsed = parse_mathir_program(
690
+ program,
691
+ allowed_symbols=allowed_symbols,
692
+ max_steps=1,
693
+ )
694
+ if len(parsed) != 1:
695
+ raise MathIRError("each action must contain exactly one command")
696
+ normalized_programs.add(program)
697
+ actions[str(action_id)] = parsed[0]
698
+ return initial_state, bindings, max_steps, actions
699
+
700
+
701
+ def parse_mathir_action_program(
702
+ text: str,
703
+ *,
704
+ action_ids: Iterable[str],
705
+ max_steps: int,
706
+ ) -> tuple[str, ...]:
707
+ """Parse a bounded sequence of prompt-local action IDs."""
708
+
709
+ compact = re.sub(r"\s+", "", str(text))
710
+ if not compact or len(compact) > _MAX_PROGRAM_CHARS:
711
+ raise MathIRError("action program is empty or too long")
712
+ compact = compact[:-1] if compact.endswith(";") else compact
713
+ if not compact or compact.startswith(";") or ";;" in compact:
714
+ raise MathIRError("empty action")
715
+ selected = tuple(compact.split(";"))
716
+ if not 1 <= len(selected) <= int(max_steps):
717
+ raise MathIRError("action program has an invalid number of steps")
718
+ allowed = frozenset(str(action_id) for action_id in action_ids)
719
+ if any(
720
+ _MENU_ACTION_RE.fullmatch(action_id) is None or action_id not in allowed
721
+ for action_id in selected
722
+ ):
723
+ raise MathIRError("unknown action ID")
724
+ return selected
725
+
726
+
727
+ def validate_mathir_action_menu(
728
+ program_text: str,
729
+ spec: Mapping[str, Any],
730
+ ) -> MathIRValidation | None:
731
+ """Execute the exact prompt-local action sequence and key its state path."""
732
+
733
+ try:
734
+ initial_state, bindings, max_steps, actions = _validated_menu_reference(spec)
735
+ action_ids = parse_mathir_action_program(
736
+ program_text,
737
+ action_ids=actions,
738
+ max_steps=max_steps,
739
+ )
740
+ commands = tuple(actions[action_id] for action_id in action_ids)
741
+ return _execute_mathir_commands(
742
+ initial_state=initial_state,
743
+ bindings=bindings,
744
+ commands=commands,
745
+ key_version=MATHIR_MENU_VERSION,
746
+ action_ids=action_ids,
747
+ )
748
+ except Exception:
749
+ return None
750
+
751
+
752
+ def enumerate_mathir_action_menu_keys(
753
+ spec: Mapping[str, Any],
754
+ ) -> set[str]:
755
+ """Exhaustively enumerate the bounded menu's distinct verified state paths."""
756
+
757
+ return {
758
+ validation.canonical_key
759
+ for validation in enumerate_mathir_action_menu_validations(spec)
760
+ }
761
+
762
+
763
+ def _terminal_solution(
764
+ state: EquationState,
765
+ *,
766
+ bindings: Mapping[str, Fraction],
767
+ target_solution: Fraction,
768
+ ) -> Fraction | None:
769
+ if state.lhs == Expr("symbol", value="x"):
770
+ final_expression = state.rhs
771
+ elif state.rhs == Expr("symbol", value="x"):
772
+ final_expression = state.lhs
773
+ else:
774
+ return None
775
+ if "x" in _expr_symbols(final_expression):
776
+ return None
777
+ solution = _eval_fraction(final_expression, bindings)
778
+ return solution if solution == target_solution else None
779
+
780
+
781
+ def enumerate_mathir_action_menu_validations(
782
+ spec: Mapping[str, Any],
783
+ ) -> tuple[MathIRValidation, ...]:
784
+ """Enumerate exact support while caching deterministic state transitions."""
785
+
786
+ initial_state, bindings, max_steps, actions = _validated_menu_reference(spec)
787
+ target_solution = _initial_solution(initial_state, bindings=bindings)
788
+ transition_cache: dict[
789
+ tuple[str, str], tuple[EquationState, str] | None
790
+ ] = {}
791
+ admitted: dict[str, MathIRValidation] = {}
792
+
793
+ def transition(
794
+ state: EquationState,
795
+ action_id: str,
796
+ ) -> tuple[EquationState, str] | None:
797
+ state_key = _canonical_state(state)
798
+ cache_key = (state_key, action_id)
799
+ if cache_key not in transition_cache:
800
+ try:
801
+ next_state = _apply_command(
802
+ state,
803
+ actions[action_id],
804
+ bindings=bindings,
805
+ )
806
+ transition_cache[cache_key] = (
807
+ next_state,
808
+ _canonical_state(next_state),
809
+ )
810
+ except Exception:
811
+ transition_cache[cache_key] = None
812
+ return transition_cache[cache_key]
813
+
814
+ def visit(
815
+ state: EquationState,
816
+ *,
817
+ seen: frozenset[str],
818
+ commands: tuple[Command, ...],
819
+ action_ids: tuple[str, ...],
820
+ states: tuple[EquationState, ...],
821
+ ) -> None:
822
+ if len(commands) >= max_steps:
823
+ return
824
+ for action_id in actions:
825
+ result = transition(state, action_id)
826
+ if result is None:
827
+ continue
828
+ next_state, next_state_key = result
829
+ if next_state_key in seen:
830
+ continue
831
+ next_commands = commands + (actions[action_id],)
832
+ next_action_ids = action_ids + (action_id,)
833
+ next_states = states + (next_state,)
834
+ solution = _terminal_solution(
835
+ next_state,
836
+ bindings=bindings,
837
+ target_solution=target_solution,
838
+ )
839
+ if solution is not None:
840
+ canonical_key = (
841
+ f"mathir:{MATHIR_MENU_VERSION}:"
842
+ + ">".join(
843
+ _canonical_state(executed_state)
844
+ for executed_state in next_states
845
+ )
846
+ )
847
+ admitted[canonical_key] = MathIRValidation(
848
+ canonical_key=canonical_key,
849
+ solution=solution,
850
+ commands=next_commands,
851
+ states=next_states,
852
+ action_ids=next_action_ids,
853
+ route_signature=_alpha_canonical_route(
854
+ initial_state,
855
+ next_commands,
856
+ ),
857
+ )
858
+ visit(
859
+ next_state,
860
+ seen=seen | {next_state_key},
861
+ commands=next_commands,
862
+ action_ids=next_action_ids,
863
+ states=next_states,
864
+ )
865
+
866
+ initial_key = _canonical_state(initial_state)
867
+ visit(
868
+ initial_state,
869
+ seen=frozenset({initial_key}),
870
+ commands=(),
871
+ action_ids=(),
872
+ states=(),
873
+ )
874
+ return tuple(admitted[key] for key in sorted(admitted))
875
+
876
+
877
+ def enumerate_mathir_action_menu_route_signatures(
878
+ spec: Mapping[str, Any],
879
+ ) -> set[str]:
880
+ """Exhaustively enumerate the menu's verified cross-prompt route support."""
881
+
882
+ return {
883
+ validation.route_signature
884
+ for validation in enumerate_mathir_action_menu_validations(spec)
885
+ }
886
+
887
+
888
+ def certified_mathir_strategy_keys(
889
+ spec: Mapping[str, Any],
890
+ programs: Iterable[str],
891
+ ) -> set[str]:
892
+ """Validate a finite audit list without treating it as exhaustive support."""
893
+
894
+ keys: set[str] = set()
895
+ for program in programs:
896
+ validation = validate_mathir_algebra(program, spec)
897
+ if validation is None:
898
+ raise MathIRError(f"certified program failed validation: {program}")
899
+ keys.add(validation.canonical_key)
900
+ return keys
901
+
902
+
903
+ def mathir_command_histogram(validation: MathIRValidation) -> Counter[str]:
904
+ """Small diagnostic helper used by audits and tests."""
905
+
906
+ return Counter(command.op for command in validation.commands)
code/oat_drgrpo/maze_modebench.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verified language action programs for PointMaze and AntMaze.
2
+
3
+ This module is deliberately simulator-independent. It validates the trusted
4
+ episode specification, parses the LM's finite action alphabet, and derives a
5
+ topological route key from a hash-bound successful execution record. MuJoCo
6
+ remains outside the trainer process; its worker must return the trajectory and
7
+ environment hashes consumed here.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass
13
+ import hashlib
14
+ import json
15
+ import math
16
+ import re
17
+ from typing import Any, Mapping, Sequence
18
+
19
+
20
+ POINT_MAZE_VERIFIER = "point_maze_action_program"
21
+ ANT_MAZE_VERIFIER = "ant_maze_action_program"
22
+ MAZE_ACTION_VERSION = "maze-action-v1"
23
+ ANT_MAZE_ACTION_VERSION = "maze-action-ant-v5"
24
+
25
+ POINT_ACTIONS = ("N", "NE", "E", "SE", "S", "SW", "W", "NW", "COAST")
26
+ ANT_ACTIONS = ("N", "NE", "E", "SE", "S", "SW", "W", "NW")
27
+
28
+ _SHA256 = re.compile(r"[0-9a-f]{64}")
29
+ _IDENTIFIER = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,95}")
30
+ _GATE_ID = re.compile(r"[a-z][a-z0-9_-]{0,31}")
31
+ _MAX_PROGRAM_CHARS = 4096
32
+
33
+
34
+ class MazeModeBenchError(ValueError):
35
+ """Raised when a trusted maze spec or execution record is invalid."""
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class DirectedGate:
40
+ gate_id: str
41
+ axis: str
42
+ coordinate: float
43
+ span_min: float
44
+ span_max: float
45
+ hysteresis: float
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class MazeActionSpec:
50
+ verifier: str
51
+ environment_id: str
52
+ environment_sha256: str
53
+ controller_sha256: str | None
54
+ map_id: str
55
+ maze_map: tuple[tuple[int, ...], ...]
56
+ reset_cell: tuple[int, int]
57
+ goal_cell: tuple[int, int]
58
+ reset_seed: int
59
+ min_actions: int
60
+ max_actions: int
61
+ action_repeat: int
62
+ action_tokens: tuple[str, ...]
63
+ success_threshold: float
64
+ max_segment_length: float
65
+ bounds: tuple[tuple[float, float], tuple[float, float]]
66
+ gates: tuple[DirectedGate, ...]
67
+ spec_sha256: str
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class MazeExecutionRecord:
72
+ environment_sha256: str
73
+ controller_sha256: str | None
74
+ spec_sha256: str
75
+ reset_seed: int
76
+ action_tokens: tuple[str, ...]
77
+ success: bool
78
+ final_goal_distance: float
79
+ trajectory_xy: tuple[tuple[float, float], ...]
80
+ simulator_steps: int
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class MazeValidation:
85
+ canonical_key: str
86
+ directed_gates: tuple[str, ...]
87
+ action_tokens: tuple[str, ...]
88
+ simulator_steps: int
89
+
90
+
91
+ def _finite_float(value: Any, *, label: str) -> float:
92
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
93
+ raise MazeModeBenchError(f"{label} must be a finite number")
94
+ result = float(value)
95
+ if not math.isfinite(result):
96
+ raise MazeModeBenchError(f"{label} must be a finite number")
97
+ return result
98
+
99
+
100
+ def _bounded_int(value: Any, *, label: str, minimum: int, maximum: int) -> int:
101
+ if isinstance(value, bool) or not isinstance(value, int):
102
+ raise MazeModeBenchError(f"{label} must be an integer")
103
+ result = int(value)
104
+ if not minimum <= result <= maximum:
105
+ raise MazeModeBenchError(f"{label} is outside [{minimum}, {maximum}]")
106
+ return result
107
+
108
+
109
+ def _sha(value: Any, *, label: str) -> str:
110
+ result = str(value)
111
+ if _SHA256.fullmatch(result) is None:
112
+ raise MazeModeBenchError(f"{label} must be a lowercase SHA-256")
113
+ return result
114
+
115
+
116
+ def _canonical_spec_sha256(spec: Mapping[str, Any]) -> str:
117
+ payload = dict(spec)
118
+ claimed = payload.pop("spec_sha256", None)
119
+ canonical = json.dumps(
120
+ payload,
121
+ allow_nan=False,
122
+ ensure_ascii=True,
123
+ separators=(",", ":"),
124
+ sort_keys=True,
125
+ ).encode("ascii")
126
+ observed = hashlib.sha256(canonical).hexdigest()
127
+ if claimed is not None and claimed != observed:
128
+ raise MazeModeBenchError("spec_sha256 does not match the canonical spec")
129
+ return observed
130
+
131
+
132
+ def _parse_bounds(value: Any) -> tuple[tuple[float, float], tuple[float, float]]:
133
+ if not isinstance(value, list) or len(value) != 2:
134
+ raise MazeModeBenchError("bounds_xy must contain x and y bounds")
135
+ parsed: list[tuple[float, float]] = []
136
+ for index, raw in enumerate(value):
137
+ if not isinstance(raw, list) or len(raw) != 2:
138
+ raise MazeModeBenchError(f"bounds_xy[{index}] must contain two values")
139
+ low = _finite_float(raw[0], label=f"bounds_xy[{index}][0]")
140
+ high = _finite_float(raw[1], label=f"bounds_xy[{index}][1]")
141
+ if low >= high:
142
+ raise MazeModeBenchError("each coordinate bound must be increasing")
143
+ parsed.append((low, high))
144
+ return parsed[0], parsed[1]
145
+
146
+
147
+ def _parse_gates(value: Any) -> tuple[DirectedGate, ...]:
148
+ if not isinstance(value, list) or not 1 <= len(value) <= 32:
149
+ raise MazeModeBenchError("route_gates must contain between 1 and 32 gates")
150
+ gates: list[DirectedGate] = []
151
+ observed: set[str] = set()
152
+ for index, raw in enumerate(value):
153
+ if not isinstance(raw, Mapping):
154
+ raise MazeModeBenchError(f"route gate {index} must be an object")
155
+ gate_id = str(raw.get("id", ""))
156
+ if _GATE_ID.fullmatch(gate_id) is None:
157
+ raise MazeModeBenchError(f"route gate {index} has an invalid id")
158
+ if gate_id in observed:
159
+ raise MazeModeBenchError(f"duplicate route gate id {gate_id!r}")
160
+ observed.add(gate_id)
161
+ axis = str(raw.get("axis", ""))
162
+ if axis not in {"x", "y"}:
163
+ raise MazeModeBenchError(f"route gate {gate_id!r} has invalid axis")
164
+ coordinate = _finite_float(raw.get("coordinate"), label=f"{gate_id}.coordinate")
165
+ raw_span = raw.get("span")
166
+ if not isinstance(raw_span, list) or len(raw_span) != 2:
167
+ raise MazeModeBenchError(f"route gate {gate_id!r} needs a span")
168
+ span_min = _finite_float(raw_span[0], label=f"{gate_id}.span[0]")
169
+ span_max = _finite_float(raw_span[1], label=f"{gate_id}.span[1]")
170
+ if span_min >= span_max:
171
+ raise MazeModeBenchError(f"route gate {gate_id!r} span is not increasing")
172
+ hysteresis = _finite_float(raw.get("hysteresis"), label=f"{gate_id}.hysteresis")
173
+ if not 0.0 < hysteresis <= 0.25:
174
+ raise MazeModeBenchError(f"route gate {gate_id!r} hysteresis is invalid")
175
+ gates.append(
176
+ DirectedGate(
177
+ gate_id=gate_id,
178
+ axis=axis,
179
+ coordinate=coordinate,
180
+ span_min=span_min,
181
+ span_max=span_max,
182
+ hysteresis=hysteresis,
183
+ )
184
+ )
185
+ return tuple(gates)
186
+
187
+
188
+ def _parse_maze_map(
189
+ value: Any,
190
+ reset_cell_value: Any,
191
+ goal_cell_value: Any,
192
+ ) -> tuple[tuple[tuple[int, ...], ...], tuple[int, int], tuple[int, int]]:
193
+ if not isinstance(value, list) or not 5 <= len(value) <= 16:
194
+ raise MazeModeBenchError("maze_map must contain between 5 and 16 rows")
195
+ width = len(value[0]) if isinstance(value[0], list) else 0
196
+ if not 5 <= width <= 16:
197
+ raise MazeModeBenchError("maze_map must contain between 5 and 16 columns")
198
+ rows: list[tuple[int, ...]] = []
199
+ for index, raw_row in enumerate(value):
200
+ if (
201
+ not isinstance(raw_row, list)
202
+ or len(raw_row) != width
203
+ or any(isinstance(cell, bool) or cell not in {0, 1} for cell in raw_row)
204
+ ):
205
+ raise MazeModeBenchError(f"maze_map row {index} is malformed")
206
+ rows.append(tuple(int(cell) for cell in raw_row))
207
+ if any(cell != 1 for cell in rows[0] + rows[-1]):
208
+ raise MazeModeBenchError("maze_map top and bottom borders must be walls")
209
+ if any(row[0] != 1 or row[-1] != 1 for row in rows):
210
+ raise MazeModeBenchError("maze_map left and right borders must be walls")
211
+
212
+ def parse_cell(raw: Any, label: str) -> tuple[int, int]:
213
+ if (
214
+ not isinstance(raw, list)
215
+ or len(raw) != 2
216
+ or any(isinstance(item, bool) or not isinstance(item, int) for item in raw)
217
+ ):
218
+ raise MazeModeBenchError(f"{label} must be a [row, column] integer pair")
219
+ cell = int(raw[0]), int(raw[1])
220
+ if not (0 <= cell[0] < len(rows) and 0 <= cell[1] < width):
221
+ raise MazeModeBenchError(f"{label} is outside maze_map")
222
+ if rows[cell[0]][cell[1]] != 0:
223
+ raise MazeModeBenchError(f"{label} must select a free maze cell")
224
+ return cell
225
+
226
+ reset_cell = parse_cell(reset_cell_value, "reset_cell")
227
+ goal_cell = parse_cell(goal_cell_value, "goal_cell")
228
+ if reset_cell == goal_cell:
229
+ raise MazeModeBenchError("reset_cell and goal_cell must differ")
230
+ return tuple(rows), reset_cell, goal_cell
231
+
232
+
233
+ def parse_maze_action_spec(spec: Mapping[str, Any]) -> MazeActionSpec:
234
+ """Parse one trusted PointMaze or AntMaze action-program specification."""
235
+
236
+ if not isinstance(spec, Mapping):
237
+ raise MazeModeBenchError("maze spec must be an object")
238
+ verifier = str(spec.get("verifier", ""))
239
+ if verifier not in {POINT_MAZE_VERIFIER, ANT_MAZE_VERIFIER}:
240
+ raise MazeModeBenchError("wrong maze action-program verifier")
241
+ expected_version = (
242
+ MAZE_ACTION_VERSION
243
+ if verifier == POINT_MAZE_VERIFIER
244
+ else ANT_MAZE_ACTION_VERSION
245
+ )
246
+ if spec.get("maze_action_version") != expected_version:
247
+ raise MazeModeBenchError("unsupported maze action-program version")
248
+ environment_id = str(spec.get("environment_id", ""))
249
+ if _IDENTIFIER.fullmatch(environment_id) is None:
250
+ raise MazeModeBenchError("environment_id is invalid")
251
+ expected_prefix = "PointMaze" if verifier == POINT_MAZE_VERIFIER else "AntMaze"
252
+ if not environment_id.startswith(expected_prefix):
253
+ raise MazeModeBenchError("environment_id does not match the verifier")
254
+ map_id = str(spec.get("map_id", ""))
255
+ if _IDENTIFIER.fullmatch(map_id) is None:
256
+ raise MazeModeBenchError("map_id is invalid")
257
+
258
+ expected_actions = POINT_ACTIONS if verifier == POINT_MAZE_VERIFIER else ANT_ACTIONS
259
+ raw_actions = spec.get("action_tokens")
260
+ if not isinstance(raw_actions, list) or tuple(raw_actions) != expected_actions:
261
+ raise MazeModeBenchError("action_tokens differ from the frozen verifier alphabet")
262
+
263
+ environment_sha256 = _sha(spec.get("environment_sha256"), label="environment_sha256")
264
+ raw_controller = spec.get("controller_sha256")
265
+ if verifier == ANT_MAZE_VERIFIER:
266
+ controller_sha256 = _sha(raw_controller, label="controller_sha256")
267
+ else:
268
+ if raw_controller is not None:
269
+ raise MazeModeBenchError("PointMaze cannot declare a locomotion controller")
270
+ controller_sha256 = None
271
+
272
+ min_actions = _bounded_int(
273
+ spec.get("min_actions"), label="min_actions", minimum=1, maximum=512
274
+ )
275
+ max_actions = _bounded_int(
276
+ spec.get("max_actions"), label="max_actions", minimum=min_actions, maximum=512
277
+ )
278
+ action_repeat = _bounded_int(
279
+ spec.get("action_repeat"),
280
+ label="action_repeat",
281
+ minimum=1,
282
+ maximum=100 if verifier == POINT_MAZE_VERIFIER else 400,
283
+ )
284
+ success_threshold = _finite_float(
285
+ spec.get("success_threshold"), label="success_threshold"
286
+ )
287
+ if not 0.0 < success_threshold <= 1.0:
288
+ raise MazeModeBenchError("success_threshold is outside (0, 1]")
289
+ max_segment_length = _finite_float(
290
+ spec.get("max_segment_length"), label="max_segment_length"
291
+ )
292
+ if not 0.0 < max_segment_length <= 10.0:
293
+ raise MazeModeBenchError("max_segment_length is outside (0, 10]")
294
+
295
+ maze_map, reset_cell, goal_cell = _parse_maze_map(
296
+ spec.get("maze_map"),
297
+ spec.get("reset_cell"),
298
+ spec.get("goal_cell"),
299
+ )
300
+
301
+ return MazeActionSpec(
302
+ verifier=verifier,
303
+ environment_id=environment_id,
304
+ environment_sha256=environment_sha256,
305
+ controller_sha256=controller_sha256,
306
+ map_id=map_id,
307
+ maze_map=maze_map,
308
+ reset_cell=reset_cell,
309
+ goal_cell=goal_cell,
310
+ reset_seed=_bounded_int(
311
+ spec.get("reset_seed"), label="reset_seed", minimum=0, maximum=2**31 - 1
312
+ ),
313
+ min_actions=min_actions,
314
+ max_actions=max_actions,
315
+ action_repeat=action_repeat,
316
+ action_tokens=expected_actions,
317
+ success_threshold=success_threshold,
318
+ max_segment_length=max_segment_length,
319
+ bounds=_parse_bounds(spec.get("bounds_xy")),
320
+ gates=_parse_gates(spec.get("route_gates")),
321
+ spec_sha256=_canonical_spec_sha256(spec),
322
+ )
323
+
324
+
325
+ def parse_maze_action_program(candidate: str, spec: MazeActionSpec) -> tuple[str, ...]:
326
+ """Parse a bounded whitespace/comma-separated action program."""
327
+
328
+ text = str(candidate).strip()
329
+ if not text or len(text) > _MAX_PROGRAM_CHARS:
330
+ raise MazeModeBenchError("action program is empty or too long")
331
+ tokens = tuple(token for token in re.split(r"[\s,]+", text.upper()) if token)
332
+ if not spec.min_actions <= len(tokens) <= spec.max_actions:
333
+ raise MazeModeBenchError("action program length is outside the frozen bounds")
334
+ allowed = set(spec.action_tokens)
335
+ unknown = [token for token in tokens if token not in allowed]
336
+ if unknown:
337
+ raise MazeModeBenchError(f"unknown action token {unknown[0]!r}")
338
+ return tokens
339
+
340
+
341
+ def _parse_execution_record(value: Mapping[str, Any]) -> MazeExecutionRecord:
342
+ if not isinstance(value, Mapping):
343
+ raise MazeModeBenchError("execution record must be an object")
344
+ raw_trajectory = value.get("trajectory_xy")
345
+ if not isinstance(raw_trajectory, list) or len(raw_trajectory) < 2:
346
+ raise MazeModeBenchError("execution trajectory must contain at least two points")
347
+ trajectory: list[tuple[float, float]] = []
348
+ for index, raw_point in enumerate(raw_trajectory):
349
+ if not isinstance(raw_point, list) or len(raw_point) != 2:
350
+ raise MazeModeBenchError(f"trajectory point {index} is malformed")
351
+ trajectory.append(
352
+ (
353
+ _finite_float(raw_point[0], label=f"trajectory[{index}].x"),
354
+ _finite_float(raw_point[1], label=f"trajectory[{index}].y"),
355
+ )
356
+ )
357
+ raw_success = value.get("success")
358
+ if not isinstance(raw_success, bool):
359
+ raise MazeModeBenchError("execution success must be boolean")
360
+ raw_tokens = value.get("action_tokens")
361
+ if not isinstance(raw_tokens, list) or not all(isinstance(x, str) for x in raw_tokens):
362
+ raise MazeModeBenchError("execution action_tokens must be a string list")
363
+ raw_controller = value.get("controller_sha256")
364
+ controller_sha256 = None if raw_controller is None else _sha(
365
+ raw_controller, label="execution.controller_sha256"
366
+ )
367
+ return MazeExecutionRecord(
368
+ environment_sha256=_sha(
369
+ value.get("environment_sha256"), label="execution.environment_sha256"
370
+ ),
371
+ controller_sha256=controller_sha256,
372
+ spec_sha256=_sha(value.get("spec_sha256"), label="execution.spec_sha256"),
373
+ reset_seed=_bounded_int(
374
+ value.get("reset_seed"),
375
+ label="execution.reset_seed",
376
+ minimum=0,
377
+ maximum=2**31 - 1,
378
+ ),
379
+ action_tokens=tuple(raw_tokens),
380
+ success=raw_success,
381
+ final_goal_distance=_finite_float(
382
+ value.get("final_goal_distance"), label="execution.final_goal_distance"
383
+ ),
384
+ trajectory_xy=tuple(trajectory),
385
+ simulator_steps=_bounded_int(
386
+ value.get("simulator_steps"),
387
+ label="execution.simulator_steps",
388
+ minimum=1,
389
+ maximum=1_000_000,
390
+ ),
391
+ )
392
+
393
+
394
+ def _outside_side(value: float, gate: DirectedGate) -> int:
395
+ if value < gate.coordinate - gate.hysteresis:
396
+ return -1
397
+ if value > gate.coordinate + gate.hysteresis:
398
+ return 1
399
+ return 0
400
+
401
+
402
+ def _gate_crossing(
403
+ first: tuple[float, float],
404
+ second: tuple[float, float],
405
+ gate: DirectedGate,
406
+ ) -> str | None:
407
+ axis_index = 0 if gate.axis == "x" else 1
408
+ span_index = 1 - axis_index
409
+ denominator = second[axis_index] - first[axis_index]
410
+ if denominator == 0.0:
411
+ return None
412
+ fraction = (gate.coordinate - first[axis_index]) / denominator
413
+ if not 0.0 <= fraction <= 1.0:
414
+ return None
415
+ span_value = first[span_index] + fraction * (
416
+ second[span_index] - first[span_index]
417
+ )
418
+ if not gate.span_min <= span_value <= gate.span_max:
419
+ return None
420
+ direction = "+" if second[axis_index] > first[axis_index] else "-"
421
+ return f"{gate.gate_id}{direction}"
422
+
423
+
424
+ def extract_directed_gate_route(
425
+ trajectory_xy: Sequence[tuple[float, float]],
426
+ spec: MazeActionSpec,
427
+ ) -> tuple[str, ...]:
428
+ """Extract a hysteresis-stable ordered directed bottleneck sequence."""
429
+
430
+ if len(trajectory_xy) < 2:
431
+ raise MazeModeBenchError("trajectory is too short")
432
+ if len(trajectory_xy) > spec.max_actions * spec.action_repeat + 2:
433
+ raise MazeModeBenchError("trajectory exceeds the frozen execution horizon")
434
+ for index, point in enumerate(trajectory_xy):
435
+ if not (
436
+ spec.bounds[0][0] <= point[0] <= spec.bounds[0][1]
437
+ and spec.bounds[1][0] <= point[1] <= spec.bounds[1][1]
438
+ ):
439
+ raise MazeModeBenchError(f"trajectory point {index} is outside maze bounds")
440
+ if index:
441
+ previous = trajectory_xy[index - 1]
442
+ distance = math.hypot(point[0] - previous[0], point[1] - previous[1])
443
+ if distance > spec.max_segment_length:
444
+ raise MazeModeBenchError("trajectory contains a teleport-sized segment")
445
+
446
+ route: list[str] = []
447
+ state: dict[str, tuple[int, tuple[float, float]] | None] = {
448
+ gate.gate_id: None for gate in spec.gates
449
+ }
450
+ for point in trajectory_xy:
451
+ step_crossings: list[str] = []
452
+ for gate in spec.gates:
453
+ coordinate = point[0] if gate.axis == "x" else point[1]
454
+ side = _outside_side(coordinate, gate)
455
+ previous_state = state[gate.gate_id]
456
+ if side == 0:
457
+ continue
458
+ if previous_state is None:
459
+ state[gate.gate_id] = (side, point)
460
+ continue
461
+ previous_side, previous_point = previous_state
462
+ if side != previous_side:
463
+ crossing = _gate_crossing(previous_point, point, gate)
464
+ if crossing is not None:
465
+ step_crossings.append(crossing)
466
+ state[gate.gate_id] = (side, point)
467
+ if len(step_crossings) > 1:
468
+ raise MazeModeBenchError("one trajectory segment crosses multiple route gates")
469
+ if step_crossings and (not route or route[-1] != step_crossings[0]):
470
+ route.append(step_crossings[0])
471
+ if not route:
472
+ raise MazeModeBenchError("successful trajectory has no certified route gate")
473
+ gate_ids = [crossing[:-1] for crossing in route]
474
+ if len(gate_ids) != len(set(gate_ids)):
475
+ raise MazeModeBenchError("trajectory recrosses a route gate")
476
+ return tuple(route)
477
+
478
+
479
+ def validate_maze_execution(
480
+ candidate: str,
481
+ raw_spec: Mapping[str, Any],
482
+ raw_execution: Mapping[str, Any],
483
+ ) -> MazeValidation:
484
+ """Bind one successful simulator execution to its semantic route key."""
485
+
486
+ spec = parse_maze_action_spec(raw_spec)
487
+ tokens = parse_maze_action_program(candidate, spec)
488
+ execution = _parse_execution_record(raw_execution)
489
+ if execution.environment_sha256 != spec.environment_sha256:
490
+ raise MazeModeBenchError("execution environment hash does not match the spec")
491
+ if execution.controller_sha256 != spec.controller_sha256:
492
+ raise MazeModeBenchError("execution controller hash does not match the spec")
493
+ if execution.spec_sha256 != spec.spec_sha256:
494
+ raise MazeModeBenchError("execution is bound to a different spec")
495
+ if execution.reset_seed != spec.reset_seed:
496
+ raise MazeModeBenchError("execution reset seed does not match the spec")
497
+ if execution.action_tokens != tokens:
498
+ raise MazeModeBenchError("execution action program does not match the candidate")
499
+ if not execution.success:
500
+ raise MazeModeBenchError("unsuccessful execution has no ModeBench identity")
501
+ if not 0.0 <= execution.final_goal_distance <= spec.success_threshold:
502
+ raise MazeModeBenchError("successful execution fails the frozen goal threshold")
503
+ if execution.simulator_steps > len(tokens) * spec.action_repeat:
504
+ raise MazeModeBenchError("execution exceeds the action-program step budget")
505
+ route = extract_directed_gate_route(execution.trajectory_xy, spec)
506
+ action_version = (
507
+ MAZE_ACTION_VERSION
508
+ if spec.verifier == POINT_MAZE_VERIFIER
509
+ else ANT_MAZE_ACTION_VERSION
510
+ )
511
+ key = f"{spec.verifier}:{action_version}:{spec.map_id}:" + ",".join(route)
512
+ return MazeValidation(
513
+ canonical_key=key,
514
+ directed_gates=route,
515
+ action_tokens=tokens,
516
+ simulator_steps=execution.simulator_steps,
517
+ )
code/oat_drgrpo/maze_modebench_process.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Killable external MuJoCo boundary for maze language-action programs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import select
9
+ import subprocess
10
+ import threading
11
+ from typing import Any, Mapping
12
+
13
+ from .maze_modebench import MazeValidation
14
+
15
+
16
+ class MazeVerifierProcess:
17
+ """Execute maze action programs outside the trainer process."""
18
+
19
+ def __init__(
20
+ self,
21
+ *,
22
+ timeout_seconds: float = 25.0,
23
+ worker_python: str | Path | None = None,
24
+ ) -> None:
25
+ if timeout_seconds <= 0:
26
+ raise ValueError("timeout_seconds must be positive")
27
+ root = Path(
28
+ os.environ.get(
29
+ "OAT_ZERO_REPO_ROOT", Path(__file__).resolve().parents[2]
30
+ )
31
+ ).resolve()
32
+ configured = worker_python or os.environ.get("OAT_ZERO_MAZE_WORKER_PYTHON")
33
+ self.worker_python = Path(configured) if configured else (
34
+ root / "var/maze_runtime/venv/bin/python"
35
+ )
36
+ self.timeout_seconds = float(timeout_seconds)
37
+ self._process: subprocess.Popen[str] | None = None
38
+ self._owner_pid = os.getpid()
39
+ self._lock = threading.Lock()
40
+
41
+ def _start(self) -> subprocess.Popen[str]:
42
+ if self._owner_pid != os.getpid():
43
+ self._process = None
44
+ self._owner_pid = os.getpid()
45
+ process = self._process
46
+ if process is not None and process.poll() is None:
47
+ return process
48
+ if not self.worker_python.is_file():
49
+ raise FileNotFoundError(f"maze worker Python is missing: {self.worker_python}")
50
+ source_root = str(Path(__file__).resolve().parents[1])
51
+ entrypoint = (
52
+ "import runpy,sys;"
53
+ f"sys.path.insert(0,{source_root!r});"
54
+ "runpy.run_module('oat_drgrpo.maze_modebench_worker',run_name='__main__')"
55
+ )
56
+ worker_env = os.environ.copy()
57
+ worker_env.setdefault("MUJOCO_GL", "egl")
58
+ self._process = subprocess.Popen(
59
+ [str(self.worker_python), "-B", "-I", "-c", entrypoint],
60
+ stdin=subprocess.PIPE,
61
+ stdout=subprocess.PIPE,
62
+ stderr=None,
63
+ text=True,
64
+ encoding="utf-8",
65
+ bufsize=1,
66
+ start_new_session=True,
67
+ env=worker_env,
68
+ )
69
+ return self._process
70
+
71
+ def _stop(self) -> None:
72
+ process, self._process = self._process, None
73
+ if process is None:
74
+ return
75
+ if process.poll() is None:
76
+ process.terminate()
77
+ try:
78
+ process.wait(timeout=1)
79
+ except subprocess.TimeoutExpired:
80
+ process.kill()
81
+ process.wait(timeout=1)
82
+ if process.stdin is not None:
83
+ process.stdin.close()
84
+ if process.stdout is not None:
85
+ process.stdout.close()
86
+
87
+ def close(self) -> None:
88
+ with self._lock:
89
+ self._stop()
90
+
91
+ def validate(
92
+ self,
93
+ candidate: str,
94
+ spec: Mapping[str, Any],
95
+ ) -> MazeValidation | None:
96
+ result = self.validate_with_execution(candidate, spec)
97
+ return result[0] if result is not None else None
98
+
99
+ def validate_with_execution(
100
+ self,
101
+ candidate: str,
102
+ spec: Mapping[str, Any],
103
+ ) -> tuple[MazeValidation, dict[str, Any]] | None:
104
+ """Return validation plus the trusted raw record for offline audits."""
105
+
106
+ request = json.dumps(
107
+ {"candidate": str(candidate), "spec": dict(spec)},
108
+ allow_nan=False,
109
+ )
110
+ with self._lock:
111
+ for attempt in range(2):
112
+ try:
113
+ process = self._start()
114
+ assert process.stdin is not None and process.stdout is not None
115
+ process.stdin.write(request + "\n")
116
+ process.stdin.flush()
117
+ readable, _, _ = select.select(
118
+ [process.stdout], [], [], self.timeout_seconds
119
+ )
120
+ if not readable:
121
+ self._stop()
122
+ return None
123
+ line = process.stdout.readline()
124
+ if not line:
125
+ raise BrokenPipeError("maze worker closed stdout")
126
+ payload = json.loads(line)
127
+ if not payload.get("valid"):
128
+ return None
129
+ validation = MazeValidation(
130
+ canonical_key=str(payload["canonical_key"]),
131
+ directed_gates=tuple(
132
+ str(value) for value in payload["directed_gates"]
133
+ ),
134
+ action_tokens=tuple(
135
+ str(value) for value in payload["action_tokens"]
136
+ ),
137
+ simulator_steps=int(payload["simulator_steps"]),
138
+ )
139
+ return validation, dict(payload["execution"])
140
+ except (
141
+ BrokenPipeError,
142
+ FileNotFoundError,
143
+ OSError,
144
+ ValueError,
145
+ json.JSONDecodeError,
146
+ ):
147
+ self._stop()
148
+ if attempt:
149
+ return None
150
+ return None
151
+
152
+ def __del__(self) -> None:
153
+ try:
154
+ self._stop()
155
+ except Exception:
156
+ pass
157
+
158
+
159
+ _SHARED_VERIFIER = MazeVerifierProcess()
160
+
161
+
162
+ def validate_maze_action_program_external(
163
+ candidate: str,
164
+ spec: Mapping[str, Any],
165
+ ) -> MazeValidation | None:
166
+ """Validate a candidate through the shared pinned MuJoCo worker."""
167
+
168
+ return _SHARED_VERIFIER.validate(candidate, spec)
code/oat_drgrpo/maze_modebench_worker.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Networkless JSON-lines worker for 0.5B maze action programs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import os
8
+ import signal
9
+ import sys
10
+ from typing import Any, Mapping
11
+
12
+ from .maze_modebench import (
13
+ ANT_MAZE_VERIFIER,
14
+ POINT_MAZE_VERIFIER,
15
+ parse_maze_action_program,
16
+ parse_maze_action_spec,
17
+ validate_maze_execution,
18
+ )
19
+ from .maze_runtime_identity import maze_runtime_identity
20
+ from .ant_maze_worker_v5 import execute_ant_v5
21
+ from .ant_maze_worker_v5 import RECEIPT_SHA256 as ANT_V5_RECEIPT_SHA256
22
+ from .ant_maze_worker_v8 import execute_ant_v8
23
+ from .ant_maze_worker_v8 import RECEIPT_SHA256 as ANT_V8_RECEIPT_SHA256
24
+ from .ant_maze_worker_v9 import controller_receipt_sha256 as ant_v9_receipt_sha256
25
+ from .ant_maze_worker_v9 import execute_ant_v9
26
+ from .ant_maze_worker_v10 import controller_receipt_sha256 as ant_v10_receipt_sha256
27
+ from .ant_maze_worker_v10 import execute_ant_v10
28
+ from .ant_maze_worker_v11 import controller_receipt_sha256 as ant_v11_receipt_sha256
29
+ from .ant_maze_worker_v11 import execute_ant_v11
30
+ from .ant_maze_worker_v12 import controller_receipt_sha256 as ant_v12_receipt_sha256
31
+ from .ant_maze_worker_v12 import execute_ant_v12
32
+
33
+
34
+ WORKER_TIMEOUT_SECONDS = float(
35
+ os.environ.get("OAT_ZERO_MAZE_WORKER_TIMEOUT_SECONDS", "20.0")
36
+ )
37
+ if not math.isfinite(WORKER_TIMEOUT_SECONDS) or WORKER_TIMEOUT_SECONDS <= 0:
38
+ raise ValueError("maze worker timeout must be finite and positive")
39
+
40
+
41
+ def _timeout(_signum, _frame) -> None:
42
+ raise TimeoutError("maze action-program execution timed out")
43
+
44
+
45
+ def _point_action(token: str):
46
+ import numpy as np
47
+
48
+ diagonal = 1.0 / math.sqrt(2.0)
49
+ values = {
50
+ "N": (0.0, 1.0),
51
+ "NE": (diagonal, diagonal),
52
+ "E": (1.0, 0.0),
53
+ "SE": (diagonal, -diagonal),
54
+ "S": (0.0, -1.0),
55
+ "SW": (-diagonal, -diagonal),
56
+ "W": (-1.0, 0.0),
57
+ "NW": (-diagonal, diagonal),
58
+ "COAST": (0.0, 0.0),
59
+ }
60
+ return np.asarray(values[token], dtype=np.float32)
61
+
62
+
63
+ def _execute_point(candidate: str, raw_spec: Mapping[str, Any]):
64
+ import gymnasium as gym
65
+ import gymnasium_robotics
66
+ import numpy as np
67
+
68
+ gym.register_envs(gymnasium_robotics)
69
+ spec = parse_maze_action_spec(raw_spec)
70
+ if spec.verifier != POINT_MAZE_VERIFIER:
71
+ raise ValueError("PointMaze executor received a non-PointMaze spec")
72
+ runtime = maze_runtime_identity()
73
+ if spec.environment_sha256 != runtime["point_environment_sha256"]:
74
+ raise ValueError("PointMaze environment hash differs from installed runtime")
75
+ tokens = parse_maze_action_program(candidate, spec)
76
+ env = gym.make(
77
+ spec.environment_id,
78
+ maze_map=[list(row) for row in spec.maze_map],
79
+ reward_type="sparse",
80
+ continuing_task=False,
81
+ reset_target=False,
82
+ max_episode_steps=len(tokens) * spec.action_repeat,
83
+ )
84
+ try:
85
+ # Gymnasium-Robotics 1.4.2 forwards this constructor argument to the
86
+ # nested PointEnv, so bind it on the MazeEnv before reset instead.
87
+ env.unwrapped.position_noise_range = 0.0
88
+ observation, info = env.reset(
89
+ seed=spec.reset_seed,
90
+ options={
91
+ "reset_cell": list(spec.reset_cell),
92
+ "goal_cell": list(spec.goal_cell),
93
+ },
94
+ )
95
+ trajectory = [observation["achieved_goal"].astype(float).tolist()]
96
+ success = bool(info.get("success", False))
97
+ simulator_steps = 0
98
+ for token in tokens:
99
+ action = _point_action(token)
100
+ for _ in range(spec.action_repeat):
101
+ observation, _reward, terminated, truncated, info = env.step(action)
102
+ simulator_steps += 1
103
+ achieved = observation["achieved_goal"].astype(float)
104
+ trajectory.append(achieved.tolist())
105
+ success = bool(info.get("success", False))
106
+ if success or terminated or truncated:
107
+ break
108
+ if success or terminated or truncated:
109
+ break
110
+ distance = float(
111
+ np.linalg.norm(
112
+ observation["achieved_goal"] - observation["desired_goal"]
113
+ )
114
+ )
115
+ finally:
116
+ env.close()
117
+ execution = {
118
+ "environment_sha256": spec.environment_sha256,
119
+ "controller_sha256": None,
120
+ "spec_sha256": spec.spec_sha256,
121
+ "reset_seed": spec.reset_seed,
122
+ "action_tokens": list(tokens),
123
+ "success": success,
124
+ "final_goal_distance": distance,
125
+ "trajectory_xy": trajectory,
126
+ "simulator_steps": simulator_steps,
127
+ }
128
+ return validate_maze_execution(candidate, raw_spec, execution), execution
129
+
130
+
131
+ def execute(candidate: str, raw_spec: Mapping[str, Any]):
132
+ spec = parse_maze_action_spec(raw_spec)
133
+ if spec.verifier == POINT_MAZE_VERIFIER:
134
+ return _execute_point(candidate, raw_spec)
135
+ if spec.verifier == ANT_MAZE_VERIFIER:
136
+ if spec.controller_sha256 == ANT_V5_RECEIPT_SHA256:
137
+ return execute_ant_v5(candidate, raw_spec)
138
+ if spec.controller_sha256 == ANT_V8_RECEIPT_SHA256:
139
+ return execute_ant_v8(candidate, raw_spec)
140
+ # V12 route identities are intentionally incompatible with the older
141
+ # controller-specific route schemas. Resolve the newest bound
142
+ # controller before asking any older validator to inspect that identity.
143
+ if spec.controller_sha256 == ant_v12_receipt_sha256():
144
+ return execute_ant_v12(candidate, raw_spec)
145
+ if spec.controller_sha256 == ant_v9_receipt_sha256():
146
+ return execute_ant_v9(candidate, raw_spec)
147
+ if spec.controller_sha256 == ant_v10_receipt_sha256():
148
+ return execute_ant_v10(candidate, raw_spec)
149
+ if spec.controller_sha256 == ant_v11_receipt_sha256():
150
+ return execute_ant_v11(candidate, raw_spec)
151
+ raise ValueError("unsupported AntMaze controller identity")
152
+ raise ValueError("unsupported maze verifier")
153
+
154
+
155
+ def main() -> None:
156
+ signal.signal(signal.SIGALRM, _timeout)
157
+ for line in sys.stdin:
158
+ try:
159
+ request = json.loads(line)
160
+ signal.setitimer(signal.ITIMER_REAL, WORKER_TIMEOUT_SECONDS)
161
+ validation, execution = execute(request["candidate"], request["spec"])
162
+ payload = {
163
+ "valid": True,
164
+ "canonical_key": validation.canonical_key,
165
+ "directed_gates": list(validation.directed_gates),
166
+ "action_tokens": list(validation.action_tokens),
167
+ "simulator_steps": validation.simulator_steps,
168
+ "execution": execution,
169
+ }
170
+ except Exception as error:
171
+ payload = {"valid": False, "error": type(error).__name__}
172
+ finally:
173
+ signal.setitimer(signal.ITIMER_REAL, 0.0)
174
+ sys.stdout.write(json.dumps(payload, allow_nan=False) + "\n")
175
+ sys.stdout.flush()
176
+
177
+
178
+ if __name__ == "__main__":
179
+ main()
code/oat_drgrpo/maze_runtime_identity.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hash the exact installed runtime used by maze execution workers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import importlib.metadata
7
+ import json
8
+ from pathlib import Path
9
+ import platform
10
+ from typing import Any
11
+
12
+
13
+ def _sha256(path: Path) -> str:
14
+ digest = hashlib.sha256()
15
+ with path.open("rb") as handle:
16
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
17
+ digest.update(chunk)
18
+ return digest.hexdigest()
19
+
20
+
21
+ def _canonical_sha256(value: Any) -> str:
22
+ encoded = json.dumps(
23
+ value,
24
+ allow_nan=False,
25
+ ensure_ascii=True,
26
+ separators=(",", ":"),
27
+ sort_keys=True,
28
+ ).encode("ascii")
29
+ return hashlib.sha256(encoded).hexdigest()
30
+
31
+
32
+ def _file_receipt(path: Path, package_root: Path) -> dict[str, str]:
33
+ return {
34
+ "path": path.relative_to(package_root.parent).as_posix(),
35
+ "sha256": _sha256(path),
36
+ }
37
+
38
+
39
+ def maze_runtime_identity() -> dict[str, Any]:
40
+ """Return source-bound PointMaze and AntMaze environment identities."""
41
+
42
+ import gymnasium
43
+ import gymnasium_robotics
44
+
45
+ robotics_root = Path(gymnasium_robotics.__file__).resolve().parent
46
+ site_packages = robotics_root.parent
47
+ gymnasium_root = Path(gymnasium.__file__).resolve().parent
48
+ common = {
49
+ "python": platform.python_version(),
50
+ "packages": {
51
+ package: importlib.metadata.version(package)
52
+ for package in ("gymnasium", "gymnasium-robotics", "mujoco", "numpy")
53
+ },
54
+ "maze_v4": _file_receipt(
55
+ robotics_root / "envs/maze/maze_v4.py", site_packages
56
+ ),
57
+ }
58
+ point_payload = {
59
+ "schema_version": "point-maze-runtime-v1",
60
+ "common": common,
61
+ "point_maze": _file_receipt(
62
+ robotics_root / "envs/maze/point_maze.py", site_packages
63
+ ),
64
+ "point_xml": _file_receipt(
65
+ robotics_root / "envs/assets/point/point.xml", site_packages
66
+ ),
67
+ }
68
+ ant_payload = {
69
+ "schema_version": "ant-maze-runtime-v1",
70
+ "common": common,
71
+ "ant_maze": _file_receipt(
72
+ robotics_root / "envs/maze/ant_maze_v5.py", site_packages
73
+ ),
74
+ "ant_v5": _file_receipt(
75
+ gymnasium_root / "envs/mujoco/ant_v5.py", site_packages
76
+ ),
77
+ "ant_xml": _file_receipt(
78
+ gymnasium_root / "envs/mujoco/assets/ant.xml", site_packages
79
+ ),
80
+ }
81
+ return {
82
+ "schema_version": "maze-runtime-identity-v1",
83
+ "point": point_payload,
84
+ "ant": ant_payload,
85
+ "point_environment_sha256": _canonical_sha256(point_payload),
86
+ "ant_environment_sha256": _canonical_sha256(ant_payload),
87
+ }
code/oat_drgrpo/modebench_guided.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Target-blind legal-output grammars for the admitted Level-2 benchmark."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import itertools
6
+ import json
7
+ import re
8
+
9
+
10
+ PROFILES = frozenset({"none", "domain_legal_v1", "countdown_legal_v3"})
11
+
12
+
13
+ def countdown_legal_regex(reference: str) -> str:
14
+ """Enumerate operand-exact expression syntax without consulting the target."""
15
+
16
+ numbers = tuple(str(int(value)) for value in json.loads(reference)["numbers"])
17
+ operator = r"[+*/-]"
18
+
19
+ def trees(values: tuple[str, ...]) -> tuple[str, ...]:
20
+ if len(values) == 1:
21
+ return (re.escape(values[0]),)
22
+ expressions = []
23
+ for split in range(1, len(values)):
24
+ for left in trees(values[:split]):
25
+ for right in trees(values[split:]):
26
+ expressions.append(r"\(" + left + " " + operator + " " + right + r"\)")
27
+ return tuple(expressions)
28
+
29
+ expressions = set()
30
+ for values in set(itertools.permutations(numbers)):
31
+ expressions.update(trees(values))
32
+ return r"\\boxed\{(?:" + "|".join(sorted(expressions)) + r")\}"
33
+
34
+
35
+ def legal_regex(profile: str, domain: str, reference: str) -> str | None:
36
+ """Return the frozen legal syntax for one row; never inspect its target."""
37
+
38
+ if profile not in PROFILES:
39
+ raise ValueError(f"unknown ModeBench syntax profile: {profile}")
40
+ if profile == "none":
41
+ return None
42
+ if profile == "countdown_legal_v3":
43
+ if domain != "countdown":
44
+ raise ValueError("countdown_legal_v3 is Countdown-only")
45
+ return countdown_legal_regex(reference)
46
+ if domain == "pantry_plan":
47
+ spec = json.loads(reference)
48
+ alternatives = []
49
+ for ingredient in spec["ingredients"]:
50
+ identifier = str(ingredient["id"])
51
+ minimum = int(ingredient["min_if_used_g"])
52
+ available = int(ingredient["available_g"])
53
+ step = int(ingredient["step_g"])
54
+ alternatives.extend(
55
+ f"{identifier}={grams}"
56
+ for grams in range(minimum, available + 1, step)
57
+ )
58
+ atom = "(?:" + "|".join(re.escape(value) for value in alternatives) + ")"
59
+ return r"\\boxed\{" + atom + "(?:;" + atom + r"){1,3}\}"
60
+ fixed = {
61
+ "python_factors": r"\\boxed\{lambda n: [A-Za-z0-9 _%<>=!+*/().-]+\}",
62
+ "mathir": r"\\boxed\{[A-F](?:;[A-F]){0,3}\}",
63
+ }
64
+ if domain not in fixed:
65
+ raise ValueError(f"domain_legal_v1 has no grammar for {domain}")
66
+ return fixed[domain]
67
+
68
+
69
+ def guided_sampling_params(base, profile: str, domain: str, references: list[str]):
70
+ """Copy one vLLM parameter object per row and attach its legal grammar."""
71
+
72
+ if profile == "none":
73
+ return base
74
+ import copy
75
+ from vllm.sampling_params import GuidedDecodingParams
76
+
77
+ params = []
78
+ for reference in references:
79
+ row = copy.copy(base)
80
+ regex = legal_regex(profile, domain, str(reference))
81
+ if regex is None:
82
+ raise RuntimeError("active syntax profile resolved no grammar")
83
+ row.guided_decoding = GuidedDecodingParams(regex=regex)
84
+ params.append(row)
85
+ return params
code/oat_drgrpo/pantry_plan.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Executable nutrition-and-inventory plans for PantryPlan ModeBench.
2
+
3
+ The model emits a compact allocation such as ``lentils=150;rice=100``. The
4
+ trusted specification supplies a frozen pantry, exact per-100g attributes,
5
+ dietary exclusions, and feasibility bounds. Correctness and semantic identity
6
+ come from the same validation:
7
+
8
+ * every used ingredient exists, is allowed, and respects its available,
9
+ minimum-serving, and quantity-step limits;
10
+ * exact decimal arithmetic checks mass, nutrition, cost, and other registered
11
+ bounds; and
12
+ * the canonical mode is the sorted set of ingredients actually used.
13
+
14
+ Quantities affect correctness but not identity. This deliberately collapses
15
+ nearby quantity variants of the same formulation instead of treating gram-level
16
+ perturbations as new semantic modes.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from dataclasses import dataclass
22
+ from decimal import Decimal, InvalidOperation
23
+ import re
24
+ from typing import Any, Mapping
25
+
26
+
27
+ PANTRY_PLAN_VERIFIER = "pantry_plan"
28
+ PANTRY_PLAN_VERSION = "pantry-v1"
29
+
30
+ _ID = re.compile(r"[a-z][a-z0-9_]{0,31}")
31
+ _ATTRIBUTE = re.compile(r"[a-z][a-z0-9_]{0,31}")
32
+ _TAG = re.compile(r"[a-z][a-z0-9_-]{0,31}")
33
+ _MAX_INGREDIENTS = 16
34
+ _MAX_CANDIDATE_CHARS = 512
35
+ _ALLOWED_ATTRIBUTES = {
36
+ "energy_kcal",
37
+ "protein_g",
38
+ "fiber_g",
39
+ "fat_g",
40
+ "carbohydrate_g",
41
+ "sodium_mg",
42
+ "cost_cents",
43
+ }
44
+
45
+
46
+ class PantryPlanError(ValueError):
47
+ """Raised for an invalid trusted specification or candidate plan."""
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class PantryIngredient:
52
+ ingredient_id: str
53
+ available_g: int
54
+ step_g: int
55
+ min_if_used_g: int
56
+ attributes_per_100g: tuple[tuple[str, Decimal], ...]
57
+ tags: frozenset[str]
58
+
59
+ @property
60
+ def attributes(self) -> dict[str, Decimal]:
61
+ return dict(self.attributes_per_100g)
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class PantryTarget:
66
+ attribute: str
67
+ minimum: Decimal | None
68
+ maximum: Decimal | None
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class PantryPlanSpec:
73
+ ingredients: tuple[PantryIngredient, ...]
74
+ targets: tuple[PantryTarget, ...]
75
+ min_ingredients: int
76
+ max_ingredients: int
77
+ forbidden_tags: frozenset[str]
78
+ certified_mode_count: int
79
+
80
+ @property
81
+ def ingredient_by_id(self) -> dict[str, PantryIngredient]:
82
+ return {row.ingredient_id: row for row in self.ingredients}
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class PantryPlanValidation:
87
+ """One accepted allocation and its validator-derived semantic mode."""
88
+
89
+ canonical_key: str
90
+ allocations_g: tuple[tuple[str, int], ...]
91
+ totals: tuple[tuple[str, Decimal], ...]
92
+
93
+
94
+ def _decimal(value: Any, *, label: str) -> Decimal:
95
+ if isinstance(value, bool) or not isinstance(value, (int, float, str, Decimal)):
96
+ raise PantryPlanError(f"{label} must be a finite decimal")
97
+ try:
98
+ result = Decimal(str(value))
99
+ except (InvalidOperation, ValueError) as error:
100
+ raise PantryPlanError(f"{label} must be a finite decimal") from error
101
+ if not result.is_finite() or result < 0:
102
+ raise PantryPlanError(f"{label} must be a nonnegative finite decimal")
103
+ return result
104
+
105
+
106
+ def _bounded_int(
107
+ value: Any,
108
+ *,
109
+ label: str,
110
+ minimum: int,
111
+ maximum: int,
112
+ ) -> int:
113
+ if isinstance(value, bool) or not isinstance(value, int):
114
+ raise PantryPlanError(f"{label} must be an integer")
115
+ result = int(value)
116
+ if not minimum <= result <= maximum:
117
+ raise PantryPlanError(f"{label} is outside [{minimum}, {maximum}]")
118
+ return result
119
+
120
+
121
+ def _tags(value: Any, *, label: str) -> frozenset[str]:
122
+ if not isinstance(value, list) or len(value) > 32:
123
+ raise PantryPlanError(f"{label} must be a bounded tag list")
124
+ result: set[str] = set()
125
+ for raw in value:
126
+ tag = str(raw)
127
+ if not _TAG.fullmatch(tag):
128
+ raise PantryPlanError(f"{label} contains invalid tag {tag!r}")
129
+ if tag in result:
130
+ raise PantryPlanError(f"{label} contains duplicate tag {tag!r}")
131
+ result.add(tag)
132
+ return frozenset(result)
133
+
134
+
135
+ def parse_pantry_plan_spec(spec: Mapping[str, Any]) -> PantryPlanSpec:
136
+ """Validate a trusted PantryPlan specification."""
137
+
138
+ if spec.get("verifier") != PANTRY_PLAN_VERIFIER:
139
+ raise PantryPlanError("wrong PantryPlan verifier")
140
+ if spec.get("pantry_version") != PANTRY_PLAN_VERSION:
141
+ raise PantryPlanError("unsupported PantryPlan version")
142
+
143
+ raw_ingredients = spec.get("ingredients")
144
+ if (
145
+ not isinstance(raw_ingredients, list)
146
+ or not 2 <= len(raw_ingredients) <= _MAX_INGREDIENTS
147
+ ):
148
+ raise PantryPlanError("ingredients must contain between 2 and 16 rows")
149
+
150
+ ingredients: list[PantryIngredient] = []
151
+ observed_ids: set[str] = set()
152
+ for index, raw in enumerate(raw_ingredients):
153
+ if not isinstance(raw, Mapping):
154
+ raise PantryPlanError(f"ingredient {index} must be an object")
155
+ ingredient_id = str(raw.get("id", ""))
156
+ if not _ID.fullmatch(ingredient_id):
157
+ raise PantryPlanError(f"ingredient {index} has an invalid id")
158
+ if ingredient_id in observed_ids:
159
+ raise PantryPlanError(f"duplicate ingredient id {ingredient_id!r}")
160
+ observed_ids.add(ingredient_id)
161
+
162
+ available_g = _bounded_int(
163
+ raw.get("available_g"),
164
+ label=f"{ingredient_id}.available_g",
165
+ minimum=1,
166
+ maximum=10_000,
167
+ )
168
+ step_g = _bounded_int(
169
+ raw.get("step_g"),
170
+ label=f"{ingredient_id}.step_g",
171
+ minimum=1,
172
+ maximum=1_000,
173
+ )
174
+ min_if_used_g = _bounded_int(
175
+ raw.get("min_if_used_g"),
176
+ label=f"{ingredient_id}.min_if_used_g",
177
+ minimum=step_g,
178
+ maximum=available_g,
179
+ )
180
+ if available_g % step_g or min_if_used_g % step_g:
181
+ raise PantryPlanError(
182
+ f"{ingredient_id} availability and minimum must align to step_g"
183
+ )
184
+
185
+ raw_attributes = raw.get("attributes_per_100g")
186
+ if not isinstance(raw_attributes, Mapping) or not raw_attributes:
187
+ raise PantryPlanError(
188
+ f"{ingredient_id}.attributes_per_100g must be nonempty"
189
+ )
190
+ attributes: list[tuple[str, Decimal]] = []
191
+ for raw_name, raw_value in raw_attributes.items():
192
+ name = str(raw_name)
193
+ if (
194
+ not _ATTRIBUTE.fullmatch(name)
195
+ or name not in _ALLOWED_ATTRIBUTES
196
+ ):
197
+ raise PantryPlanError(
198
+ f"{ingredient_id} has unsupported attribute {name!r}"
199
+ )
200
+ attributes.append(
201
+ (
202
+ name,
203
+ _decimal(
204
+ raw_value,
205
+ label=f"{ingredient_id}.attributes_per_100g.{name}",
206
+ ),
207
+ )
208
+ )
209
+ ingredients.append(
210
+ PantryIngredient(
211
+ ingredient_id=ingredient_id,
212
+ available_g=available_g,
213
+ step_g=step_g,
214
+ min_if_used_g=min_if_used_g,
215
+ attributes_per_100g=tuple(sorted(attributes)),
216
+ tags=_tags(raw.get("tags", []), label=f"{ingredient_id}.tags"),
217
+ )
218
+ )
219
+
220
+ min_ingredients = _bounded_int(
221
+ spec.get("min_ingredients"),
222
+ label="min_ingredients",
223
+ minimum=1,
224
+ maximum=len(ingredients),
225
+ )
226
+ max_ingredients = _bounded_int(
227
+ spec.get("max_ingredients"),
228
+ label="max_ingredients",
229
+ minimum=min_ingredients,
230
+ maximum=len(ingredients),
231
+ )
232
+ certified_mode_count = _bounded_int(
233
+ spec.get("certified_mode_count"),
234
+ label="certified_mode_count",
235
+ minimum=2,
236
+ maximum=1_000_000,
237
+ )
238
+ forbidden_tags = _tags(spec.get("forbidden_tags", []), label="forbidden_tags")
239
+
240
+ raw_targets = spec.get("targets")
241
+ if not isinstance(raw_targets, Mapping) or not raw_targets:
242
+ raise PantryPlanError("targets must be a nonempty object")
243
+ targets: list[PantryTarget] = []
244
+ for raw_name, raw_bounds in raw_targets.items():
245
+ name = str(raw_name)
246
+ if name != "mass_g" and name not in _ALLOWED_ATTRIBUTES:
247
+ raise PantryPlanError(f"unsupported target attribute {name!r}")
248
+ if not isinstance(raw_bounds, Mapping):
249
+ raise PantryPlanError(f"target {name!r} must be an object")
250
+ unknown_bounds = set(raw_bounds) - {"min", "max"}
251
+ if unknown_bounds:
252
+ raise PantryPlanError(f"target {name!r} has unknown bounds")
253
+ minimum = (
254
+ _decimal(raw_bounds["min"], label=f"targets.{name}.min")
255
+ if "min" in raw_bounds
256
+ else None
257
+ )
258
+ maximum = (
259
+ _decimal(raw_bounds["max"], label=f"targets.{name}.max")
260
+ if "max" in raw_bounds
261
+ else None
262
+ )
263
+ if minimum is None and maximum is None:
264
+ raise PantryPlanError(f"target {name!r} has no bound")
265
+ if minimum is not None and maximum is not None and minimum > maximum:
266
+ raise PantryPlanError(f"target {name!r} has min greater than max")
267
+ if name != "mass_g":
268
+ for ingredient in ingredients:
269
+ if name not in ingredient.attributes:
270
+ raise PantryPlanError(
271
+ f"ingredient {ingredient.ingredient_id!r} lacks target "
272
+ f"attribute {name!r}"
273
+ )
274
+ targets.append(PantryTarget(name, minimum, maximum))
275
+
276
+ return PantryPlanSpec(
277
+ ingredients=tuple(ingredients),
278
+ targets=tuple(sorted(targets, key=lambda target: target.attribute)),
279
+ min_ingredients=min_ingredients,
280
+ max_ingredients=max_ingredients,
281
+ forbidden_tags=forbidden_tags,
282
+ certified_mode_count=certified_mode_count,
283
+ )
284
+
285
+
286
+ def parse_pantry_plan_candidate(candidate: str) -> tuple[tuple[str, int], ...]:
287
+ """Parse ``ingredient_id=grams`` entries without executing model text."""
288
+
289
+ text = str(candidate).strip()
290
+ if not text or len(text) > _MAX_CANDIDATE_CHARS:
291
+ raise PantryPlanError("candidate is empty or too long")
292
+ if text.startswith("{") and text.endswith("}"):
293
+ text = text[1:-1].strip()
294
+ pieces = [piece.strip() for piece in re.split(r"[;,]", text)]
295
+ if not pieces or any(not piece for piece in pieces):
296
+ raise PantryPlanError("candidate contains an empty allocation")
297
+
298
+ allocations: dict[str, int] = {}
299
+ for piece in pieces:
300
+ match = re.fullmatch(r"([a-z][a-z0-9_]{0,31})\s*=\s*([0-9]+)", piece)
301
+ if match is None:
302
+ raise PantryPlanError(f"invalid allocation {piece!r}")
303
+ ingredient_id, raw_grams = match.groups()
304
+ if ingredient_id in allocations:
305
+ raise PantryPlanError(f"duplicate allocation for {ingredient_id!r}")
306
+ grams = int(raw_grams)
307
+ if not 1 <= grams <= 10_000:
308
+ raise PantryPlanError(f"allocation for {ingredient_id!r} is out of range")
309
+ allocations[ingredient_id] = grams
310
+ return tuple(sorted(allocations.items()))
311
+
312
+
313
+ def validate_pantry_plan(
314
+ candidate: str,
315
+ spec: Mapping[str, Any],
316
+ ) -> PantryPlanValidation | None:
317
+ """Return the exact verified formulation mode, or ``None`` on rejection."""
318
+
319
+ try:
320
+ parsed_spec = parse_pantry_plan_spec(spec)
321
+ allocations = parse_pantry_plan_candidate(candidate)
322
+ if not (
323
+ parsed_spec.min_ingredients
324
+ <= len(allocations)
325
+ <= parsed_spec.max_ingredients
326
+ ):
327
+ raise PantryPlanError("candidate uses the wrong number of ingredients")
328
+
329
+ by_id = parsed_spec.ingredient_by_id
330
+ totals: dict[str, Decimal] = {"mass_g": Decimal(0)}
331
+ for ingredient_id, grams in allocations:
332
+ ingredient = by_id.get(ingredient_id)
333
+ if ingredient is None:
334
+ raise PantryPlanError(f"unknown ingredient {ingredient_id!r}")
335
+ if ingredient.tags & parsed_spec.forbidden_tags:
336
+ raise PantryPlanError(f"ingredient {ingredient_id!r} is forbidden")
337
+ if (
338
+ grams < ingredient.min_if_used_g
339
+ or grams > ingredient.available_g
340
+ or grams % ingredient.step_g
341
+ ):
342
+ raise PantryPlanError(
343
+ f"allocation for {ingredient_id!r} violates pantry bounds"
344
+ )
345
+ grams_decimal = Decimal(grams)
346
+ totals["mass_g"] += grams_decimal
347
+ for name, per_100g in ingredient.attributes_per_100g:
348
+ totals[name] = (
349
+ totals.get(name, Decimal(0))
350
+ + per_100g * grams_decimal / Decimal(100)
351
+ )
352
+
353
+ for target in parsed_spec.targets:
354
+ value = totals.get(target.attribute, Decimal(0))
355
+ if target.minimum is not None and value < target.minimum:
356
+ raise PantryPlanError(f"{target.attribute} is below its minimum")
357
+ if target.maximum is not None and value > target.maximum:
358
+ raise PantryPlanError(f"{target.attribute} exceeds its maximum")
359
+
360
+ support = tuple(ingredient_id for ingredient_id, _grams in allocations)
361
+ canonical_key = f"{PANTRY_PLAN_VERIFIER}:{PANTRY_PLAN_VERSION}:" + "+".join(
362
+ support
363
+ )
364
+ return PantryPlanValidation(
365
+ canonical_key=canonical_key,
366
+ allocations_g=allocations,
367
+ totals=tuple(sorted(totals.items())),
368
+ )
369
+ except (PantryPlanError, ArithmeticError, ValueError):
370
+ return None
code/oat_drgrpo/pantry_support_action.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Development adapter for support-first PantryPlan actions.
2
+
3
+ The language policy chooses only the ingredient support. A deterministic,
4
+ trusted environment transition searches the registered quantity grid for the
5
+ lexicographically first feasible allocation on exactly that support. It never
6
+ consults the certified support catalogue or a reference allocation.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from itertools import product
12
+ import re
13
+ from typing import Any, Mapping
14
+
15
+ from .pantry_plan import (
16
+ PantryPlanError,
17
+ PantryPlanValidation,
18
+ parse_pantry_plan_spec,
19
+ validate_pantry_plan,
20
+ )
21
+
22
+
23
+ PANTRY_SUPPORT_ACTION_VERSION = "pantry-support-action-dev-v1"
24
+ PANTRY_SUPPORT_MASK_TASK = "pantry_support_mask"
25
+ PANTRY_SUPPORT_MASK_WIDTH = 6
26
+ PANTRY_SUPPORT_MASK_INVALID = "__INVALID_PANTRY_SUPPORT_MASK__"
27
+ _MAX_SUPPORT_CHARS = 256
28
+
29
+
30
+ def parse_pantry_support_action(
31
+ candidate: str,
32
+ spec: Mapping[str, Any],
33
+ ) -> tuple[str, ...]:
34
+ """Parse a support-only action against the prompt-local ingredient IDs."""
35
+
36
+ parsed_spec = parse_pantry_plan_spec(spec)
37
+ text = str(candidate).strip()
38
+ if not text or len(text) > _MAX_SUPPORT_CHARS:
39
+ raise PantryPlanError("support action is empty or too long")
40
+ if text.startswith("{") and text.endswith("}"):
41
+ text = text[1:-1].strip()
42
+ text = re.sub(r"^(?:support|ingredients?)\s*[:=]\s*", "", text, flags=re.I)
43
+ pieces = tuple(
44
+ piece for piece in re.split(r"[\s,;+]+", text.lower()) if piece
45
+ )
46
+ if not parsed_spec.min_ingredients <= len(pieces) <= parsed_spec.max_ingredients:
47
+ raise PantryPlanError("support action uses the wrong number of ingredients")
48
+ if len(set(pieces)) != len(pieces):
49
+ raise PantryPlanError("support action contains a duplicate ingredient")
50
+ allowed = parsed_spec.ingredient_by_id
51
+ unknown = [piece for piece in pieces if piece not in allowed]
52
+ if unknown:
53
+ raise PantryPlanError(f"unknown ingredient {unknown[0]!r}")
54
+ return tuple(sorted(pieces))
55
+
56
+
57
+ def project_pantry_support(
58
+ support: tuple[str, ...],
59
+ spec: Mapping[str, Any],
60
+ ) -> PantryPlanValidation | None:
61
+ """Search only the selected support's registered quantity lattice."""
62
+
63
+ parsed_spec = parse_pantry_plan_spec(spec)
64
+ by_id = parsed_spec.ingredient_by_id
65
+ if (
66
+ not parsed_spec.min_ingredients <= len(support) <= parsed_spec.max_ingredients
67
+ or len(set(support)) != len(support)
68
+ or any(ingredient_id not in by_id for ingredient_id in support)
69
+ ):
70
+ return None
71
+ grids = []
72
+ for ingredient_id in support:
73
+ ingredient = by_id[ingredient_id]
74
+ grids.append(
75
+ range(
76
+ ingredient.min_if_used_g,
77
+ ingredient.available_g + 1,
78
+ ingredient.step_g,
79
+ )
80
+ )
81
+ for quantities in product(*grids):
82
+ allocation = ";".join(
83
+ f"{ingredient_id}={grams}"
84
+ for ingredient_id, grams in zip(support, quantities)
85
+ )
86
+ validation = validate_pantry_plan(allocation, spec)
87
+ if validation is not None:
88
+ return validation
89
+ return None
90
+
91
+
92
+ def validate_pantry_support_action(
93
+ candidate: str,
94
+ spec: Mapping[str, Any],
95
+ ) -> PantryPlanValidation | None:
96
+ """Return a verifier-bound mode after deterministic quantity projection."""
97
+
98
+ try:
99
+ support = parse_pantry_support_action(candidate, spec)
100
+ except (PantryPlanError, ValueError):
101
+ return None
102
+ return project_pantry_support(support, spec)
103
+
104
+ def pantry_support_from_mask(
105
+ mask: str,
106
+ spec: Mapping[str, Any],
107
+ ) -> tuple[str, ...] | None:
108
+ """Decode one fixed-width inclusion mask using the public pantry row order."""
109
+
110
+ parsed_spec = parse_pantry_plan_spec(spec)
111
+ text = str(mask).strip()
112
+ if (
113
+ len(parsed_spec.ingredients) != PANTRY_SUPPORT_MASK_WIDTH
114
+ or len(text) != PANTRY_SUPPORT_MASK_WIDTH
115
+ or any(bit not in {"0", "1"} for bit in text)
116
+ ):
117
+ return None
118
+ support = tuple(
119
+ ingredient.ingredient_id
120
+ for bit, ingredient in zip(text, parsed_spec.ingredients)
121
+ if bit == "1"
122
+ )
123
+ if not parsed_spec.min_ingredients <= len(support) <= parsed_spec.max_ingredients:
124
+ return None
125
+ return tuple(sorted(support))
126
+
127
+
128
+ def pantry_support_mask_from_allocation(
129
+ allocation: str,
130
+ spec: Mapping[str, Any],
131
+ ) -> str:
132
+ """Project a verifier-valid allocation onto its public-row support mask.
133
+
134
+ This is the inverse representation adapter needed when an offline replay
135
+ pool stores PantryPlan witnesses but the policy acts on the registered
136
+ support-mask surface. It validates the original witness first and changes
137
+ only its serialization; no replay row is dropped or deduplicated.
138
+ """
139
+
140
+ parsed_spec = parse_pantry_plan_spec(spec)
141
+ if len(parsed_spec.ingredients) != PANTRY_SUPPORT_MASK_WIDTH:
142
+ raise PantryPlanError(
143
+ "Pantry support masks require exactly "
144
+ f"{PANTRY_SUPPORT_MASK_WIDTH} public ingredient rows"
145
+ )
146
+ validation = validate_pantry_plan(allocation, spec)
147
+ if validation is None:
148
+ raise PantryPlanError("replayed Pantry allocation fails its verifier")
149
+ selected = {ingredient_id for ingredient_id, _grams in validation.allocations_g}
150
+ mask = "".join(
151
+ "1" if ingredient.ingredient_id in selected else "0"
152
+ for ingredient in parsed_spec.ingredients
153
+ )
154
+ decoded_support = pantry_support_from_mask(mask, spec)
155
+ if decoded_support != tuple(sorted(selected)):
156
+ raise PantryPlanError("Pantry allocation cannot be represented by its mask")
157
+ return mask
158
+
159
+
160
+ def decode_pantry_support_mask(
161
+ mask: str,
162
+ spec: Mapping[str, Any],
163
+ ) -> str:
164
+ """Project a six-bit policy action into the exact allocation grader surface.
165
+
166
+ Every bit string is a syntactically valid fixed-horizon policy action.
167
+ Masks with an invalid support width or no feasible quantity assignment map
168
+ to a fail-closed sentinel that the ordinary PantryPlan verifier rejects.
169
+ """
170
+
171
+ support = pantry_support_from_mask(mask, spec)
172
+ if support is None:
173
+ return PANTRY_SUPPORT_MASK_INVALID
174
+ validation = project_pantry_support(support, spec)
175
+ if validation is None:
176
+ return PANTRY_SUPPORT_MASK_INVALID
177
+ return ";".join(
178
+ f"{ingredient_id}={grams}"
179
+ for ingredient_id, grams in validation.allocations_g
180
+ )
code/oat_drgrpo/python_modebench.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Restricted executable Python tasks for ModeBench.
2
+
3
+ The model writes one pure ``lambda n: ...`` expression. A separate worker
4
+ process evaluates the function on a frozen prompt-local test suite. A response
5
+ is correct when every returned integer is a proper divisor of its input. The
6
+ semantic outcome is the complete vector returned by that same execution.
7
+
8
+ This module owns the syntax and task contract. The actual call to model code
9
+ is made only by :mod:`oat_drgrpo.python_modebench_worker`.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import ast
15
+ from dataclasses import dataclass
16
+ from math import prod
17
+ from typing import Any, Mapping
18
+
19
+
20
+ PYTHON_FACTOR_VERIFIER = "python_factor_function"
21
+ PYTHON_FACTOR_VERSION = "factor-v1"
22
+ _MAX_CANDIDATE_CHARS = 240
23
+ _MAX_AST_NODES = 64
24
+ _MAX_CASES = 8
25
+
26
+ _ALLOWED_NODE_TYPES = (
27
+ ast.Expression,
28
+ ast.Lambda,
29
+ ast.arguments,
30
+ ast.arg,
31
+ ast.IfExp,
32
+ ast.BoolOp,
33
+ ast.And,
34
+ ast.Or,
35
+ ast.Compare,
36
+ ast.Eq,
37
+ ast.NotEq,
38
+ ast.Lt,
39
+ ast.LtE,
40
+ ast.Gt,
41
+ ast.GtE,
42
+ ast.BinOp,
43
+ ast.Add,
44
+ ast.Sub,
45
+ ast.Mult,
46
+ ast.FloorDiv,
47
+ ast.Mod,
48
+ ast.UnaryOp,
49
+ ast.UAdd,
50
+ ast.USub,
51
+ ast.Not,
52
+ ast.Name,
53
+ ast.Load,
54
+ ast.Constant,
55
+ )
56
+
57
+
58
+ class PythonModeBenchError(ValueError):
59
+ """Raised for a malformed task or candidate program."""
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class PythonFactorValidation:
64
+ """Result of one successful external execution."""
65
+
66
+ canonical_key: str
67
+ outputs: tuple[int, ...]
68
+
69
+
70
+ def _canonical_python_route_ast(node: ast.AST) -> str:
71
+ """Return a literal-abstracted strategy skeleton for restricted Python."""
72
+
73
+ if isinstance(node, ast.Expression):
74
+ return _canonical_python_route_ast(node.body)
75
+ if isinstance(node, ast.Lambda):
76
+ return f"lambda({_canonical_python_route_ast(node.body)})"
77
+ if isinstance(node, ast.Name):
78
+ return "input"
79
+ if isinstance(node, ast.Constant):
80
+ return "literal"
81
+ if isinstance(node, ast.UnaryOp):
82
+ return (
83
+ f"{type(node.op).__name__.lower()}"
84
+ f"({_canonical_python_route_ast(node.operand)})"
85
+ )
86
+ if isinstance(node, ast.BinOp):
87
+ op = type(node.op).__name__.lower()
88
+ children = [
89
+ _canonical_python_route_ast(node.left),
90
+ _canonical_python_route_ast(node.right),
91
+ ]
92
+ if isinstance(node.op, (ast.Add, ast.Mult)):
93
+ children.sort()
94
+ return f"{op}({','.join(children)})"
95
+ if isinstance(node, ast.Compare):
96
+ return "compare(" + ",".join(
97
+ [
98
+ _canonical_python_route_ast(node.left),
99
+ *(type(op).__name__.lower() for op in node.ops),
100
+ *(
101
+ _canonical_python_route_ast(comparator)
102
+ for comparator in node.comparators
103
+ ),
104
+ ]
105
+ ) + ")"
106
+ if isinstance(node, ast.BoolOp):
107
+ values = [_canonical_python_route_ast(value) for value in node.values]
108
+ values.sort()
109
+ return f"{type(node.op).__name__.lower()}({','.join(values)})"
110
+ if isinstance(node, ast.IfExp):
111
+ return (
112
+ f"if({_canonical_python_route_ast(node.test)},"
113
+ f"{_canonical_python_route_ast(node.body)},"
114
+ f"{_canonical_python_route_ast(node.orelse)})"
115
+ )
116
+ raise PythonModeBenchError(
117
+ f"cannot canonicalize Python route node {type(node).__name__}"
118
+ )
119
+
120
+
121
+ def python_factor_route_signature(candidate: str) -> str:
122
+ """Return code-structure identity after the restricted parser accepts it."""
123
+
124
+ parsed = parse_python_factor_candidate(candidate)
125
+ return "python-factor-route:v1:" + _canonical_python_route_ast(parsed)
126
+
127
+
128
+ def proper_divisors(value: int) -> tuple[int, ...]:
129
+ """Return all positive proper divisors other than one."""
130
+
131
+ value = int(value)
132
+ if value < 4:
133
+ return ()
134
+ return tuple(divisor for divisor in range(2, value) if value % divisor == 0)
135
+
136
+
137
+ def python_factor_mode_count(cases: tuple[int, ...] | list[int]) -> int:
138
+ """Return the exact number of valid behavior vectors for a task."""
139
+
140
+ divisor_sets = [proper_divisors(value) for value in cases]
141
+ if any(not divisors for divisors in divisor_sets):
142
+ return 0
143
+ return prod(len(divisors) for divisors in divisor_sets)
144
+
145
+
146
+ def parse_python_factor_spec(spec: Mapping[str, Any]) -> tuple[int, ...]:
147
+ """Validate a trusted dataset specification and return its tool inputs."""
148
+
149
+ if spec.get("verifier") != PYTHON_FACTOR_VERIFIER:
150
+ raise PythonModeBenchError("wrong Python ModeBench verifier")
151
+ if spec.get("python_version") != PYTHON_FACTOR_VERSION:
152
+ raise PythonModeBenchError("unsupported Python ModeBench version")
153
+ raw_cases = spec.get("cases")
154
+ if not isinstance(raw_cases, list) or not 2 <= len(raw_cases) <= _MAX_CASES:
155
+ raise PythonModeBenchError("cases must contain between two and eight inputs")
156
+ if any(isinstance(value, bool) or not isinstance(value, int) for value in raw_cases):
157
+ raise PythonModeBenchError("case inputs must be integers")
158
+ cases = tuple(int(value) for value in raw_cases)
159
+ if len(set(cases)) != len(cases):
160
+ raise PythonModeBenchError("case inputs must be unique")
161
+ if any(value < 4 or value > 1_000 for value in cases):
162
+ raise PythonModeBenchError("case inputs are outside the bounded domain")
163
+ if python_factor_mode_count(cases) < 2:
164
+ raise PythonModeBenchError("task does not have multiple valid modes")
165
+ return cases
166
+
167
+
168
+ def parse_python_factor_candidate(candidate: str) -> ast.Expression:
169
+ """Parse the bounded, call-free lambda language."""
170
+
171
+ text = str(candidate).strip()
172
+ if not text or len(text) > _MAX_CANDIDATE_CHARS:
173
+ raise PythonModeBenchError("candidate is empty or too long")
174
+ try:
175
+ parsed = ast.parse(text, mode="eval")
176
+ except (SyntaxError, ValueError) as error:
177
+ raise PythonModeBenchError("candidate is not one Python expression") from error
178
+ if not isinstance(parsed.body, ast.Lambda):
179
+ raise PythonModeBenchError("candidate must be a lambda")
180
+ arguments = parsed.body.args
181
+ if (
182
+ len(arguments.args) != 1
183
+ or arguments.args[0].arg != "n"
184
+ or arguments.posonlyargs
185
+ or arguments.kwonlyargs
186
+ or arguments.vararg is not None
187
+ or arguments.kwarg is not None
188
+ or arguments.defaults
189
+ or arguments.kw_defaults
190
+ ):
191
+ raise PythonModeBenchError("lambda must have the exact signature lambda n")
192
+ nodes = list(ast.walk(parsed))
193
+ if len(nodes) > _MAX_AST_NODES:
194
+ raise PythonModeBenchError("candidate AST is too large")
195
+ for node in nodes:
196
+ if not isinstance(node, _ALLOWED_NODE_TYPES):
197
+ raise PythonModeBenchError(
198
+ f"unsupported Python syntax: {type(node).__name__}"
199
+ )
200
+ if isinstance(node, ast.Name) and node.id != "n":
201
+ raise PythonModeBenchError(f"unknown name: {node.id}")
202
+ if isinstance(node, ast.Constant):
203
+ if isinstance(node.value, bool) or not isinstance(node.value, int):
204
+ raise PythonModeBenchError("only integer literals are allowed")
205
+ if abs(int(node.value)) > 10_000:
206
+ raise PythonModeBenchError("integer literal is too large")
207
+ return parsed
208
+
209
+
210
+ def execute_python_factor_candidate(
211
+ candidate: str,
212
+ spec: Mapping[str, Any],
213
+ ) -> PythonFactorValidation:
214
+ """Execute one already restricted candidate.
215
+
216
+ This entry point is worker-only. Callers in the trainer and evaluator use
217
+ ``validate_python_factor_function_external`` so model code never executes
218
+ in their process.
219
+ """
220
+
221
+ cases = parse_python_factor_spec(spec)
222
+ parsed = parse_python_factor_candidate(candidate)
223
+ code = compile(parsed, "<modebench-python-factor>", "eval")
224
+ function = eval(code, {"__builtins__": {}}, {}) # noqa: S307
225
+ outputs: list[int] = []
226
+ for value in cases:
227
+ output = function(value)
228
+ if isinstance(output, bool) or not isinstance(output, int):
229
+ raise PythonModeBenchError("function output must be an integer")
230
+ output = int(output)
231
+ if output <= 1 or output >= value or value % output != 0:
232
+ raise PythonModeBenchError(
233
+ f"function returned {output}, not a proper divisor of {value}"
234
+ )
235
+ outputs.append(output)
236
+ output_tuple = tuple(outputs)
237
+ key = "python_factor:" + ",".join(str(value) for value in output_tuple)
238
+ return PythonFactorValidation(canonical_key=key, outputs=output_tuple)
code/oat_drgrpo/python_modebench_process.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Killable external execution boundary for ModeBench Python functions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import select
9
+ import subprocess
10
+ import sys
11
+ import threading
12
+ from typing import Any, Mapping
13
+
14
+ from .python_modebench import PythonFactorValidation
15
+
16
+
17
+ class PythonFactorVerifierProcess:
18
+ """Execute restricted candidate functions outside the trainer process."""
19
+
20
+ def __init__(self, *, timeout_seconds: float = 1.0) -> None:
21
+ if timeout_seconds <= 0:
22
+ raise ValueError("timeout_seconds must be positive")
23
+ self.timeout_seconds = float(timeout_seconds)
24
+ self._process: subprocess.Popen[str] | None = None
25
+ self._owner_pid = os.getpid()
26
+ self._lock = threading.Lock()
27
+
28
+ def _start(self) -> subprocess.Popen[str]:
29
+ if self._owner_pid != os.getpid():
30
+ self._process = None
31
+ self._owner_pid = os.getpid()
32
+ process = self._process
33
+ if process is not None and process.poll() is None:
34
+ return process
35
+ worker_env = os.environ.copy()
36
+ source_root = str(Path(__file__).resolve().parents[1])
37
+ inherited_pythonpath = worker_env.get("PYTHONPATH")
38
+ worker_env["PYTHONPATH"] = (
39
+ source_root
40
+ if not inherited_pythonpath
41
+ else source_root + os.pathsep + inherited_pythonpath
42
+ )
43
+ isolated_entrypoint = (
44
+ "import runpy,sys;"
45
+ f"sys.path.insert(0,{source_root!r});"
46
+ "runpy.run_module('oat_drgrpo.python_modebench_worker',run_name='__main__')"
47
+ )
48
+ self._process = subprocess.Popen(
49
+ [sys.executable, "-I", "-c", isolated_entrypoint],
50
+ stdin=subprocess.PIPE,
51
+ stdout=subprocess.PIPE,
52
+ stderr=None,
53
+ text=True,
54
+ encoding="utf-8",
55
+ bufsize=1,
56
+ start_new_session=True,
57
+ env=worker_env,
58
+ )
59
+ return self._process
60
+
61
+ def _stop(self) -> None:
62
+ process, self._process = self._process, None
63
+ if process is None:
64
+ return
65
+ if process.poll() is None:
66
+ process.terminate()
67
+ try:
68
+ process.wait(timeout=1)
69
+ except subprocess.TimeoutExpired:
70
+ process.kill()
71
+ process.wait(timeout=1)
72
+ if process.stdin is not None:
73
+ process.stdin.close()
74
+ if process.stdout is not None:
75
+ process.stdout.close()
76
+
77
+ def close(self) -> None:
78
+ with self._lock:
79
+ self._stop()
80
+
81
+ def validate(
82
+ self,
83
+ candidate: str,
84
+ spec: Mapping[str, Any],
85
+ ) -> PythonFactorValidation | None:
86
+ request = json.dumps(
87
+ {"candidate": str(candidate), "spec": dict(spec)},
88
+ allow_nan=False,
89
+ )
90
+ with self._lock:
91
+ for attempt in range(2):
92
+ process = self._start()
93
+ try:
94
+ assert process.stdin is not None and process.stdout is not None
95
+ process.stdin.write(request + "\n")
96
+ process.stdin.flush()
97
+ readable, _, _ = select.select(
98
+ [process.stdout], [], [], self.timeout_seconds
99
+ )
100
+ if not readable:
101
+ self._stop()
102
+ return None
103
+ line = process.stdout.readline()
104
+ if not line:
105
+ raise BrokenPipeError("Python ModeBench worker closed stdout")
106
+ payload = json.loads(line)
107
+ if not payload.get("valid"):
108
+ return None
109
+ return PythonFactorValidation(
110
+ canonical_key=str(payload["canonical_key"]),
111
+ outputs=tuple(int(value) for value in payload["outputs"]),
112
+ )
113
+ except (BrokenPipeError, OSError, ValueError, json.JSONDecodeError):
114
+ self._stop()
115
+ if attempt:
116
+ return None
117
+ return None
118
+
119
+ def __del__(self) -> None:
120
+ try:
121
+ self._stop()
122
+ except Exception:
123
+ pass
124
+
125
+
126
+ _SHARED_VERIFIER = PythonFactorVerifierProcess()
127
+
128
+
129
+ def validate_python_factor_function_external(
130
+ candidate: str,
131
+ spec: Mapping[str, Any],
132
+ ) -> PythonFactorValidation | None:
133
+ """Validate a candidate through the shared external Python worker."""
134
+
135
+ return _SHARED_VERIFIER.validate(candidate, spec)
code/oat_drgrpo/python_modebench_worker.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """JSON-lines worker that executes restricted ModeBench Python functions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import signal
7
+ import sys
8
+
9
+ from .python_modebench import execute_python_factor_candidate
10
+
11
+
12
+ def _timeout(_signum, _frame) -> None:
13
+ raise TimeoutError("Python ModeBench candidate timed out")
14
+
15
+
16
+ def main() -> None:
17
+ signal.signal(signal.SIGALRM, _timeout)
18
+ for line in sys.stdin:
19
+ try:
20
+ request = json.loads(line)
21
+ signal.setitimer(signal.ITIMER_REAL, 0.25)
22
+ validation = execute_python_factor_candidate(
23
+ request["candidate"],
24
+ request["spec"],
25
+ )
26
+ payload = {
27
+ "valid": True,
28
+ "canonical_key": validation.canonical_key,
29
+ "outputs": list(validation.outputs),
30
+ }
31
+ except Exception as error:
32
+ payload = {
33
+ "valid": False,
34
+ "error": type(error).__name__,
35
+ }
36
+ finally:
37
+ signal.setitimer(signal.ITIMER_REAL, 0)
38
+ sys.stdout.write(json.dumps(payload, allow_nan=False) + "\n")
39
+ sys.stdout.flush()
40
+
41
+
42
+ if __name__ == "__main__":
43
+ main()
code/oat_drgrpo/templates.py ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prompt templates and response-token mask helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Sequence
6
+
7
+ import torch
8
+
9
+ # Chat surfaces keep one benchmark contract portable across model families.
10
+ # A surface supplies only the role markers; the system instruction and the user
11
+ # body below are shared verbatim, so a Qwen prompt and its Falcon counterpart
12
+ # differ in nothing but the tokens the base model was instruction-tuned on.
13
+ # The Falcon markers reproduce tiiuae/Falcon3-*-Instruct's published chat
14
+ # template byte for byte (``<|system|>\n...\n<|user|>\n...\n<|assistant|>\n``);
15
+ # unlike Qwen's single-token ``<|im_start|>`` they encode as ordinary tokens,
16
+ # which costs a few prompt tokens but leaves the response surface untouched.
17
+ CHAT_SURFACES: dict[str, tuple[str, str, str]] = {
18
+ "qwen": (
19
+ "<|im_start|>system\n",
20
+ "<|im_end|>\n<|im_start|>user\n",
21
+ "<|im_end|>\n<|im_start|>assistant\n",
22
+ ),
23
+ "falcon": ("<|system|>\n", "\n<|user|>\n", "\n<|assistant|>\n"),
24
+ }
25
+
26
+
27
+ def render_chat_prompt(surface: str, system: str, user: str) -> str:
28
+ """Render one system/user turn onto a named chat surface."""
29
+
30
+ system_marker, user_marker, assistant_marker = CHAT_SURFACES[surface]
31
+ return system_marker + system + user_marker + user + assistant_marker
32
+
33
+
34
+ _MATH_SYSTEM = (
35
+ "Please reason step by step, and put your final answer within \\boxed{}."
36
+ )
37
+
38
+
39
+ def apply_qwen_math_template(question: str) -> str:
40
+ return render_chat_prompt("qwen", _MATH_SYSTEM, question)
41
+
42
+
43
+ def apply_falcon_math_template(question: str) -> str:
44
+ return render_chat_prompt("falcon", _MATH_SYSTEM, question)
45
+
46
+
47
+ def apply_qwen_math_route_json_v1_template(question: str) -> str:
48
+ """Reproduce the frozen JSON-v1 Gate 1 prompt exactly."""
49
+
50
+ return (
51
+ "<|im_start|>system\n"
52
+ "Solve the problem step by step and put the final answer within "
53
+ "\\boxed{}. After the boxed answer, also emit exactly one compact "
54
+ "<route>JSON</route> block when the computation fits this schema: "
55
+ '{"version":"math-route-v1","steps":[...],"final":"sN"}. '
56
+ "Step IDs are contiguous s1,s2,... . A source step is "
57
+ '{"id":"s1","op":"source","value":"a number copied from the problem"}. '
58
+ "Other steps contain only id, op, and earlier args; never write a "
59
+ "result field. Allowed ops are neg, abs, square, cube, sqrt, factorial, "
60
+ "percent, add, mul, sub, div, pow, mod, choose, permute, gcd, lcm, min, "
61
+ "max, and average. Every step must contribute to final. If this exact "
62
+ "numeric trace language cannot express the solution, omit the route "
63
+ "block but still give the boxed answer."
64
+ "<|im_end|>\n<|im_start|>user\n"
65
+ + question
66
+ + "<|im_end|>\n<|im_start|>assistant\n"
67
+ )
68
+
69
+
70
+ _MATH_ROUTE_SYSTEM = (
71
+ "Solve the problem step by step and put the final answer within "
72
+ "\\boxed{}. When the answer is computed from numbers in the problem, "
73
+ "end with exactly one compact reverse-Polish program between "
74
+ "<route> and </route>. Start the program with v2. Write copied input "
75
+ "numbers and operation words separated only by spaces. For example, "
76
+ "'<route>v2 2 5 mul 1 sub square 1 add</route>' computes "
77
+ "(2*5-1)^2+1. Unary operations are neg abs square cube sqrt factorial "
78
+ "percent. Binary operations are add mul sub div pow mod choose permute "
79
+ "gcd lcm min max average. A binary operation consumes the previous two "
80
+ "values in left-to-right order. Copy every numeric input from the "
81
+ "problem; never put a computed result, JSON, equations, labels, or "
82
+ "prose inside <route>. If this numeric stack language cannot express "
83
+ "the solution, omit <route> but still give the boxed answer."
84
+ )
85
+
86
+
87
+ def apply_qwen_math_route_template(question: str) -> str:
88
+ """Request a boxed answer plus a compact executable numeric route."""
89
+
90
+ return render_chat_prompt("qwen", _MATH_ROUTE_SYSTEM, question)
91
+
92
+
93
+ def apply_falcon_math_route_template(question: str) -> str:
94
+ """Falcon-surface twin of :func:`apply_qwen_math_route_template`."""
95
+
96
+ return render_chat_prompt("falcon", _MATH_ROUTE_SYSTEM, question)
97
+
98
+
99
+ _BOXED_SYSTEM = "Return only the final answer inside \\boxed{}. Do not explain."
100
+
101
+
102
+ def apply_qwen_boxed_template(question: str) -> str:
103
+ return render_chat_prompt("qwen", _BOXED_SYSTEM, question)
104
+
105
+
106
+ def apply_falcon_boxed_template(question: str) -> str:
107
+ return render_chat_prompt("falcon", _BOXED_SYSTEM, question)
108
+
109
+
110
+ _LEVEL2_HYBRID_SYSTEMS = {
111
+ "countdown": (
112
+ "Solve the executable constraint problem carefully. You may reason briefly, "
113
+ "but end with exactly one final answer inside \\boxed{}. Systematically combine "
114
+ "every supplied number exactly once using +, -, *, /, and parentheses. Check "
115
+ "the exact target before answering. Output exactly the boxed expression."
116
+ ),
117
+ "python_factors": (
118
+ "Solve the executable constraint problem carefully. You may reason briefly, "
119
+ "but end with exactly one final answer inside \\boxed{}. Construct one allowed "
120
+ "lambda expression. Test small divisors with nested conditional expressions, "
121
+ "for example 2 if n % 2 == 0 else 3 if n % 3 == 0 else 5, but adapt the "
122
+ "tests to every listed case. You may instead dispatch on each listed value. "
123
+ "Output exactly the boxed lambda."
124
+ ),
125
+ "mathir": (
126
+ "Solve the executable constraint problem carefully. You may reason briefly, "
127
+ "but end with exactly one final answer inside \\boxed{}. Use algebraic isolation: "
128
+ "move the right-side x term left, remove the left constant, then divide by the "
129
+ "combined coefficient. Match those operations to the shuffled menu IDs."
130
+ ),
131
+ "pantry": (
132
+ "Solve the executable constraint problem carefully. You may reason briefly, "
133
+ "but end with exactly one final answer inside \\boxed{}. Prefer allowed "
134
+ "high-energy/protein, very-low-sodium ingredients, especially seeds or oats. "
135
+ "Choose stepped amounts, check every bound, and output 2 to 4 "
136
+ "ingredient_id=grams pairs."
137
+ ),
138
+ }
139
+
140
+
141
+ def apply_qwen_level2_countdown_template(question: str) -> str:
142
+ return render_chat_prompt("qwen", _LEVEL2_HYBRID_SYSTEMS["countdown"], question)
143
+
144
+
145
+ def apply_qwen_level2_python_factors_template(question: str) -> str:
146
+ return render_chat_prompt("qwen", _LEVEL2_HYBRID_SYSTEMS["python_factors"], question)
147
+
148
+
149
+ def apply_qwen_level2_mathir_template(question: str) -> str:
150
+ return render_chat_prompt("qwen", _LEVEL2_HYBRID_SYSTEMS["mathir"], question)
151
+
152
+
153
+ def apply_qwen_level2_pantry_template(question: str) -> str:
154
+ return render_chat_prompt("qwen", _LEVEL2_HYBRID_SYSTEMS["pantry"], question)
155
+
156
+
157
+ _GRAPH_DIGITS_SYSTEM = (
158
+ "Return only the requested bare sequence of digits. Do not explain, "
159
+ "add punctuation, or use LaTeX."
160
+ )
161
+
162
+
163
+ def _graph_digits_user(question: str, template_name: str) -> str:
164
+ boxed_suffix = "inside \\boxed{}."
165
+ if question.count(boxed_suffix) != 1 or not question.endswith(boxed_suffix):
166
+ raise ValueError(
167
+ f"{template_name} requires a graph prompt ending in a boxed answer"
168
+ )
169
+ return (
170
+ question[: -len(boxed_suffix)]
171
+ + "as one bare digit string with no spaces, punctuation, or other text."
172
+ )
173
+
174
+
175
+ def apply_qwen_graph_digits_template(question: str) -> str:
176
+ """Request the benchmark's canonical bare graph-color action vector."""
177
+
178
+ return render_chat_prompt(
179
+ "qwen",
180
+ _GRAPH_DIGITS_SYSTEM,
181
+ _graph_digits_user(question, "qwen_graph_digits"),
182
+ )
183
+
184
+
185
+ def apply_falcon_graph_digits_template(question: str) -> str:
186
+ """Falcon-surface twin of :func:`apply_qwen_graph_digits_template`."""
187
+
188
+ return render_chat_prompt(
189
+ "falcon",
190
+ _GRAPH_DIGITS_SYSTEM,
191
+ _graph_digits_user(question, "falcon_graph_digits"),
192
+ )
193
+
194
+
195
+ _COUNTDOWN_DIGITS_SYSTEM = (
196
+ "Return only three digits and no other text. The given numbers are "
197
+ "n1,n2,n3 in dataset order. Digit 2 selects singleton s: 1=n1, "
198
+ "2=n2, 3=n3; a,b are the other two numbers in their original order. "
199
+ "Digit 3 makes pair: 1=a+b, 2=a*b, 3=a-b, 4=b-a, 5=a/b, 6=b/a. "
200
+ "Digit 1 combines pair and s: 1=pair+s, 2=pair*s, 3=pair-s, "
201
+ "4=s-pair, 5=pair/s, 6=s/pair."
202
+ )
203
+
204
+
205
+ def _countdown_digits_user(question: str, template_name: str) -> str:
206
+ boxed_suffix = "the expression inside \\boxed{}."
207
+ if question.count(boxed_suffix) != 1 or not question.endswith(boxed_suffix):
208
+ raise ValueError(
209
+ f"{template_name} requires an easy3 Countdown prompt ending "
210
+ "in the boxed-expression instruction"
211
+ )
212
+ return (
213
+ question[: -len(boxed_suffix)]
214
+ + "a three-digit canonical action code using the scheme above."
215
+ )
216
+
217
+
218
+ def apply_qwen_countdown_digits_template(question: str) -> str:
219
+ """Request the audited three-digit Countdown expression code."""
220
+
221
+ return render_chat_prompt(
222
+ "qwen",
223
+ _COUNTDOWN_DIGITS_SYSTEM,
224
+ _countdown_digits_user(question, "qwen_countdown_digits"),
225
+ )
226
+
227
+
228
+ def apply_falcon_countdown_digits_template(question: str) -> str:
229
+ """Falcon-surface twin of :func:`apply_qwen_countdown_digits_template`."""
230
+
231
+ return render_chat_prompt(
232
+ "falcon",
233
+ _COUNTDOWN_DIGITS_SYSTEM,
234
+ _countdown_digits_user(question, "falcon_countdown_digits"),
235
+ )
236
+
237
+
238
+ _PANTRY_SUPPORT_MASK_SYSTEM = (
239
+ "Return only six binary digits and no other text. Each digit maps to "
240
+ "the corresponding Pantry row in printed order. A trusted environment "
241
+ "will choose exact quantities on precisely the selected rows."
242
+ )
243
+
244
+
245
+ def _pantry_support_mask_user(question: str, template_name: str) -> str:
246
+ suffix = (
247
+ "Return only ingredient_id=grams pairs separated by semicolons inside "
248
+ "\\boxed{}. Do not add a recipe name or preparation prose."
249
+ )
250
+ if question.count(suffix) != 1 or not question.endswith(suffix):
251
+ raise ValueError(
252
+ f"{template_name} requires the frozen PantryPlan answer suffix"
253
+ )
254
+ return (
255
+ question[: -len(suffix)]
256
+ + "Choose the ingredient support as a six-bit mask in the exact Pantry "
257
+ "row order. Bit 1 includes that row and bit 0 excludes it."
258
+ )
259
+
260
+
261
+ def apply_qwen_pantry_support_mask_template(question: str) -> str:
262
+ """Request a six-bit ingredient-support action in printed pantry order."""
263
+
264
+ return render_chat_prompt(
265
+ "qwen",
266
+ _PANTRY_SUPPORT_MASK_SYSTEM,
267
+ _pantry_support_mask_user(question, "qwen_pantry_support_mask"),
268
+ )
269
+
270
+
271
+ def apply_falcon_pantry_support_mask_template(question: str) -> str:
272
+ """Falcon-surface twin of :func:`apply_qwen_pantry_support_mask_template`."""
273
+
274
+ return render_chat_prompt(
275
+ "falcon",
276
+ _PANTRY_SUPPORT_MASK_SYSTEM,
277
+ _pantry_support_mask_user(question, "falcon_pantry_support_mask"),
278
+ )
279
+
280
+
281
+ # Every canonical-action task admits exactly one prompt template per chat
282
+ # surface. Binding the task to that closed set keeps a Falcon run from
283
+ # silently training against Qwen role markers the base model never saw.
284
+ CANONICAL_TASK_PROMPT_TEMPLATES: dict[str, frozenset[str]] = {
285
+ "graph_coloring": frozenset({"qwen_graph_digits", "falcon_graph_digits"}),
286
+ "countdown": frozenset(
287
+ {"qwen_countdown_digits", "falcon_countdown_digits"}
288
+ ),
289
+ "pantry_support_mask": frozenset(
290
+ {"qwen_pantry_support_mask", "falcon_pantry_support_mask"}
291
+ ),
292
+ }
293
+
294
+
295
+ def validate_canonical_prompt_materialization(
296
+ prompt_template: str,
297
+ raw_questions: Sequence[str],
298
+ formatted_prompts: Sequence[str],
299
+ ) -> None:
300
+ """Fail closed if dataset mapping did not render the canonical template.
301
+
302
+ The exact string comparison deliberately detects stale Hugging Face map
303
+ caches from older prompt templates as well as dropped or reordered rows.
304
+ Re-applying ``TEMPLATE_FACTORY[prompt_template]`` rather than a hardcoded
305
+ function makes the check family-agnostic: a Falcon-surface run is held to
306
+ its own template and cannot pass on Qwen-rendered rows.
307
+ """
308
+
309
+ if len(raw_questions) != len(formatted_prompts):
310
+ raise RuntimeError(
311
+ "canonical prompt materialization changed the row count: "
312
+ f"raw={len(raw_questions)} formatted={len(formatted_prompts)}"
313
+ )
314
+ apply_template = TEMPLATE_FACTORY[prompt_template]
315
+ for row_index, (question, observed) in enumerate(
316
+ zip(raw_questions, formatted_prompts)
317
+ ):
318
+ if observed != apply_template(question):
319
+ raise RuntimeError(
320
+ f"canonical {prompt_template} prompt materialization mismatch "
321
+ f"at row {row_index}; stale or foreign template cache detected"
322
+ )
323
+
324
+
325
+ def validate_qwen_graph_digits_materialization(
326
+ raw_questions: Sequence[str], formatted_prompts: Sequence[str]
327
+ ) -> None:
328
+ """Fail closed on stale or foreign canonical graph prompt rows."""
329
+
330
+ validate_canonical_prompt_materialization(
331
+ "qwen_graph_digits", raw_questions, formatted_prompts
332
+ )
333
+
334
+
335
+ def validate_qwen_countdown_digits_materialization(
336
+ raw_questions: Sequence[str], formatted_prompts: Sequence[str]
337
+ ) -> None:
338
+ """Fail closed on stale or foreign canonical Countdown prompt rows."""
339
+
340
+ validate_canonical_prompt_materialization(
341
+ "qwen_countdown_digits", raw_questions, formatted_prompts
342
+ )
343
+
344
+
345
+ def validate_qwen_pantry_support_mask_materialization(
346
+ raw_questions: Sequence[str], formatted_prompts: Sequence[str]
347
+ ) -> None:
348
+ """Fail closed on stale or foreign Pantry support-mask prompt rows."""
349
+
350
+ validate_canonical_prompt_materialization(
351
+ "qwen_pantry_support_mask", raw_questions, formatted_prompts
352
+ )
353
+
354
+
355
+ def apply_r1_template(question: str) -> str:
356
+ return (
357
+ "A conversation between User and Assistant. The User asks a question, "
358
+ "and the Assistant solves it. The Assistant first thinks about the "
359
+ "reasoning process in the mind and then provides the User with the "
360
+ "answer. The reasoning process is enclosed within <think> </think> "
361
+ "and answer is enclosed within <answer> </answer> tags, respectively, "
362
+ "i.e., <think> reasoning process here </think> <answer> answer here "
363
+ "</answer>.\nUser: " + question + "\nAssistant: <think>"
364
+ )
365
+
366
+
367
+ def apply_no_template(question: str) -> str:
368
+ return question
369
+
370
+
371
+ TEMPLATE_FACTORY: dict[str, Callable[[str], str]] = {
372
+ "qwen_boxed": apply_qwen_boxed_template,
373
+ "qwen_countdown_digits": apply_qwen_countdown_digits_template,
374
+ "qwen_graph_digits": apply_qwen_graph_digits_template,
375
+ "qwen_pantry_support_mask": apply_qwen_pantry_support_mask_template,
376
+ "qwen_math": apply_qwen_math_template,
377
+ "qwen_math_route": apply_qwen_math_route_template,
378
+ "qwen_level2_countdown": apply_qwen_level2_countdown_template,
379
+ "qwen_level2_python_factors": apply_qwen_level2_python_factors_template,
380
+ "qwen_level2_mathir": apply_qwen_level2_mathir_template,
381
+ "qwen_level2_pantry": apply_qwen_level2_pantry_template,
382
+ "falcon_boxed": apply_falcon_boxed_template,
383
+ "falcon_countdown_digits": apply_falcon_countdown_digits_template,
384
+ "falcon_graph_digits": apply_falcon_graph_digits_template,
385
+ "falcon_pantry_support_mask": apply_falcon_pantry_support_mask_template,
386
+ "falcon_math": apply_falcon_math_template,
387
+ "falcon_math_route": apply_falcon_math_route_template,
388
+ "r1": apply_r1_template,
389
+ "no": apply_no_template,
390
+ }
391
+
392
+ # The Qwen and Falcon families must stay a pure surface swap of one contract.
393
+ PROMPT_TEMPLATE_FAMILY_TWINS: dict[str, str] = {
394
+ "qwen_boxed": "falcon_boxed",
395
+ "qwen_countdown_digits": "falcon_countdown_digits",
396
+ "qwen_graph_digits": "falcon_graph_digits",
397
+ "qwen_pantry_support_mask": "falcon_pantry_support_mask",
398
+ "qwen_math": "falcon_math",
399
+ "qwen_math_route": "falcon_math_route",
400
+ }
401
+
402
+ # A template's *role* is the training contract it encodes; the chat surface is
403
+ # an implementation detail of the base model. Argument validation keys off the
404
+ # role so a Falcon run is held to exactly the Qwen run's contract.
405
+ PROMPT_TEMPLATE_ROLES: dict[str, str] = {
406
+ "qwen_boxed": "boxed",
407
+ "falcon_boxed": "boxed",
408
+ "qwen_countdown_digits": "countdown_digits",
409
+ "falcon_countdown_digits": "countdown_digits",
410
+ "qwen_graph_digits": "graph_digits",
411
+ "falcon_graph_digits": "graph_digits",
412
+ "qwen_pantry_support_mask": "pantry_support_mask",
413
+ "falcon_pantry_support_mask": "pantry_support_mask",
414
+ "qwen_math": "math",
415
+ "falcon_math": "math",
416
+ "qwen_math_route": "math_route",
417
+ "qwen_level2_countdown": "boxed",
418
+ "qwen_level2_python_factors": "boxed",
419
+ "qwen_level2_mathir": "boxed",
420
+ "qwen_level2_pantry": "boxed",
421
+ "falcon_math_route": "math_route",
422
+ "r1": "r1",
423
+ "no": "no",
424
+ }
425
+
426
+ CANONICAL_DIGIT_TEMPLATE_ROLES: frozenset[str] = frozenset(
427
+ {"graph_digits", "countdown_digits", "pantry_support_mask"}
428
+ )
429
+
430
+
431
+ def prompt_template_role(prompt_template: str) -> str:
432
+ """Return the surface-independent training contract a template encodes."""
433
+
434
+ return PROMPT_TEMPLATE_ROLES[prompt_template]
435
+
436
+
437
+ def prompt_template_surface(prompt_template: str) -> str:
438
+ """Return the chat surface family a template renders onto."""
439
+
440
+ for surface in CHAT_SURFACES:
441
+ if prompt_template.startswith(f"{surface}_"):
442
+ return surface
443
+ return "none"
444
+
445
+
446
+ def apply_prompt_template_to_example(
447
+ example: dict,
448
+ *,
449
+ input_key: str,
450
+ prompt_template: str,
451
+ ) -> dict:
452
+ """Apply a configured prompt template to one dataset row."""
453
+
454
+ problem = example[input_key]
455
+ example[input_key] = TEMPLATE_FACTORY[prompt_template](problem)
456
+ return example
457
+
458
+
459
+ def collate_eval_prompt_items(
460
+ item_list: list[dict],
461
+ *,
462
+ prompt_template: str,
463
+ ) -> tuple[list[str], list[str], list[str]]:
464
+ """Collate eval rows into templated prompts, raw problems, and answers."""
465
+
466
+ problems = []
467
+ formatted_problems = []
468
+ answers = []
469
+ for item in item_list:
470
+ problems.append(item["problem"])
471
+ formatted_problems.append(TEMPLATE_FACTORY[prompt_template](item["problem"]))
472
+ answers.append(item["answer"])
473
+ return formatted_problems, problems, answers
474
+
475
+
476
+ def build_response_token_prefix_mask(
477
+ response_masks: torch.Tensor,
478
+ token_counts: torch.Tensor,
479
+ ) -> torch.Tensor:
480
+ """Select the first ``token_counts`` response tokens in each row."""
481
+
482
+ if response_masks.ndim != 2:
483
+ raise ValueError("response_masks must have shape [batch, seq].")
484
+ if token_counts.ndim != 1 or token_counts.shape[0] != response_masks.shape[0]:
485
+ raise ValueError(
486
+ "token_counts must have shape [batch] matching response_masks."
487
+ )
488
+ safe_counts = token_counts.to(
489
+ device=response_masks.device, dtype=torch.int64
490
+ ).clamp(min=0)
491
+ response_positions = response_masks.to(torch.int64).cumsum(dim=1)
492
+ return response_masks.to(torch.bool) & (response_positions <= safe_counts[:, None])
data/level1_countdown/eval.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1da95c1b5997a0c8d804c8bf7b607817b11bb8c7982b3d04bd4c345da7b9c33
3
+ size 8432
data/level1_countdown/train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:00054c212d28ccb103b982cb56de7c381691b91a8ee3af7d984c5e0d57fe74f1
3
+ size 13725
data/level1_graph_coloring/eval.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5c009576b979ac78b9bf73c80790e0048a75f4c27c400569907f096e18a220fb
3
+ size 13112
data/level1_graph_coloring/train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:56266083798c5e86223e7705d3ed2b97d22dc8aba56814402a0c09afc9eddf30
3
+ size 22522
data/level1_graph_coloring_unique_answer/eval.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:759ba48dbcd3fcd4f000449eed1b9e0ea55319dc9677f5150842180ea95893bf
3
+ size 13015
data/level1_mathir/eval.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc0280c144e5c9c54624303cd508612dbbb3a0ef130dfee9a42fb8f9413e9902
3
+ size 20812
data/level1_mathir/train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aac7f11f814eb85769cd16fe8464d886cef3daade22d3d61de50385de9c0662a
3
+ size 37345
data/level1_pantry_plan/dev.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0411b6d32ff14491d14ab5c9edf37a28e8d6fc9ad95ad3afc3f172ba7ec23319
3
+ size 36731
data/level1_pantry_plan/eval.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2807515694c01108c5b8a616eded485a6ffded07fd1f9eb5fa0155cfeb7c2c34
3
+ size 48960
data/level1_pantry_plan/train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eced2be5ca3fb8194703e8f9d7cfd5d29a1ee701369be14cd388d2004b80a8a3
3
+ size 98671
data/level1_python_factors/eval.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:88a3f35b0f3e8e9b8ec4da5151ca7697afc79894c0507d00c258d4154983cea0
3
+ size 16281
data/level1_python_factors/train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:86e4abc2ff3f2efff47c67aaa3263af2fcb226adefcb8fa52e94ff3c15a94948
3
+ size 31553
data/level2_countdown/dev.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f9451228cfd2a49580d3c93b21f58685a477adf2a40d014f480a8f3cc91ef99
3
+ size 8674
data/level2_countdown/eval.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50b90a6197ff1ac83ba0020239bb903bb597c334a27329d3e8703f163cf5d17c
3
+ size 8752
data/level2_countdown/train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bd6a3645bd2e84e90478ddd9f4c4f4f69c28f41a6df7615acb91a9f92374db97
3
+ size 14452
data/level2_graph_coloring/dev.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9d32ed70ff3f002f35dd23b5197e4b06a477b08e4e418bc682675b1e0402ece7
3
+ size 13257
data/level2_graph_coloring/eval.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:63e5f1b8f4b3db950022080c9971cec71c864d369f346f64aa9c303da5b1e33f
3
+ size 13086
data/level2_graph_coloring/train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bd250e096ea785d45e76d0de1c7d872ca8822e95181568cb8ae1b69a6b905fd8
3
+ size 23261
data/level2_mathir/dev.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3dbbb10af2589e467ace24420fe67387fb299ba465a1180163a2b62910dd2fd4
3
+ size 20318