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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
# Copyright 2025 Garena Online Private Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Provides a math answer grading function with high recall.
Based on HF math_verify, verl, open reasoner zero, etc.
"""

import ast
from dataclasses import dataclass
import functools
import json
from multiprocessing import TimeoutError as MultiprocessingTimeoutError
import queue
import re
import signal
import threading
from collections import Counter
from fractions import Fraction
from itertools import islice, zip_longest
from math import isclose
from typing import Any, Optional

import sympy
from latex2sympy2_extended import latex2sympy
from math_verify import ExprExtractionConfig, LatexExtractionConfig, parse, verify
from math_verify import grader as math_verify_grader
from math_verify import parser as math_verify_parser
from math_verify.errors import TimeoutException as MathVerifyTimeout
from math_verify.utils import timeout as math_verify_signal_timeout
from pylatexenc import latex2text
from sympy import N, simplify
from sympy.parsing import sympy_parser
from sympy.parsing.latex import parse_latex
from sympy.parsing.sympy_parser import parse_expr

from .maze_modebench import (
    ANT_MAZE_VERIFIER,
    POINT_MAZE_VERIFIER,
)
from .maze_modebench_process import validate_maze_action_program_external
from .mathir import (
    MATHIR_MENU_VERIFIER,
    MATHIR_VERIFIER,
    validate_mathir_action_menu,
    validate_mathir_algebra,
)
from .math_route import validate_math_route_response
from .pantry_plan import (
    PANTRY_PLAN_VERIFIER,
    validate_pantry_plan,
)
from .python_modebench import (
    PYTHON_FACTOR_VERIFIER,
    python_factor_route_signature,
)
from .python_modebench_process import validate_python_factor_function_external


def _thread_compatible_math_verify_timeout(timeout_seconds: int = 10):
    """Keep math_verify bounded when grading runs in an actor worker thread.

    math_verify's POSIX timeout installs SIGALRM. Python only permits signal
    handler installation on the interpreter's main thread, while OAT grades
    actor responses in a ThreadPool to avoid forking a CUDA/vLLM process. On
    the main thread retain math_verify's native alarm. Else run the protected
    operation in a daemon helper thread and bound the caller's wait.
    """

    seconds = int(timeout_seconds)
    if seconds <= 0:
        raise ValueError("timeout_seconds must be positive")

    def decorator(func):
        signal_wrapped = math_verify_signal_timeout(timeout_seconds=seconds)(func)

        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            if threading.current_thread() is threading.main_thread():
                return signal_wrapped(*args, **kwargs)
            result_queue: queue.Queue[tuple[bool, Any]] = queue.Queue(maxsize=1)

            def run() -> None:
                try:
                    result_queue.put((True, func(*args, **kwargs)))
                except BaseException as error:
                    result_queue.put((False, error))

            worker = threading.Thread(
                target=run,
                name="math-verify-timeout",
                daemon=True,
            )
            worker.start()
            worker.join(seconds)
            if worker.is_alive():
                raise MathVerifyTimeout("Operation timed out!")
            succeeded, value = result_queue.get_nowait()
            if succeeded:
                return value
            raise value

        return wrapper

    return decorator


# parse() and verify() resolve `timeout` from their defining module globals at
# call time. Install the actor-thread-safe policy without altering the external
# math_verify package or its grading semantics.
math_verify_parser.timeout = _thread_compatible_math_verify_timeout
math_verify_grader.timeout = _thread_compatible_math_verify_timeout


_math_verify_sympy_solve_and_compare = math_verify_grader.sympy_solve_and_compare


def _robust_math_verify_sympy_solve_and_compare(
    gold,
    pred,
    float_rounding: int,
    numeric_precision: int,
):
    """Repair math_verify's scalar ``solve(Eq)`` compatibility edge case.

    Some SymPy versions return a list of scalar roots for ``solve(Eq, symbols)``
    while math_verify assumes a list of dictionaries and calls ``.items()``.
    Retry only that failing equality path with ``dict=True`` and preserve the
    package's exact symbol-key and expression-comparison semantics.
    """

    try:
        return _math_verify_sympy_solve_and_compare(
            gold,
            pred,
            float_rounding,
            numeric_precision,
        )
    except AttributeError as error:
        if (
            "items" not in str(error)
            or not isinstance(gold, sympy.Eq)
            or not isinstance(pred, sympy.Eq)
        ):
            raise

    solved_gold = sympy.solve(
        gold,
        gold.free_symbols,
        dict=True,
    )
    solved_pred = sympy.solve(
        pred,
        pred.free_symbols,
        dict=True,
    )
    if not isinstance(solved_gold, list) or not isinstance(solved_pred, list):
        return False
    if len(solved_gold) != len(solved_pred):
        return False

    unmatched = list(solved_pred)
    for gold_solution in solved_gold:
        if not isinstance(gold_solution, dict):
            return False
        match_index = None
        for index, pred_solution in enumerate(unmatched):
            if (
                isinstance(pred_solution, dict)
                and set(gold_solution) == set(pred_solution)
                and all(
                    math_verify_grader.sympy_expr_eq(
                        gold_solution[key],
                        pred_solution[key],
                        float_rounding,
                        numeric_precision,
                    )
                    for key in gold_solution
                )
            ):
                match_index = index
                break
        if match_index is None:
            return False
        unmatched.pop(match_index)
    return not unmatched


math_verify_grader.sympy_solve_and_compare = _robust_math_verify_sympy_solve_and_compare


def collect_threaded_math_rewards(
    pool,
    reward_fn,
    responses,
    references,
    *,
    timeout_seconds: float,
):
    """Grade a response batch concurrently with one bounded wait per result."""

    pending = [
        pool.apply_async(reward_fn, (response, reference))
        for response, reference in zip(responses, references)
    ]
    rewards = []
    infos = []
    for result in pending:
        try:
            info, reward = result.get(timeout=timeout_seconds)
            rewards.append(reward)
            infos.append(info)
        except MultiprocessingTimeoutError:
            rewards.append(0.0)
            infos.append({"formatted": False})
    return rewards, infos


# Dan Hendrycks' code
def mathd_normalize_answer(answer: Optional[str]) -> Optional[str]:
    if answer is None:
        return None
    answer = answer.strip()
    try:
        # Remove enclosing `\text{}`.
        m = re.search(r"^\\text\{(?P<text>.+?)\}$", answer)
        if m is not None:
            answer = m.group("text").strip()
        return _strip_string(answer)
    except Exception:
        return answer


# units mainly from MathQA
unit_texts = [
    "east",
    "degree",
    "mph",
    "kmph",
    "ft",
    "m sqaure",
    " m east",
    "sq m",
    "deg",
    "mile",
    "q .",
    "monkey",
    "prime",
    "ratio",
    "profit of rs",
    "rd",
    "o",
    "gm",
    "p . m",
    "lb",
    "tile",
    "per",
    "dm",
    "lt",
    "gain",
    "ab",
    "way",
    "west",
    "a .",
    "b .",
    "c .",
    "d .",
    "e .",
    "f .",
    "g .",
    "h .",
    "t",
    "a",
    "h",
    "no change",
    "men",
    "soldier",
    "pie",
    "bc",
    "excess",
    "st",
    "inches",
    "noon",
    "percent",
    "by",
    "gal",
    "kmh",
    "c",
    "acre",
    "rise",
    "a . m",
    "th",
    "π r 2",
    "sq",
    "mark",
    "l",
    "toy",
    "coin",
    "sq . m",
    "gallon",
    "° f",
    "profit",
    "minw",
    "yr",
    "women",
    "feet",
    "am",
    "pm",
    "hr",
    "cu cm",
    "square",
    "v â € ™",
    "are",
    "rupee",
    "rounds",
    "cubic",
    "cc",
    "mtr",
    "s",
    "ohm",
    "number",
    "kmph",
    "day",
    "hour",
    "minute",
    "min",
    "second",
    "man",
    "woman",
    "sec",
    "cube",
    "mt",
    "sq inch",
    "mp",
    "∏ cm ³",
    "hectare",
    "more",
    "sec",
    "unit",
    "cu . m",
    "cm 2",
    "rs .",
    "rs",
    "kg",
    "g",
    "month",
    "km",
    "m",
    "cm",
    "mm",
    "apple",
    "liter",
    "loss",
    "yard",
    "pure",
    "year",
    "increase",
    "decrease",
    "d",
    "less",
    "Surface",
    "litre",
    "pi sq m",
    "s .",
    "metre",
    "meter",
    "inch",
]

unit_texts.extend([t + "s" for t in unit_texts])


def _strip_string(string):
    def _fix_fracs(string):
        substrs = string.split("\\frac")
        new_str = substrs[0]
        if len(substrs) > 1:
            substrs = substrs[1:]
            for substr in substrs:
                new_str += "\\frac"
                if substr[0] == "{":
                    new_str += substr
                else:
                    try:
                        assert len(substr) >= 2
                    except Exception:
                        return string
                    a = substr[0]
                    b = substr[1]
                    if b != "{":
                        if len(substr) > 2:
                            post_substr = substr[2:]
                            new_str += "{" + a + "}{" + b + "}" + post_substr
                        else:
                            new_str += "{" + a + "}{" + b + "}"
                    else:
                        if len(substr) > 2:
                            post_substr = substr[2:]
                            new_str += "{" + a + "}" + b + post_substr
                        else:
                            new_str += "{" + a + "}" + b
        string = new_str
        return string

    def _fix_a_slash_b(string):
        if len(string.split("/")) != 2:
            return string
        a = string.split("/")[0]
        b = string.split("/")[1]
        try:
            a = int(a)
            b = int(b)
            assert string == "{}/{}".format(a, b)
            new_string = "\\frac{" + str(a) + "}{" + str(b) + "}"
            return new_string
        except Exception:
            return string

    def _remove_right_units(string):
        # "\\text{ " only ever occurs (at least in the val set) when describing units
        if "\\text{ " in string:
            splits = string.split("\\text{ ")
            assert len(splits) == 2
            return splits[0]
        else:
            return string

    def _fix_sqrt(string):
        if "\\sqrt" not in string:
            return string
        splits = string.split("\\sqrt")
        new_string = splits[0]
        for split in splits[1:]:
            if split[0] != "{":
                a = split[0]
                new_substr = "\\sqrt{" + a + "}" + split[1:]
            else:
                new_substr = "\\sqrt" + split
            new_string += new_substr
        return new_string

    # linebreaks
    string = string.replace("\n", "")
    # print(string)

    # remove inverse spaces
    string = string.replace("\\!", "")
    # print(string)

    # replace \\ with \
    string = string.replace("\\\\", "\\")
    # print(string)

    # matrix
    string = re.sub(r"\\begin\{array\}\{.*?\}", r"\\begin{pmatrix}", string)
    string = re.sub(r"\\end\{array\}", r"\\end{pmatrix}", string)
    string = string.replace("bmatrix", "pmatrix")

    # replace tfrac and dfrac with frac
    string = string.replace("tfrac", "frac")
    string = string.replace("dfrac", "frac")
    string = (
        string.replace("\\neq", "\\ne")
        .replace("\\leq", "\\le")
        .replace("\\geq", "\\ge")
    )
    # print(string)

    # remove \left and \right
    string = string.replace("\\left", "")
    string = string.replace("\\right", "")
    # print(string)

    # Remove unit: miles, dollars if after is not none
    _string = re.sub(r"\\text{.*?}$", "", string).strip()
    if _string != "" and _string != string:
        # print("Warning: unit not removed: '{}' -> '{}'".format(string, _string))
        string = _string

    # Remove unit: texts
    for _ in range(2):
        for unit_text in unit_texts:
            # use regex, the prefix should be either the start of the string or a non-alphanumeric character
            # the suffix should be either the end of the string or a non-alphanumeric character
            _string = re.sub(r"(^|\W)" + unit_text + r"($|\W)", r"\1\2", string)
            if _string != "":
                string = _string

    # Remove circ (degrees)
    string = string.replace("^{\\circ}", "")
    string = string.replace("^\\circ", "")

    # remove dollar signs
    string = string.replace("\\$", "")

    # remove units (on the right)
    string = _remove_right_units(string)

    # remove percentage
    string = string.replace("\\%", "")
    string = string.replace(r"\%", "")

    # " 0." equivalent to " ." and "{0." equivalent to "{." Alternatively, add "0" if "." is the start of the string
    string = string.replace(" .", " 0.")
    string = string.replace("{.", "{0.")
    # if empty, return empty string
    if len(string) == 0:
        return string
    if string[0] == ".":
        string = "0" + string

    # to consider: get rid of e.g. "k = " or "q = " at beginning
    if len(string.split("=")) == 2:
        if len(string.split("=")[0]) <= 2:
            string = string.split("=")[1]

    # fix sqrt3 --> sqrt{3}
    string = _fix_sqrt(string)

    # remove spaces
    string = string.replace(" ", "")

    # \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}
    string = _fix_fracs(string)

    # manually change 0.5 --> \frac{1}{2}
    if string == "0.5":
        string = "\\frac{1}{2}"

    # NOTE: X/Y changed to \frac{X}{Y} in dataset, but in simple cases fix in case the model output is X/Y
    string = _fix_a_slash_b(string)

    return string


SUBSTITUTIONS = [
    ("an ", ""),
    ("a ", ""),
    (".$", "$"),
    ("\\$", ""),
    (r"\ ", ""),
    (" ", ""),
    ("mbox", "text"),
    (",\\text{and}", ","),
    ("\\text{and}", ","),
    ("\\text{m}", "\\text{}"),
]


REMOVED_EXPRESSIONS = [
    "square",
    "ways",
    "integers",
    "dollars",
    "mph",
    "inches",
    "ft",
    "hours",
    "km",
    "units",
    "\\ldots",
    "sue",
    "points",
    "feet",
    "minutes",
    "digits",
    "cents",
    "degrees",
    "cm",
    "gm",
    "pounds",
    "meters",
    "meals",
    "edges",
    "students",
    "childrentickets",
    "multiples",
    "\\text{s}",
    "\\text{.}",
    "\\text{\ns}",
    "\\text{}^2",
    "\\text{}^3",
    "\\text{\n}",
    "\\text{}",
    r"\mathrm{th}",
    r"^\circ",
    r"^{\circ}",
    r"\;",
    r",\!",
    "{,}",
    '"',
    "\\dots",
]


def normalize_final_answer(final_answer: str) -> str:
    """
    Normalize a final answer to a quantitative reasoning question.
    This code comes from https://arxiv.org/pdf/2206.14858.pdf, page18.
    """
    # final_answer = final_answer.split("=")[-1]

    for before, after in SUBSTITUTIONS:
        final_answer = final_answer.replace(before, after)
    for expr in REMOVED_EXPRESSIONS:
        final_answer = final_answer.replace(expr, "")

    # Extract answer that is in LaTeX math, is bold,
    # is surrounded by a box, etc.
    final_answer = re.sub(r"(.*?)(\$)(.*?)(\$)(.*)", "$\\3$", final_answer)
    final_answer = re.sub(r"(\\text\{)(.*?)(\})", "\\2", final_answer)
    final_answer = re.sub(r"(\\textbf\{)(.*?)(\})", "\\2", final_answer)
    final_answer = re.sub(r"(\\overline\{)(.*?)(\})", "\\2", final_answer)
    final_answer = re.sub(r"(\\boxed\{)(.*)(\})", "\\2", final_answer)

    # Normalize shorthand TeX:
    # \fracab -> \frac{a}{b}
    # \frac{abc}{bef} -> \frac{abc}{bef}
    # \fracabc -> \frac{a}{b}c
    # \sqrta -> \sqrt{a}
    # \sqrtab -> sqrt{a}b
    final_answer = re.sub(r"(frac)([^{])(.)", "frac{\\2}{\\3}", final_answer)
    final_answer = re.sub(r"(sqrt)([^{])", "sqrt{\\2}", final_answer)
    final_answer = final_answer.replace("$", "")

    # Normalize 100,000 -> 100000
    if final_answer.replace(",", "").isdigit():
        final_answer = final_answer.replace(",", "")

    return final_answer


def repeatness(s: str):
    def ranks(values):
        index = {v: i for i, v in enumerate(sorted(set(values)))}
        return [index[v] for v in values]

    def suffixArray(s):
        line = ranks(s)
        n, k, ans, sa = len(s), 1, line, [0] * len(s)
        while k < n - 1:
            line = ranks(list(zip_longest(line, islice(line, k, None), fillvalue=-1)))
            ans, k = line, k << 1
        for i, k in enumerate(ans):
            sa[k] = i
        return ans, sa

    def lcp(arr, suffixArr, inv_suff):
        n, ans, k = len(arr), [0] * len(arr), 0

        for i in range(n):
            if inv_suff[i] == n - 1:
                k = 0
                continue

            j = suffixArr[inv_suff[i] + 1]
            while i + k < n and j + k < n and arr[i + k] == arr[j + k]:
                k += 1

            ans[inv_suff[i]] = k
            if k > 0:
                k -= 1

        return ans

    arr = [ord(i) for i in s]
    n = len(arr)
    if n <= 1:
        return 0
    c, sa = suffixArray(arr)
    cnt = sum(lcp(arr, sa, c))

    return (cnt * 2 / (n * (n + 1))) > 0.2


class timeout:
    def __init__(self, seconds=1, error_message="Timeout"):
        self.seconds = seconds
        self.error_message = error_message
        self._armed = False
        self._old_handler = None

    def handle_timeout(self, signum, frame):
        raise TimeoutError(self.error_message)

    def __enter__(self):
        if threading.current_thread() is not threading.main_thread():
            return self
        self._old_handler = signal.getsignal(signal.SIGALRM)
        signal.signal(signal.SIGALRM, self.handle_timeout)
        signal.alarm(self.seconds)
        self._armed = True
        return self

    def __exit__(self, type, value, traceback):
        if self._armed:
            signal.alarm(0)
            signal.signal(signal.SIGALRM, self._old_handler)
            self._armed = False


def latex_eval(latex):
    sym = parse_latex(latex)
    val = sym.evalf()
    return sym, val


def numeric_equal(prediction: float, reference: float):
    # Note that relative tolerance has significant impact
    # on the result of the synthesized GSM-Hard dataset
    # if reference.is_integer():
    #     return isclose(reference, round(prediction), abs_tol=1e-4)
    # else:
    # prediction = round(prediction, len(str(reference).split(".")[-1]))
    return isclose(reference, prediction, rel_tol=1e-4)


def symbolic_equal(a, b):
    def _parse(s):
        for f in [parse_latex, parse_expr, latex2sympy]:
            try:
                return f(s.replace("\\\\", "\\"))
            except Exception:
                try:
                    return f(s)
                except Exception:
                    pass
        return s

    a = _parse(a)
    b = _parse(b)

    # direct equal
    try:
        if str(a) == str(b) or a == b:
            return True
    except Exception:
        pass

    # simplify equal
    try:
        if a.equals(b) or simplify(a - b) == 0:
            return True
    except Exception:
        pass

    # equation equal
    try:
        if (abs(a.lhs - a.rhs)).equals(abs(b.lhs - b.rhs)):
            return True
    except Exception:
        pass

    try:
        if numeric_equal(float(N(a)), float(N(b))):
            return True
    except Exception:
        pass

    # matrix
    try:
        # if a and b are matrix
        if a.shape == b.shape:
            _a = a.applyfunc(lambda x: round(x, 3))
            _b = b.applyfunc(lambda x: round(x, 3))
            if _a.equals(_b):
                return True
    except Exception:
        pass

    return False


def _is_latex_equal(str1, str2):
    try:
        sym1, val1 = latex_eval(str1)
        sym2, val2 = latex_eval(str2)
        if sym1 == sym2 or val1 == val2:
            return True
        else:
            raise ValueError
    except Exception:  # noqa
        try:
            norm1, norm2 = normalize_final_answer(str1), normalize_final_answer(str2)
            sym1, val1 = latex_eval(norm1)
            sym2, val2 = latex_eval(norm2)
            if sym1 == sym2 or val1 == val2:
                return True
        except Exception:  # noqa
            return norm1 == norm2
    return False


def is_latex_equal(given_answer: str, ground_truth: str) -> bool:
    try:
        with timeout(1):
            try:
                if (len(given_answer) > 128 and repeatness(given_answer)) or (
                    len(ground_truth) > 128 and repeatness(ground_truth)
                ):
                    return False
                # First conduct normalized string matching.
                ground_truth_normalized = _normalize(ground_truth)
                given_normalized = _normalize(given_answer)
                if ground_truth_normalized is None:
                    return False
                if ground_truth_normalized == given_normalized:
                    return True

                # Next call math verify.
                given_answer.replace("\n", "")
                ground_truth.replace("\n", "")
                if "$" not in given_answer:
                    given_answer = f"${given_answer}$"
                if "$" not in ground_truth:
                    ground_truth = f"${ground_truth}$"
                return verify(
                    parse(
                        ground_truth,
                        extraction_config=(
                            LatexExtractionConfig(boxed_match_priority=0),
                            ExprExtractionConfig(),
                        ),
                        fallback_mode="no_fallback",
                        extraction_mode=["first_match"],
                        parsing_timeout=1,
                    ),
                    parse(
                        given_answer,
                        extraction_config=(
                            LatexExtractionConfig(boxed_match_priority=0),
                            ExprExtractionConfig(),
                        ),
                        fallback_mode="no_fallback",
                        extraction_mode=["first_match"],
                        parsing_timeout=1,
                    ),
                    timeout_seconds=1,
                )
                # or symbolic_equal(ground_truth, given_answer)
            except Exception:
                return False
    except TimeoutError:
        return False


def is_value_equal(given_answer: str, ground_truth: str) -> bool:
    assert ground_truth is not None
    ground_truth_normalized_mathd = mathd_normalize_answer(ground_truth)
    given_answer_normalized_mathd = mathd_normalize_answer(given_answer)

    str_equal = ground_truth_normalized_mathd == given_answer_normalized_mathd
    try:
        number_equal = float(ground_truth_normalized_mathd) == float(
            given_answer_normalized_mathd
        )
        return str_equal or number_equal
    except Exception:
        return str_equal


# sympy might hang -- we don't care about trying to be lenient in these cases
BAD_SUBSTRINGS = ["^{", "^("]
BAD_REGEXES = [r"\^[0-9]+\^", r"\^[0-9][0-9]+"]
TUPLE_CHARS = "()[]"


def _sympy_parse(expr: str):
    """Parses an expression with sympy."""
    py_expr = expr.replace("^", "**")
    return sympy_parser.parse_expr(
        py_expr,
        transformations=(
            sympy_parser.standard_transformations
            + (sympy_parser.implicit_multiplication_application,)
        ),
    )


def _parse_latex(expr: str) -> str:
    """Attempts to parse latex to an expression sympy can read."""
    expr = expr.replace("\\tfrac", "\\frac")
    expr = expr.replace("\\dfrac", "\\frac")
    expr = expr.replace("\\frac", " \\frac")  # Play nice with mixed numbers.
    expr = latex2text.LatexNodes2Text().latex_to_text(expr)

    # Replace the specific characters that this parser uses.
    expr = expr.replace("√", "sqrt")
    expr = expr.replace("π", "pi")
    expr = expr.replace("∞", "inf")
    expr = expr.replace("∪", "U")
    expr = expr.replace("·", "*")
    expr = expr.replace("×", "*")

    return expr.strip()


def _is_float(num: str) -> bool:
    try:
        float(num)
        return True
    except ValueError:
        return False


def _is_int(x: float) -> bool:
    try:
        return abs(x - int(round(x))) <= 1e-7
    except Exception:
        return False


def _is_frac(expr: str) -> bool:
    return bool(re.search(r"^-?[0-9]+.?/0*[1-9][0-9]*.?$", expr))


def _str_is_int(x: str) -> bool:
    try:
        x = _strip_properly_formatted_commas(x)
        x = float(x)
        return abs(x - int(round(x))) <= 1e-7
    except Exception:
        return False


def _str_to_int(x: str) -> bool:
    x = x.replace(",", "")
    x = float(x)
    return int(x)


def _inject_implicit_mixed_number(step: str):
    """
    Automatically make a mixed number evalable
    e.g. 7 3/4 => 7+3/4
    """
    p1 = re.compile("([0-9]) +([0-9])")
    step = p1.sub("\\1+\\2", step)  ## implicit mults
    return step


def _strip_properly_formatted_commas(expr: str):
    # We want to be careful because we don't want to strip tuple commas
    p1 = re.compile(r"(\d)(,)(\d\d\d)($|\D)")
    while True:
        next_expr = p1.sub("\\1\\3\\4", expr)
        if next_expr == expr:
            break
        expr = next_expr
    return next_expr


def _normalize(expr: str) -> str:
    """Normalize answer expressions."""
    if expr is None:
        return None

    # Remove enclosing `\text{}`.
    m = re.search(r"^\\text\{(?P<text>.+?)\}$", expr)
    if m is not None:
        expr = m.group("text")

    expr = expr.replace("\\%", "%")
    expr = expr.replace("\\$", "$")
    expr = expr.replace("$", "")
    expr = expr.replace("%", "")
    expr = expr.replace(" or ", " , ")
    expr = expr.replace(" and ", " , ")

    expr = expr.replace("million", "*10^6")
    expr = expr.replace("billion", "*10^9")
    expr = expr.replace("trillion", "*10^12")

    for unit in [
        "degree",
        "cm",
        "centimeter",
        "meter",
        "mile",
        "second",
        "minute",
        "hour",
        "day",
        "week",
        "month",
        "year",
        "foot",
        "feet",
        "inch",
        "yard",
    ]:
        expr = re.sub(rf"{unit}(es)?(s)? *(\^[0-9]+)?", "", expr)
    expr = re.sub(r"\^ *\\\\circ", "", expr)

    if len(expr) > 0 and expr[0] == "{" and expr[-1] == "}":
        expr = expr[1:-1]

    expr = re.sub(",\\\\! *", "", expr)
    if _is_float(expr) and _is_int(float(expr)):
        expr = str(int(round(float(expr))))
    if "\\" in expr:
        try:
            expr = _parse_latex(expr)
        except Exception:
            pass

    # edge case with mixed numbers and negative signs
    expr = re.sub("- *", "-", expr)

    expr = _inject_implicit_mixed_number(expr)
    expr = expr.replace(" ", "")

    # if we somehow still have latex braces here, just drop them
    expr = expr.replace("{", "")
    expr = expr.replace("}", "")

    # don't be case sensitive for text answers
    expr = expr.lower()

    if _str_is_int(expr):
        expr = str(_str_to_int(expr))

    return expr


def count_unknown_letters_in_expr(expr: str):
    expr = expr.replace("sqrt", "")
    expr = expr.replace("frac", "")
    letters_in_expr = set([x for x in expr if x.isalpha()])
    return len(letters_in_expr)


def should_allow_eval(expr: str):
    # we don't want to try parsing unknown text or functions of more than two variables
    if count_unknown_letters_in_expr(expr) > 2:
        return False

    for bad_string in BAD_SUBSTRINGS:
        if bad_string in expr:
            return False

    for bad_regex in BAD_REGEXES:
        if re.search(bad_regex, expr) is not None:
            return False

    return True


def are_equal_under_sympy(ground_truth_normalized: str, given_normalized: str):
    are_equal = False
    try:
        expr = f"({ground_truth_normalized})-({given_normalized})"
        if should_allow_eval(expr):
            sympy_diff = _sympy_parse(expr)
            simplified = sympy.simplify(sympy_diff)
            if simplified == 0:
                are_equal = True
    except Exception:
        pass
    return are_equal


def split_tuple(expr: str):
    """
    Split the elements in a tuple/interval, while handling well-formatted commas in large numbers
    """
    expr = _strip_properly_formatted_commas(expr)
    if len(expr) == 0:
        return []
    if (
        len(expr) > 2
        and expr[0] in TUPLE_CHARS
        and expr[-1] in TUPLE_CHARS
        and all([ch not in expr[1:-1] for ch in TUPLE_CHARS])
    ):
        elems = [elem.strip() for elem in expr[1:-1].split(",")]
    else:
        elems = [expr]
    return elems


def last_boxed_only_string(string):
    idx = string.rfind("\\boxed")
    if idx < 0:
        idx = string.rfind("\\fbox")
        if idx < 0:
            return None

    i = idx
    right_brace_idx = None
    num_left_braces_open = 0
    while i < len(string):
        if string[i] == "{":
            num_left_braces_open += 1
        if string[i] == "}":
            num_left_braces_open -= 1
            if num_left_braces_open == 0:
                right_brace_idx = i
                break
        i += 1

    if right_brace_idx is None:
        retval = None
    else:
        retval = string[idx : right_brace_idx + 1]

    return retval


def remove_boxed(s):
    left = "\\boxed{"
    try:
        assert s[: len(left)] == left
        assert s[-1] == "}"
        return s[len(left) : -1]
    except Exception:
        return None


def extract_boxed_answer(solution: str) -> str:
    """Extract the answer from inside a LaTeX \\boxed{} command"""
    solution = last_boxed_only_string(solution)
    solution = remove_boxed(solution)
    return solution


def grade_answer_sympy(given_answer: str, ground_truth: str) -> bool:
    ground_truth_normalized = _normalize(ground_truth)
    given_normalized = _normalize(given_answer)

    if ground_truth_normalized is None:
        return False

    if ground_truth_normalized == given_normalized:
        return True

    if len(given_normalized) == 0:
        return False

    ground_truth_elems = split_tuple(ground_truth_normalized)
    given_elems = split_tuple(given_normalized)

    if len(ground_truth_elems) > 1 and (
        ground_truth_normalized[0] != given_normalized[0]
        or ground_truth_normalized[-1] != given_normalized[-1]
    ):
        is_correct = False
    elif len(ground_truth_elems) != len(given_elems):
        is_correct = False
    else:
        for ground_truth_elem, given_elem in zip(ground_truth_elems, given_elems):
            if _is_frac(ground_truth_elem) and _is_frac(given_elem):
                # if fractions aren't reduced, then shouldn't be marked as correct
                # so, we don't want to allow sympy.simplify in this case
                is_correct = ground_truth_elem == given_elem
            elif _str_is_int(ground_truth_elem) != _str_is_int(given_elem):
                # if the ground truth answer is an integer, we require the given answer to be a strict match (no sympy.simplify)
                is_correct = False
            else:
                is_correct = are_equal_under_sympy(ground_truth_elem, given_elem)
            if not is_correct:
                break

    return is_correct


def grade_answer_mathd(given_answer: str, ground_truth: str) -> bool:
    ground_truth_normalized_mathd = mathd_normalize_answer(ground_truth)
    given_answer_normalized_mathd = mathd_normalize_answer(given_answer)

    # be at least as lenient as mathd
    if ground_truth_normalized_mathd == given_answer_normalized_mathd:
        return True
    return False


def extract_answer(passage: str) -> str:
    if "\\boxed" in passage:
        return extract_boxed_answer(passage)
    return None


def _parse_modebench_spec(gt_answer: Any) -> dict[str, Any] | None:
    if isinstance(gt_answer, dict):
        spec = gt_answer
    elif isinstance(gt_answer, str):
        text = gt_answer.strip()
        if not (text.startswith("{") and text.endswith("}")):
            return None
        try:
            spec = json.loads(text)
        except Exception:
            return None
    else:
        return None
    verifier = spec.get("verifier")
    if verifier in {
        "graph_coloring",
        "countdown",
        MATHIR_VERIFIER,
        MATHIR_MENU_VERIFIER,
        PANTRY_PLAN_VERIFIER,
        PYTHON_FACTOR_VERIFIER,
        POINT_MAZE_VERIFIER,
        ANT_MAZE_VERIFIER,
    }:
        return spec
    return None


PYTHON_FACTOR_RESPONSE_SURFACE_VERSION = (
    "python-factor-response-v2-latex-lambda"
)


def _normalize_python_factor_lambda_surface(candidate: str) -> str:
    """Normalize one formatting-only LaTeX spelling of ``lambda n:``."""

    # Qwen's native boxed surface can typeset the Python keyword as the LaTeX
    # command ``\lambda``.  Accept only the exact required signature (plus the
    # conventional ``\,`` spacing alias); the restricted AST parser and
    # isolated executable validator remain the authority.
    return re.sub(
        r"^\\lambda(?:\s+|\\,\s*)n\s*:\s*",
        "lambda n: ",
        str(candidate).strip(),
        count=1,
    ).strip()


def _extract_modebench_candidate(model_response: str, gt_answer: Any) -> str | None:
    spec = _parse_modebench_spec(gt_answer)
    if spec is None:
        return None
    if "\\boxed" in str(model_response):
        candidate = extract_answer(str(model_response))
        if candidate is None:
            return None
        if str(spec.get("verifier")) == PYTHON_FACTOR_VERIFIER:
            candidate = _normalize_python_factor_lambda_surface(candidate)
        return candidate or None
    candidate = str(model_response).strip()
    if not candidate:
        return None
    if str(spec.get("verifier")) in {
        MATHIR_VERIFIER,
        MATHIR_MENU_VERIFIER,
    }:
        fenced = re.fullmatch(
            r"```(?:mathir)?\s*(.*?)\s*```",
            candidate,
            flags=re.IGNORECASE | re.DOTALL,
        )
        if fenced is not None:
            candidate = fenced.group(1).strip()
        if len(candidate) > 200 or "<" in candidate or ">" in candidate:
            return None
        # Whitespace, a terminal semicolon, and an all-program code fence are
        # formatting aliases.  The restricted parser remains the authority.
        return candidate or None
    if str(spec.get("verifier")) == PYTHON_FACTOR_VERIFIER:
        fenced = re.fullmatch(
            r"```(?:python)?\s*(.*?)\s*```",
            candidate,
            flags=re.IGNORECASE | re.DOTALL,
        )
        if fenced is not None:
            candidate = fenced.group(1).strip()
        if (
            len(candidate) > 240
            or "\n" in candidate
            or "\r" in candidate
            or "<" in candidate
            or ">" in candidate
        ):
            return None
        candidate = re.sub(
            r"^\s*(?:the\s+)?(?:final\s+)?(?:answer|program|function)\s*"
            r"(?:is|=|:)\s*",
            "",
            candidate,
            flags=re.IGNORECASE,
        ).strip()
        candidate = _normalize_python_factor_lambda_surface(candidate)
        return candidate or None
    if str(spec.get("verifier")) in {
        POINT_MAZE_VERIFIER,
        ANT_MAZE_VERIFIER,
    }:
        fenced = re.fullmatch(
            r"```(?:actions?|plan)?\s*(.*?)\s*```",
            candidate,
            flags=re.IGNORECASE | re.DOTALL,
        )
        if fenced is not None:
            candidate = fenced.group(1).strip()
        if len(candidate) > 4096 or "<" in candidate or ">" in candidate:
            return None
        candidate = re.sub(
            r"^\s*(?:the\s+)?(?:final\s+)?(?:answer|plan|program|actions?)\s*"
            r"(?:is|=|:)\s*",
            "",
            candidate,
            flags=re.IGNORECASE,
        ).strip()
        return candidate or None
    if str(spec.get("verifier")) == PANTRY_PLAN_VERIFIER:
        if (
            len(candidate) > 512
            or "\n" in candidate
            or "\r" in candidate
            or "<" in candidate
            or ">" in candidate
        ):
            return None
        candidate = re.sub(
            r"^\s*(?:the\s+)?(?:final\s+)?(?:answer|plan|recipe)\s*"
            r"(?:is|=|:)\s*",
            "",
            candidate,
            flags=re.IGNORECASE,
        ).strip()
        return candidate or None
    if "\n" in candidate or "\r" in candidate or "<" in candidate or ">" in candidate:
        return None
    if len(candidate) > 160:
        return None
    candidate = re.sub(
        r"^\s*(?:the\s+)?(?:final\s+)?(?:answer|expression|coloring|program)\s*"
        r"(?:is|=|:)\s*",
        "",
        candidate,
        flags=re.IGNORECASE,
    ).strip()
    return candidate or None


def _parse_graph_coloring_answer(candidate: str, n: int) -> list[int] | None:
    text = str(candidate).strip().lower()
    text = re.sub(r"^(?:coloring|answer)\s*(?:is|=|:)\s*", "", text).strip()
    compact = re.sub(r"[\s,;|\[\]\(\)\{\}:.-]+", "", text)
    if len(compact) == n and all(ch in "123" for ch in compact):
        return [int(ch) for ch in compact]
    tokens = re.findall(r"[123]", text)
    if len(tokens) == n:
        return [int(token) for token in tokens]
    return None


def _parse_graph_digit_sequence(candidate: str, expected_len: int) -> list[int] | None:
    text = str(candidate).strip().lower()
    text = re.sub(
        r"^(?:missing\s+)?(?:colors?|digits?|answer)\s*(?:are|is|=|:)\s*",
        "",
        text,
    ).strip()
    compact = re.sub(r"[\s,;|\[\]\(\)\{\}:.-]+", "", text)
    if len(compact) == expected_len and all(ch in "123" for ch in compact):
        return [int(ch) for ch in compact]
    tokens = re.findall(r"[123]", text)
    if len(tokens) == expected_len:
        return [int(token) for token in tokens]
    return None


def _verify_graph_coloring_colors(
    colors: list[int] | None,
    spec: dict[str, Any],
) -> bool:
    """Validate one already-parsed coloring object against its problem."""

    try:
        n = int(spec["n"])
        edges = spec["edges"]
    except Exception:
        return False
    if colors is None or len(colors) != n:
        return False
    partial_colors = spec.get("partial_colors")
    if partial_colors is not None:
        try:
            if len(partial_colors) != n:
                return False
            for index, color in enumerate(partial_colors):
                if color is None:
                    continue
                if colors[index] != int(color):
                    return False
        except Exception:
            return False
    for edge in edges:
        try:
            u, v = int(edge[0]), int(edge[1])
        except Exception:
            return False
        if u < 1 or v < 1 or u > n or v > n:
            return False
        if colors[u - 1] == colors[v - 1]:
            return False
    return True


def _verify_graph_coloring_answer(candidate: str, spec: dict[str, Any]) -> bool:
    colors = _graph_coloring_from_candidate(candidate, spec)
    return _verify_graph_coloring_colors(colors, spec)


def _normalize_countdown_expression(candidate: str) -> str:
    text = str(candidate).strip()
    text = text.replace("\\times", "*").replace("\\cdot", "*")
    text = text.replace("\\div", "/").replace("÷", "/").replace("×", "*")
    text = text.replace("^", "**")
    text = re.sub(r"^\s*(?:expression|answer)\s*(?:is|=|:)\s*", "", text, flags=re.I)
    return text.strip()


def _countdown_eval_and_numbers(node: ast.AST) -> tuple[Fraction, list[int]]:
    if isinstance(node, ast.Expression):
        return _countdown_eval_and_numbers(node.body)
    if isinstance(node, ast.Constant):
        if isinstance(node.value, bool) or not isinstance(node.value, int):
            raise ValueError("Countdown constants must be integers.")
        return Fraction(int(node.value), 1), [int(node.value)]
    if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
        value, numbers = _countdown_eval_and_numbers(node.operand)
        if isinstance(node.op, ast.USub):
            value = -value
        return value, numbers
    if isinstance(node, ast.BinOp):
        left, left_numbers = _countdown_eval_and_numbers(node.left)
        right, right_numbers = _countdown_eval_and_numbers(node.right)
        if isinstance(node.op, ast.Add):
            value = left + right
        elif isinstance(node.op, ast.Sub):
            value = left - right
        elif isinstance(node.op, ast.Mult):
            value = left * right
        elif isinstance(node.op, ast.Div):
            if right == 0:
                raise ValueError("Countdown division by zero.")
            value = left / right
        else:
            raise ValueError("Unsupported Countdown operator.")
        return value, left_numbers + right_numbers
    raise ValueError("Unsupported Countdown expression.")


def _verify_countdown_expression(candidate: str, spec: dict[str, Any]) -> bool:
    try:
        target = Fraction(int(spec["target"]), 1)
        expected_numbers = Counter(int(value) for value in spec["numbers"])
    except Exception:
        return False
    text = _normalize_countdown_expression(candidate)
    if not text:
        return False
    parts = [part.strip() for part in text.split("=") if part.strip()]
    if not parts:
        parts = [text]
    for part in parts:
        if not re.fullmatch(r"[0-9+\-*/().\s*]+", part):
            continue
        try:
            parsed = ast.parse(part, mode="eval")
            value, used_numbers = _countdown_eval_and_numbers(parsed)
        except Exception:
            continue
        if value == target and Counter(used_numbers) == expected_numbers:
            return True
    return False


def _graph_coloring_from_candidate(
    candidate: str,
    spec: dict[str, Any],
) -> list[int] | None:
    try:
        n = int(spec["n"])
    except Exception:
        return None
    colors = _parse_graph_coloring_answer(candidate, n)
    partial_colors = spec.get("partial_colors")
    if colors is None and partial_colors is not None:
        try:
            hidden_positions = [
                index for index, color in enumerate(partial_colors) if color is None
            ]
            fill = _parse_graph_digit_sequence(candidate, len(hidden_positions))
            if fill is not None:
                colors = [
                    int(color) if color is not None else 0 for color in partial_colors
                ]
                for index, color in zip(hidden_positions, fill):
                    colors[index] = color
        except Exception:
            return None
    if colors is None or len(colors) != n:
        return None
    return colors


def _canonical_countdown_ast(node: ast.AST) -> str:
    if isinstance(node, ast.Expression):
        return _canonical_countdown_ast(node.body)
    if isinstance(node, ast.Constant):
        if isinstance(node.value, bool) or not isinstance(node.value, int):
            raise ValueError("Countdown constants must be integers.")
        return str(int(node.value))
    if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
        inner = _canonical_countdown_ast(node.operand)
        if isinstance(node.op, ast.USub):
            return f"neg({inner})"
        return inner
    if isinstance(node, ast.BinOp):
        left = _canonical_countdown_ast(node.left)
        right = _canonical_countdown_ast(node.right)
        if isinstance(node.op, ast.Add):
            parts = sorted([left, right])
            return f"add({parts[0]},{parts[1]})"
        if isinstance(node.op, ast.Mult):
            parts = sorted([left, right])
            return f"mul({parts[0]},{parts[1]})"
        if isinstance(node.op, ast.Sub):
            return f"sub({left},{right})"
        if isinstance(node.op, ast.Div):
            return f"div({left},{right})"
    raise ValueError("Unsupported Countdown expression.")


def _canonical_countdown_route_ast(node: ast.AST) -> str:
    """Canonical operator/dependency skeleton with numeric leaves abstracted."""

    if isinstance(node, ast.Expression):
        return _canonical_countdown_route_ast(node.body)
    if isinstance(node, ast.Constant):
        if isinstance(node.value, bool) or not isinstance(node.value, int):
            raise ValueError("Countdown constants must be integers.")
        return "input"
    if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
        inner = _canonical_countdown_route_ast(node.operand)
        return f"neg({inner})" if isinstance(node.op, ast.USub) else inner
    if isinstance(node, ast.BinOp):
        left = _canonical_countdown_route_ast(node.left)
        right = _canonical_countdown_route_ast(node.right)
        if isinstance(node.op, ast.Add):
            parts = sorted([left, right])
            return f"add({parts[0]},{parts[1]})"
        if isinstance(node.op, ast.Mult):
            parts = sorted([left, right])
            return f"mul({parts[0]},{parts[1]})"
        if isinstance(node.op, ast.Sub):
            return f"sub({left},{right})"
        if isinstance(node.op, ast.Div):
            return f"div({left},{right})"
    raise ValueError("Unsupported Countdown route expression.")


def _canonical_countdown_expression_key(
    candidate: str,
    spec: dict[str, Any],
) -> str | None:
    try:
        expected_numbers = Counter(int(value) for value in spec["numbers"])
    except Exception:
        return None
    text = _normalize_countdown_expression(candidate)
    if not text:
        return None
    parts = [part.strip() for part in text.split("=") if part.strip()] or [text]
    for part in parts:
        if not re.fullmatch(r"[0-9+\-*/().\s*]+", part):
            continue
        try:
            parsed = ast.parse(part, mode="eval")
            _, used_numbers = _countdown_eval_and_numbers(parsed)
            if Counter(used_numbers) != expected_numbers:
                continue
            return f"countdown:{_canonical_countdown_ast(parsed)}"
        except Exception:
            continue
    return None


def _modebench_answer_key(
    model_response: str,
    gt_answer: Any,
) -> str | None:
    spec = _parse_modebench_spec(gt_answer)
    if spec is None:
        return None
    candidate = _extract_modebench_candidate(model_response, gt_answer)
    if candidate is None:
        return None
    verifier = str(spec.get("verifier"))
    if verifier == "graph_coloring":
        colors = _graph_coloring_from_candidate(candidate, spec)
        if colors is None:
            return None
        return "graph_coloring:" + "".join(str(int(color)) for color in colors)
    if verifier == "countdown":
        return _canonical_countdown_expression_key(candidate, spec)
    if verifier == MATHIR_VERIFIER:
        validation = validate_mathir_algebra(candidate, spec)
        return validation.canonical_key if validation is not None else None
    if verifier == MATHIR_MENU_VERIFIER:
        validation = validate_mathir_action_menu(candidate, spec)
        return validation.canonical_key if validation is not None else None
    if verifier == PYTHON_FACTOR_VERIFIER:
        validation = validate_python_factor_function_external(candidate, spec)
        return validation.canonical_key if validation is not None else None
    if verifier == PANTRY_PLAN_VERIFIER:
        validation = validate_pantry_plan(candidate, spec)
        return validation.canonical_key if validation is not None else None
    if verifier in {POINT_MAZE_VERIFIER, ANT_MAZE_VERIFIER}:
        validation = validate_maze_action_program_external(candidate, spec)
        return validation.canonical_key if validation is not None else None
    return None


def validated_modebench_outcome_key(
    model_response: str,
    gt_answer: Any,
) -> str | None:
    """Return a canonical outcome only when that same response verifies.

    This is the admission boundary for online canonical banks.  It deliberately
    supports only ModeBench tasks with executable validators:

    - graph colorings are parsed and checked against every graph edge;
    - Countdown expressions are parsed, checked for exact operand use, and
      executed against the requested target.

    - MathIR algebra programs are parsed by a restricted grammar, executed as
      state transformations, exact-normalized, and accepted only when execution
      isolates the right solution.  Their key comes from those executed states.

    - Python factor functions are syntax-restricted and called in an isolated
      Python worker.  Their key is the vector returned by those exact tool calls.

    Ordinary MATH final-answer grading is not a proof/strategy verifier and is
    therefore rejected here rather than being mislabeled as canonical search.
    """

    spec = _parse_modebench_spec(gt_answer)
    if spec is None:
        return None
    candidate = _extract_modebench_candidate(model_response, gt_answer)
    if candidate is None:
        return None
    verifier = str(spec.get("verifier"))
    if verifier == "graph_coloring":
        colors = _graph_coloring_from_candidate(candidate, spec)
        if not _verify_graph_coloring_colors(colors, spec):
            return None
        assert colors is not None
        return "graph_coloring:" + "".join(str(int(color)) for color in colors)
    if verifier == MATHIR_VERIFIER:
        validation = validate_mathir_algebra(candidate, spec)
        # The key is constructed from the exact normalized equation states
        # produced by the same interpreter execution that validated the answer.
        return validation.canonical_key if validation is not None else None
    if verifier == MATHIR_MENU_VERIFIER:
        validation = validate_mathir_action_menu(candidate, spec)
        # Menu labels are expanded first. Identity comes only from the exact
        # normalized states produced by executing those concrete operations.
        return validation.canonical_key if validation is not None else None
    if verifier == PYTHON_FACTOR_VERIFIER:
        validation = validate_python_factor_function_external(candidate, spec)
        return validation.canonical_key if validation is not None else None
    if verifier == PANTRY_PLAN_VERIFIER:
        validation = validate_pantry_plan(candidate, spec)
        return validation.canonical_key if validation is not None else None
    if verifier in {POINT_MAZE_VERIFIER, ANT_MAZE_VERIFIER}:
        validation = validate_maze_action_program_external(candidate, spec)
        return validation.canonical_key if validation is not None else None
    if verifier != "countdown":
        return None
    try:
        target = Fraction(int(spec["target"]), 1)
        expected_numbers = Counter(int(value) for value in spec["numbers"])
    except Exception:
        return None
    text = _normalize_countdown_expression(candidate)
    parts = [part.strip() for part in text.split("=") if part.strip()] or [text]
    for part in parts:
        if not re.fullmatch(r"[0-9+\-*/().\s*]+", part):
            continue
        try:
            parsed = ast.parse(part, mode="eval")
            value, used_numbers = _countdown_eval_and_numbers(parsed)
            if value != target or Counter(used_numbers) != expected_numbers:
                continue
            # The key is derived from the exact AST object that passed
            # execution and operand validation above.
            return f"countdown:{_canonical_countdown_ast(parsed)}"
        except Exception:
            continue
    return None


@dataclass(frozen=True)
class VerifiedExplorationIdentity:
    """Separate prompt-local endpoint and cross-prompt route identities."""

    verifier: str
    endpoint_key: str
    route_signature: str | None


def validated_modebench_exploration_identity(
    model_response: str,
    gt_answer: Any,
) -> VerifiedExplorationIdentity | None:
    """Return hierarchical identity only after exact executable validation."""

    spec = _parse_modebench_spec(gt_answer)
    if spec is None:
        return None
    candidate = _extract_modebench_candidate(model_response, gt_answer)
    if candidate is None:
        return None
    verifier = str(spec.get("verifier"))
    if verifier == "graph_coloring":
        colors = _graph_coloring_from_candidate(candidate, spec)
        if not _verify_graph_coloring_colors(colors, spec):
            return None
        assert colors is not None
        endpoint = "graph_coloring:" + "".join(str(int(color)) for color in colors)
        return VerifiedExplorationIdentity(verifier, endpoint, None)
    if verifier == MATHIR_VERIFIER:
        validation = validate_mathir_algebra(candidate, spec)
        if validation is None:
            return None
        solution = validation.solution
        endpoint = f"mathir-solution:{solution.numerator}/{solution.denominator}"
        return VerifiedExplorationIdentity(
            verifier,
            endpoint,
            validation.route_signature,
        )
    if verifier == MATHIR_MENU_VERIFIER:
        validation = validate_mathir_action_menu(candidate, spec)
        if validation is None:
            return None
        solution = validation.solution
        endpoint = f"mathir-solution:{solution.numerator}/{solution.denominator}"
        return VerifiedExplorationIdentity(
            verifier,
            endpoint,
            validation.route_signature,
        )
    if verifier == PYTHON_FACTOR_VERIFIER:
        validation = validate_python_factor_function_external(candidate, spec)
        if validation is None:
            return None
        try:
            route = python_factor_route_signature(candidate)
        except Exception:
            return None
        return VerifiedExplorationIdentity(
            verifier,
            validation.canonical_key,
            route,
        )
    if verifier == PANTRY_PLAN_VERIFIER:
        validation = validate_pantry_plan(candidate, spec)
        if validation is None:
            return None
        return VerifiedExplorationIdentity(
            verifier,
            validation.canonical_key,
            None,
        )
    if verifier in {POINT_MAZE_VERIFIER, ANT_MAZE_VERIFIER}:
        validation = validate_maze_action_program_external(candidate, spec)
        if validation is None:
            return None
        return VerifiedExplorationIdentity(
            verifier,
            f"{verifier}:goal:{spec.get('map_id')}",
            validation.canonical_key,
        )
    if verifier != "countdown":
        return None
    try:
        target = Fraction(int(spec["target"]), 1)
        expected_numbers = Counter(int(value) for value in spec["numbers"])
    except Exception:
        return None
    text = _normalize_countdown_expression(candidate)
    parts = [part.strip() for part in text.split("=") if part.strip()] or [text]
    for part in parts:
        if not re.fullmatch(r"[0-9+\-*/().\s*]+", part):
            continue
        try:
            parsed = ast.parse(part, mode="eval")
            value, used_numbers = _countdown_eval_and_numbers(parsed)
            if value != target or Counter(used_numbers) != expected_numbers:
                continue
            endpoint = f"countdown-value:{value.numerator}/{value.denominator}"
            route = "countdown-route:v1:" + _canonical_countdown_route_ast(parsed)
            return VerifiedExplorationIdentity(verifier, endpoint, route)
        except Exception:
            continue
    return None


def _grade_modebench_answer(model_answer: str, gt_answer: Any) -> bool | None:
    spec = _parse_modebench_spec(gt_answer)
    if spec is None:
        return None
    verifier = str(spec.get("verifier"))
    if verifier == "graph_coloring":
        return _verify_graph_coloring_answer(model_answer, spec)
    if verifier == "countdown":
        return _verify_countdown_expression(model_answer, spec)
    if verifier == MATHIR_VERIFIER:
        return validate_mathir_algebra(model_answer, spec) is not None
    if verifier == MATHIR_MENU_VERIFIER:
        return validate_mathir_action_menu(model_answer, spec) is not None
    if verifier == PYTHON_FACTOR_VERIFIER:
        return validate_python_factor_function_external(model_answer, spec) is not None
    if verifier == PANTRY_PLAN_VERIFIER:
        return validate_pantry_plan(model_answer, spec) is not None
    if verifier in {POINT_MAZE_VERIFIER, ANT_MAZE_VERIFIER}:
        return validate_maze_action_program_external(model_answer, spec) is not None
    return False


def _clean_final_answer_candidate(candidate: str | None) -> str | None:
    """Return a compact final-answer candidate, or ``None`` for malformed text."""

    if candidate is None:
        return None
    candidate = str(candidate).strip()
    if not candidate:
        return None
    # Answer identity is deliberately stricter than correctness grading: mode
    # metrics need one stable, compact key per formatted final answer.
    if "\n" in candidate or "\r" in candidate or "<" in candidate or ">" in candidate:
        return None
    if len(candidate) > 160:
        return None
    candidate = re.sub(
        r"^\s*(?:the\s+)?(?:final\s+)?answer\s*(?:is|=|:)\s*",
        "",
        candidate,
        flags=re.IGNORECASE,
    ).strip()
    return candidate or None


def _extract_r1_reasoning_and_answer_sections(
    model_response: str,
) -> tuple[str | None, str | None]:
    """Return ``(<think> body, <answer> body)`` for an R1-style trace.

    Training prompts already end inside an open ``<think>`` tag, so many model
    responses begin with reasoning text and only emit the closing ``</think>``
    before ``<answer>``. We accept both:

    1. full tagged traces containing ``<think>...</think><answer>...</answer>``
    2. response-only continuations containing ``... </think> <answer>...</answer>``
    """

    if "<answer>" not in model_response or "</answer>" not in model_response:
        return None, None
    try:
        prefix, answer_suffix = model_response.split("<answer>", 1)
        answer = answer_suffix.split("</answer>", 1)[0].strip()
        reasoning = None
        if "<think>" in prefix and "</think>" in prefix:
            reasoning = prefix.split("<think>", 1)[1].split("</think>", 1)[0].strip()
        elif "</think>" in prefix:
            reasoning = prefix.split("</think>", 1)[0].strip()
        else:
            return None, None
        answer = answer
    except Exception:
        return None, None
    return reasoning or None, answer or None


def extract_normalized_final_answer(
    model_response: str, *, template: str = "r1", gt_answer: Any = None
) -> str | None:
    """Return a conservative canonical key for an answer or exact benchmark mode."""

    try:
        if gt_answer is not None:
            if _parse_modebench_spec(gt_answer) is not None:
                return _modebench_answer_key(
                    model_response,
                    gt_answer,
                )
            modebench_key = _modebench_answer_key(
                model_response,
                gt_answer,
            )
            if modebench_key is not None:
                return modebench_key
        candidate = None
        if template == "r1":
            # Match the training reward's strict R1 formatting gate.
            _, candidate = _extract_r1_reasoning_and_answer_sections(model_response)
            if candidate is None:
                return None
        else:
            candidate = extract_answer(model_response)
        if candidate is None:
            return None
        extracted = extract_answer(candidate) if "\\boxed" in candidate else candidate
        extracted = _clean_final_answer_candidate(extracted)
        if extracted is None:
            return None
        normalized = normalize_final_answer(extracted)
        normalized = _normalize(normalized)
        if normalized is None:
            normalized = normalize_final_answer(extracted)
        if normalized is None:
            return None
        normalized = str(normalized).strip().lower()
        return normalized or None
    except Exception:
        return None


def grade(model_answer: str, gt_answer: str, fast: bool = True):
    if "\\boxed" in gt_answer:
        gt_answer = extract_answer(gt_answer)
    correct = grade_answer_mathd(model_answer, gt_answer) or grade_answer_sympy(
        model_answer, gt_answer
    )
    if not fast:
        # This mode further uses math_verify to recall originally false positives.
        # Will be a bit slower, and sensitive to bad inputs.
        correct = correct or is_latex_equal(
            model_answer,
            gt_answer,
        )
    return correct


def boxed_reward_fn(model_response, gt_answer, fast=False):
    model_answer = _extract_modebench_candidate(model_response, gt_answer)
    if model_answer is not None:
        modebench_correct = _grade_modebench_answer(model_answer, gt_answer)
        if modebench_correct is not None:
            return {"formatted": True}, 1.0 if modebench_correct else 0.0
    model_answer = extract_answer(model_response)
    if model_answer is None:
        return {"formatted": False}, 0.0  # Cannot even parse anything.
    modebench_correct = _grade_modebench_answer(model_answer, gt_answer)
    if modebench_correct is not None:
        return {"formatted": True}, 1.0 if modebench_correct else 0.0
    if isinstance(gt_answer, float) or isinstance(gt_answer, int):
        gt_answer = str(gt_answer)
    if isinstance(gt_answer, str):
        is_correct = grade(model_answer, gt_answer, fast)
    elif isinstance(gt_answer, list):
        is_correct = False
        for gt in gt_answer:
            is_correct |= grade(model_answer, gt, fast)
    if is_correct:
        return {"formatted": True}, 1.0  # Correctness reward.
    else:
        return {
            "formatted": True
        }, 0.0  # Formatted but wrong answer; no format reward to avoid hacking.


def validated_math_route_signature(
    model_response: str,
    problem: str,
    gt_answer: Any,
    *,
    fast: bool = False,
    task_verified: bool | None = None,
) -> str | None:
    """Return an executable route identity only for a task-correct response.

    Task correctness, route execution, and agreement between the trace terminal
    value and the response's boxed answer are independent fail-closed checks.
    A correct answer without a valid trace keeps its ordinary task reward but
    has no route identity.
    """

    try:
        if task_verified is None:
            _info, reward = boxed_reward_fn(
                model_response,
                gt_answer,
                fast=fast,
            )
            task_verified = float(reward) > 0.0
        if not bool(task_verified):
            return None
        validation = validate_math_route_response(model_response, problem)
        if validation is None:
            return None
        model_answer = extract_answer(model_response)
        if model_answer is None:
            return None
        terminal_answer = sympy.latex(validation.terminal_value)
        if not grade(model_answer, terminal_answer, fast=fast):
            return None
        return validation.route_signature
    except Exception:
        return None


def validated_exploration_identity(
    model_response: str,
    problem: str,
    gt_answer: Any,
    *,
    fast: bool = False,
    task_verified: bool | None = None,
) -> VerifiedExplorationIdentity | None:
    """Return the endpoint/route pair for ModeBench or free-form MATH.

    ModeBench references always remain on their exact executable validator
    path. Free-form MATH may reuse the actor's already-computed task verdict,
    but route admission still independently executes the restricted trace and
    checks its terminal value against the boxed response. Thus a task-correct
    response without a valid route retains an endpoint identity and ordinary
    reward while contributing no route identity.
    """

    if _parse_modebench_spec(gt_answer) is not None:
        return validated_modebench_exploration_identity(
            model_response,
            gt_answer,
        )
    try:
        if task_verified is None:
            _info, reward = boxed_reward_fn(
                model_response,
                gt_answer,
                fast=fast,
            )
            task_verified = float(reward) > 0.0
        if not bool(task_verified):
            return None
        endpoint = extract_normalized_final_answer(
            model_response,
            template="qwen_math_route",
            gt_answer=gt_answer,
        )
        if endpoint is None:
            return None
        route = validated_math_route_signature(
            model_response,
            problem,
            gt_answer,
            fast=fast,
            task_verified=True,
        )
        return VerifiedExplorationIdentity(
            verifier="math_verify",
            endpoint_key=f"math-answer:{endpoint}",
            route_signature=route,
        )
    except Exception:
        return None


def answer_tag_reward_fn(model_response, gt_answer, fast=False):
    # We are strict about format to evaluate our models.
    if "</think> <answer>" in model_response and "</answer>" in model_response:
        model_answer = model_response.split("<answer>")[-1].replace("</answer>", "")
        if "\\boxed" in model_answer:
            model_answer = extract_answer(model_answer)
            if model_answer is None:
                return {"formatted": True}, 0.0
        modebench_plain_answer = _extract_modebench_candidate(model_answer, gt_answer)
        if modebench_plain_answer is not None:
            model_answer = modebench_plain_answer
        modebench_correct = _grade_modebench_answer(model_answer, gt_answer)
        if modebench_correct is not None:
            return {"formatted": True}, 1.0 if modebench_correct else 0.0
        if isinstance(gt_answer, float) or isinstance(gt_answer, int):
            gt_answer = str(gt_answer)
        if isinstance(gt_answer, str):
            is_correct = grade(model_answer, gt_answer, fast)
        elif isinstance(gt_answer, list):
            is_correct = False
            for gt in gt_answer:
                is_correct |= grade(model_answer, gt, fast)
        if is_correct:
            return {"formatted": True}, 1.0  # Correctness reward.
        else:
            return (
                {"formatted": True},
                0.0,
            )  # Formatted but wrong answer; no format reward to avoid hacking.
    else:
        return {"formatted": False}, 0.0  # Unformatted.


def answer_tag_reward_fn_for_orz(model_response, gt_answer, fast=False):
    # We are a bit less strict for baselines.
    if "<answer>" in model_response and "</answer>" in model_response:
        model_answer = model_response.split("<answer>")[-1].replace("</answer>", "")
        if "\\boxed" in model_answer:
            model_answer = extract_answer(model_answer)
            if model_answer is None:
                return {"formatted": True}, 0.0
        modebench_plain_answer = _extract_modebench_candidate(model_answer, gt_answer)
        if modebench_plain_answer is not None:
            model_answer = modebench_plain_answer
        modebench_correct = _grade_modebench_answer(model_answer, gt_answer)
        if modebench_correct is not None:
            return {"formatted": True}, 1.0 if modebench_correct else 0.0
        if isinstance(gt_answer, float) or isinstance(gt_answer, int):
            gt_answer = str(gt_answer)
        if isinstance(gt_answer, str):
            is_correct = grade(model_answer, gt_answer, fast)
        elif isinstance(gt_answer, list):
            is_correct = False
            for gt in gt_answer:
                is_correct |= grade(model_answer, gt, fast)
        if is_correct:
            return {"formatted": True}, 1.0  # Correctness reward.
        else:
            return (
                {"formatted": True},
                0.0,
            )  # Formatted but wrong answer; no format reward to avoid hacking.
    else:
        return {"formatted": False}, 0.0  # Unformatted.