File size: 59,086 Bytes
d765c14 | 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 | #!/usr/bin/env python3
"""
Deep Arithmark — the long-horizon tier of ArithMark.
ArithMark 3.0 asks a base model to finish a two-clause word problem whose four
continuations are **adjacent integers** (43 / 44 / 45 / 46). That design has a
measurable shortcut: to reject a wrong option you only need to know that the
answer is "about 44", so magnitude smoothing wins points without arithmetic.
Every item is also one or two dependent operations, which is why the best
sub-1B model (MobileLLM-R1-140M) sits at 65.7 %.
Deep Arithmark keeps ArithMark's contract exactly -- one unfinished sentence,
four continuations with a leading space, one correct index, scored by
length-normalised continuation log-likelihood, chance 25 % -- and changes three
things:
* **Depth.** Every item needs 2-5 *dependent* operations. Later steps consume
the result of earlier steps, so you cannot get the ending by matching a
phrase to a memorised one-step template.
* **Decoys with provenance.** No decoy is "answer ± 1". Every decoy is the
exact value some specific plausible wrong reasoning produces: the state
after step 2 instead of step 4, the percentage applied to the wrong base,
the divisor n instead of n+1, the unit conversion left out, ceil instead of
floor, the a.m./p.m. carry dropped. Each ending therefore has to be judged,
not merely ranked by size. `metadata.option_sources` records, per ending,
which wrong path produced it -- the dataset is auditable, not a black box.
* **Balanced rank, not just balanced position.** ArithMark balances which
slot holds the answer, but leaves the answer's *numeric* rank free, so
"pick the largest" is worth points on the easy tiers. Here the answer's
rank among the four values is balanced too: 25 % of items have it as the
smallest, 25 % as the second, and so on. Picking a magnitude is worth 25 %.
Why this is still fair to a sub-1B model: scoring is pure continuation
log-likelihood (no chain-of-thought, no tools, no generation), items stay under
~45 words, the whole set is 1,000 items, and it is graded in four depth tiers so
a 100M model still has a readable curve to climb instead of a single number
pinned at chance.
Usage
-----
python deeparithmark.py selftest
python deeparithmark.py build --out deeparithmark-dataset/data/deeparithmark-1.jsonl
python deeparithmark.py audit --data deeparithmark-dataset/data/deeparithmark-1.jsonl
Grading a model on it is `bench_deeparithmark.py`; the file below is also scored
unchanged by ArithMark 3.0's own `bencharithmark-3.py --data-path`, because the
record schema is identical.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import random
import statistics
from collections import Counter
from dataclasses import dataclass
from pathlib import Path
from typing import Callable
VERSION = "1.0"
DATASET_NAME = "deeparithmark-1"
DEPTHS = (2, 3, 4, 5)
PER_DEPTH = 250
# ranks are split 62/63/62/63 so each depth still totals exactly PER_DEPTH
RANK_QUOTAS = (62, 63, 62, 63)
# ---------------------------------------------------------------------------
# drafts: what a problem family produces before options are laid out
# ---------------------------------------------------------------------------
@dataclass
class Draft:
"""One generated problem, before decoy selection and slot assignment."""
ctx: str
answer: int
# (kind, value) for every plausible wrong reasoning path we can compute.
# `kind` is a short human-readable description of the mistake.
pool: list[tuple[str, int]]
fmt: Callable[[int], str]
unit: str
topic: str
grade_band: str
difficulty: str
depth: int
steps: list[tuple[str, int]]
# number-valued options need the "no 1" rule (all endings share one plural
# unit, so " 1 boxes." would be ungrammatical *and* a giveaway).
render_is_number: bool = True
NAMES = [
"Amara", "Ben", "Chen", "Dara", "Eli", "Farid", "Greta", "Hana",
"Ivo", "Jae", "Kofi", "Lena", "Milo", "Nia", "Omar", "Priya",
"Quinn", "Rosa", "Samir", "Tara", "Umar", "Vera", "Wes", "Yara",
]
def num(v: int, unit: str) -> str:
return f" {v} {unit}."
def dollars(v: int) -> str:
"""Render an integer number of cents as a dollar amount."""
return f"${v // 100}.{v % 100:02d}"
def money(v: int) -> str:
return f" {dollars(v)}."
def _same_period(
pool: list[tuple[str, int]], window: int
) -> list[tuple[str, int]]:
"""Keep only options inside one half of the day (all a.m., or all p.m.).
Every option in a time item has to carry the same a.m./p.m. marker, or the
marker itself becomes an "odd one out" cue that needs no arithmetic.
"""
low = window * 720
return [(k, v) for k, v in pool if low <= v < low + 720]
def _clock(total_minutes: int) -> str:
"""Render minutes past midnight as a 12-hour clock time."""
minutes = total_minutes % (24 * 60)
hour, minute = divmod(minutes, 60)
suffix = "a.m." if hour < 12 else "p.m."
display = hour % 12 or 12
return f" {display}:{minute:02d} {suffix}"
def _ok_value(v: int) -> bool:
return v >= 0 and v != 1
# ---------------------------------------------------------------------------
# problem families
#
# Each family returns a Draft or None when the random parameters landed on a
# degenerate case (colliding values, non-integer division, an ungrammatical
# option). The caller retries. `steps` is the real computation, so
# `answer == steps[-1][1]` by construction and selftest can assert it.
# ---------------------------------------------------------------------------
def fam_money_discount_fee(rng: random.Random) -> Draft | None:
"""depth 2 - percent off, then a fixed fee (money)."""
price = rng.choice([240, 320, 380, 460, 540, 680, 720, 840, 960])
pct = rng.choice([10, 20, 25, 50])
fee = rng.choice([15, 25, 35, 45, 60])
discount = price * pct // 100
reduced = price - discount
answer = reduced + fee
ctx = (
f"At the fair, a ride pass cost {dollars(price)}. The booth took {pct}% off the pass "
f"and then charged a handling fee of {dollars(fee)}. In total, the pass cost"
)
steps = [
(f"take {pct}% of {price} off: {price} - {discount} = {reduced}", reduced),
(f"add the {fee}-cent fee: {reduced} + {fee} = {answer}", answer),
]
flat = price - pct + fee # read "20%" as "20 cents"
pool = [
("forgot the fee", price - discount),
("forgot the discount", price + fee),
("added the discount instead of removing it", price + discount + fee),
("took the percentage off twice", price - 2 * discount + fee),
("read the percentage as a flat number of cents", flat),
("charged the handling fee twice", reduced + 2 * fee),
(
"took the discount off the fee as well",
(price + fee) - (price + fee) * pct // 100,
),
]
return Draft(
ctx=ctx,
answer=answer,
pool=pool,
fmt=money,
unit="dollars",
topic="money_percent",
grade_band="grades_4_5",
difficulty="medium",
depth=2,
steps=steps,
)
def fam_measure_cm_cut(rng: random.Random) -> Draft | None:
"""depth 2 - metres+centimetres converted, then cut (measurement)."""
meters = rng.randint(2, 6)
extra = rng.choice([12, 25, 38, 47, 55, 68, 74])
cut = rng.choice([45, 60, 75, 90, 115, 130])
total = meters * 100 + extra
answer = total - cut
if answer < 20:
return None
ctx = (
f"A board was {meters} metres and {extra} centimetres long. A worker cut off "
f"{cut} centimetres. The board left was"
)
steps = [
(f"convert metres: {meters} x 100 = {meters * 100} cm", meters * 100),
(f"add the extra centimetres: {meters * 100} + {extra} = {total} cm", total),
(f"subtract the cut: {total} - {cut} = {answer} cm", answer),
]
pool = [
("forgot the extra centimetres", meters * 100 - cut),
("used 10 cm to the metre", meters * 10 + extra - cut),
("used 1000 cm to the metre", meters * 1000 + extra - cut),
("added the cut instead of removing it", total + cut),
("cut a whole metre off as well", total - cut - 100),
("reported the length in whole metres", (answer // 100) * 100),
("subtracted the cut from the centimetres only", meters * 100 + (extra - cut)),
("added the cut and a whole metre", total + cut + 100),
("counted the extra centimetres twice", total + extra - cut),
("stopped ten centimetres short of the cut", total - cut + 10),
]
return Draft(
ctx=ctx,
answer=answer,
pool=pool,
fmt=lambda v: num(v, "centimetres"),
unit="centimetres",
topic="measurement",
grade_band="grades_4_5",
difficulty="medium",
depth=3, # convert, add the extra centimetres, subtract the cut
steps=steps,
)
def fam_time_clock_end(rng: random.Random) -> Draft | None:
"""depth 2 - clock time plus a duration (time)."""
start = rng.randrange(6 * 60, 8 * 60 + 45) # 06:00 .. 08:44
duration = rng.choice([50, 65, 80, 95, 110, 125])
end = start + duration
# keep the whole item inside the morning: every option has to share the
# a.m. marker, or the marker itself becomes an "odd one out" cue
if not 6 * 60 <= end <= 10 * 60 + 50:
return None
ctx = (
f"The hall was booked from {_clock(start).strip()} for {duration} minutes. "
f"The booking ended at"
)
steps = [
(f"convert the start: {start} minutes after midnight", start),
(f"add the duration: {start} + {duration} = {end} minutes", end),
]
def fmt(v: int) -> str:
return _clock(v)
pool = [
("dropped the hour carry", start - (start % 60) + ((start + duration) % 60)),
("added an extra hour", end + 60),
("subtracted the duration instead of adding it", start - duration),
("counted the duration as hours, not minutes", start + duration * 60),
("added the minutes without the hours", start + duration % 60),
("counted the duration as ten minutes an hour", start + duration * 10),
("forgot the last full hour", end - 60),
("ran half an hour long", end + 30),
("stopped a quarter of an hour early", end - 15),
("ran an hour and a half long", end + 90),
]
pool = _same_period(pool, 0)
return Draft(
ctx=ctx,
answer=end,
pool=pool,
fmt=fmt,
unit="clock time",
topic="time",
grade_band="grades_4_5",
difficulty="medium",
depth=2,
steps=steps,
render_is_number=False,
)
def fam_share_then_split(rng: random.Random) -> Draft | None:
"""depth 3 - give away a third, then split the rest (fractions)."""
k = rng.choice([4, 5, 6])
# a larger per-child share keeps the four candidate values far enough apart
# that "about this big" smoothing cannot separate them
share = rng.choice([12, 15, 18, 20, 24])
rest = k * share
# rest must be two thirds of the total
total = rest * 3 // 2
if rest * 3 % 2 or total % 3:
return None
given = total // 3
if given != total - rest:
return None
if total > 400 or given < 6:
return None
baker = rng.choice(NAMES)
noun = rng.choice(["cookies", "muffins", "biscuits", "buns"])
ctx = (
f"{baker} baked {total} {noun}. One third went to a neighbour, and the rest were "
f"split equally among {k} grandchildren. Each grandchild got"
)
describe = noun
steps = [
(f"one third given away: {total} / 3 = {given}", given),
(f"rest kept: {total} - {given} = {rest}", rest),
(f"split among {k}: {rest} / {k} = {share}", share),
]
pool = [
("split all the cookies, not the rest", total // k),
("gave away a half instead of a third", (total - total // 2) // k),
("stopped after giving the third away", rest),
("split the rest among one more child", rest // (k + 1)),
("gave away a third twice", (rest - rest // 3) // k),
("multiplied instead of dividing", rest * k),
("split the given-away cookies too", given // k),
("gave away a half and split among one more child", (total - total // 2) // (k + 1)),
("gave away two thirds", (total - 2 * given) // k),
("split all the cookies among one more child", total // (k + 1)),
("split the rest among twice as many children", rest // (2 * k)),
("gave away two thirds and split among one more child", (total - 2 * given) // (k + 1)),
("gave away a third twice and split among one more child", (rest - rest // 3) // (k + 1)),
("split all the cookies among two more children", total // (k + 2)),
]
return Draft(
ctx=ctx,
answer=share,
pool=pool,
fmt=lambda v: num(v, describe),
unit=describe,
topic="fractions",
grade_band="grades_5_6",
difficulty="hard",
depth=3,
steps=steps,
)
def fam_two_rate_pay(rng: random.Random) -> Draft | None:
"""depth 3 - two different hourly rates (rate/money)."""
h1 = rng.choice([3, 4, 5, 6])
h2 = rng.choice([2, 3, 4])
r1 = rng.choice([900, 1100, 1250, 1400, 1500])
r2 = r1 + rng.choice([200, 300, 400, 500])
part1 = h1 * r1
part2 = h2 * r2
answer = part1 + part2
ctx = (
f"Ravi worked {h1} hours at {dollars(r1)} an hour, and then {h2} hours at "
f"{dollars(r2)} an hour. He earned"
)
steps = [
(f"first stretch: {h1} x {r1} = {part1}", part1),
(f"second stretch: {h2} x {r2} = {part2}", part2),
(f"total pay: {part1} + {part2} = {answer}", answer),
]
pool = [
("paid every hour at the first rate", (h1 + h2) * r1),
("paid every hour at the second rate", (h1 + h2) * r2),
("forgot the second stretch", part1),
("forgot the first stretch", part2),
("swapped the two rates", h1 * r2 + h2 * r1),
("added the rates together", (h1 + h2) * (r1 + r2)),
("worked one hour less in the first stretch", (h1 - 1) * r1 + part2),
("worked one hour less in each stretch", (h1 - 1) * r1 + (h2 - 1) * r2),
("paid the slower rate for the whole day", (h1 + h2) * r1 // 2),
]
return Draft(
ctx=ctx,
answer=answer,
pool=pool,
fmt=money,
unit="dollars",
topic="rate_pay",
grade_band="grades_5_6",
difficulty="hard",
depth=3,
steps=steps,
)
def fam_mix_split(rng: random.Random) -> Draft | None:
"""depth 3 - mixed basket, then split (money)."""
a = rng.choice([4, 5, 6, 7, 8])
b = rng.choice([3, 4, 5, 6])
x = rng.choice([45, 60, 75, 80, 95, 120])
y = rng.choice([30, 35, 50, 65, 70])
friends = rng.choice([2, 3, 4, 5])
total = a * x + b * y
people = friends + 1
if total % people:
return None
answer = total // people
if answer < 4:
return None
ctx = (
f"Priya bought {a} markers at {dollars(x)} each and {b} erasers at {dollars(y)} "
f"each. She split the total cost equally between herself and {friends} friends. "
f"Each person paid"
)
steps = [
(f"markers: {a} x {x} = {a * x}", a * x),
(f"erasers: {b} x {y} = {b * y}", b * y),
(f"total cost: {a * x} + {b * y} = {total}", total),
(f"split between {people} people: {total} / {people} = {answer}", answer),
]
pool = [
("split only between the friends", total // friends),
("divided by one person too few", total // (people - 1)),
("forgot the erasers", (a * x) // people),
("charged the marker price for everything", ((a + b) * x) // people),
("swapped the two unit prices", (a * y + b * x) // people),
("did not split the total at all", total),
("added the unit prices instead of multiplying", (a * (x + 1) + b * (y + 1)) // people),
("split among one more person", total // (people + 1)),
("bought one extra of each item", ((a + 1) * x + (b + 1) * y) // people),
("split among two more people", total // (people + 2)),
]
return Draft(
ctx=ctx,
answer=answer,
pool=pool,
fmt=money,
unit="dollars",
topic="money",
grade_band="grades_5_6",
difficulty="hard",
depth=4, # two products, a sum, then the split
steps=steps,
)
def fam_stock_percent_pack(rng: random.Random) -> Draft | None:
"""depth 3 - sell a percentage, pack the rest (percent / packing)."""
stock = rng.choice([240, 280, 320, 360, 400, 440, 480])
pct = rng.choice([15, 25, 30, 40, 55])
crate = rng.choice([6, 7, 8, 9, 12])
sold = stock * pct // 100
rest = stock - sold
answer = rest // crate
if answer < 3:
return None
ctx = (
f"A shop had {stock} shirts. It sold {pct}% of them, then packed the rest into "
f"boxes of {crate}. The number of full boxes filled was"
)
steps = [
(f"sold: {pct}% of {stock} = {sold}", sold),
(f"left over: {stock} - {sold} = {rest}", rest),
(f"full boxes: {rest} / {crate} = {answer} (remainder {rest % crate})", answer),
]
pool = [
("packed the whole stock, not the rest", stock // crate),
("packed the sold shirts", sold // crate),
("rounded the box count up", -(-rest // crate)),
("sold twice as many", (stock - 2 * sold) // crate),
("took the percentage off the remainder again", (rest * (100 - pct) // 100) // crate),
("divided by the number of boxes left over", rest // max(1, rest % crate)),
("counted the loose shirts as a box", rest // crate + 1),
("sold half the stock regardless of the percentage", (stock - stock // 2) // crate),
("sold only a tenth of the stock", (stock - stock // 10) // crate),
]
return Draft(
ctx=ctx,
answer=answer,
pool=pool,
fmt=lambda v: num(v, "boxes"),
unit="boxes",
topic="percent",
grade_band="grades_6",
difficulty="hard",
depth=3,
steps=steps,
)
def fam_inventory_boxes(rng: random.Random) -> Draft | None:
"""depth 4 - receive, ship, damage, then pack (multi-step)."""
start = rng.choice([420, 480, 560, 620, 700, 760, 840])
add = rng.choice([130, 180, 240, 260, 310])
ship = rng.choice([90, 140, 170, 210, 250])
damaged = rng.choice([12, 18, 24, 32, 40])
crate = rng.choice([8, 9, 12, 14, 16])
after_add = start + add
after_ship = after_add - ship
good = after_ship - damaged
answer = good // crate
if answer < 3 or good < 30:
return None
ctx = (
f"A warehouse held {start} units. A delivery added {add}, then {ship} units were "
f"shipped out, and {damaged} were found damaged. The rest were packed into crates "
f"of {crate}. The number of full crates packed was"
)
steps = [
(f"after delivery: {start} + {add} = {after_add}", after_add),
(f"after shipping: {after_add} - {ship} = {after_ship}", after_ship),
(f"good units: {after_ship} - {damaged} = {good}", good),
(f"full crates: {good} / {crate} = {answer} (remainder {good % crate})", answer),
]
pool = [
("forgot the damaged units", after_ship // crate),
("forgot the shipping", (after_add - damaged) // crate),
("added the damaged units", (after_ship + damaged) // crate),
("shipped out twice", (after_add - 2 * ship - damaged) // crate),
("counted the loose units as a crate", good // crate + 1),
("stopped before packing", good),
("packed the arriving units only", (add - damaged) // crate),
("packed into larger crates", good // (crate + 1)),
("shipped twice and damaged twice", (after_add - 2 * ship - 2 * damaged) // crate),
("forgot the delivery", (start - ship - damaged) // crate),
]
return Draft(
ctx=ctx,
answer=answer,
pool=pool,
fmt=lambda v: num(v, "crates"),
unit="crates",
topic="multi_step_inventory",
grade_band="grades_6_7",
difficulty="hard",
depth=4,
steps=steps,
)
def fam_trip_minutes(rng: random.Random) -> Draft | None:
"""depth 4 - two legs at different speeds plus a rest (rate/time)."""
v1 = rng.choice([12, 15, 18, 20])
v2 = rng.choice([4, 5, 6])
d1 = v1 * rng.choice([1, 2, 3])
d2 = v2 * rng.choice([1, 2, 3])
rest = rng.choice([12, 15, 20, 25, 30])
t1 = 60 * d1 // v1
t2 = 60 * d2 // v2
answer = t1 + rest + t2
if answer < 20 or (d1 + d2) < 6:
return None
ctx = (
f"Nadia cycled {d1} km at {v1} km/h, rested {rest} minutes, then walked {d2} km "
f"at {v2} km/h. Her total time, in minutes, was"
)
steps = [
(f"cycling time: 60 x {d1} / {v1} = {t1} minutes", t1),
(f"walking time: 60 x {d2} / {v2} = {t2} minutes", t2),
(f"add the rest: {t1} + {rest} + {t2} = {answer} minutes", answer),
]
pool = [
("forgot the rest", t1 + t2),
("counted the rest twice", t1 + 2 * rest + t2),
("counted the rest as hours", t1 + t2 + 60 * rest),
("used the cycling speed for both legs", 60 * (d1 + d2) // v1 + rest),
("used the walking speed for both legs", 60 * (d1 + d2) // v2 + rest),
("forgot the walking leg", t1 + rest),
("divided by the speed twice", (t1 + t2) // max(1, v2) + rest),
]
return Draft(
ctx=ctx,
answer=answer,
pool=pool,
fmt=lambda v: num(v, "minutes"),
unit="minutes",
topic="rate_time",
grade_band="grades_6_7",
difficulty="hard",
depth=3, # cycling time, walking time, then add the rest
steps=steps,
)
def fam_discount_tax_coupon_split(rng: random.Random) -> Draft | None:
"""depth 4 - discount, tax, coupon, then split (percent/money)."""
price = rng.choice([1200, 1600, 2000, 2400, 2800, 3600])
pct = rng.choice([10, 20, 25, 30])
tax = rng.choice([5, 8, 10, 15])
coupon = rng.choice([40, 60, 80, 120])
group = rng.choice([2, 3, 4, 5])
discount = price * pct // 100
reduced = price - discount
taxed = reduced * (100 + tax)
if taxed % 100:
return None
taxed //= 100
total = taxed - coupon
if total <= 0 or total % group:
return None
answer = total // group
if answer < 4:
return None
ctx = (
f"An order cost {dollars(price)}. A {pct}% discount came off it, then {tax}% tax "
f"was added to the discounted price, and a {dollars(coupon)} coupon was applied "
f"last. {group} people split the final cost equally. Each paid"
)
steps = [
(f"discount: {price} - {discount} = {reduced}", reduced),
(f"tax on the discounted price: {reduced} + {taxed - reduced} = {taxed}", taxed),
(f"coupon: {taxed} - {coupon} = {total}", total),
(f"split {group} ways: {total} / {group} = {answer}", answer),
]
pool = [
("forgot the coupon", taxed // group),
("forgot the discount", ((price * (100 + tax) // 100) - coupon) // group),
(
"taxed the price before the discount",
(((price * (100 + tax) // 100) * (100 - pct) // 100) - coupon) // group,
),
("forgot the discount and the coupon", (price * (100 + tax) // 100) // group),
("split the total among one fewer person", total // (group - 1) if group > 1 else total),
("did not split the cost at all", total),
("added the coupon instead of subtracting it", (taxed + coupon) // group),
("split the price before the discount", price // group),
("used the coupon twice", (taxed - 2 * coupon) // group),
("split the total among one more person", total // (group + 1)),
(
"applied the discount twice",
(((price - 2 * discount) * (100 + tax) // 100) - coupon) // group,
),
]
return Draft(
ctx=ctx,
answer=answer,
pool=pool,
fmt=money,
unit="dollars",
topic="percent_money",
grade_band="grades_7_8",
difficulty="hard",
depth=4,
steps=steps,
)
def fam_tank_fill(rng: random.Random) -> Draft | None:
"""depth 4 - two fill stages, then a drain (rate)."""
start = rng.choice([120, 180, 240, 300])
r1 = rng.choice([6, 9, 12, 15])
t1 = rng.choice([4, 6, 8, 10])
r2 = rng.choice([3, 5, 7])
t2 = rng.choice([5, 7, 9])
drain = rng.choice([25, 40, 55, 70])
stage1 = r1 * t1
stage2 = r2 * t2
filled = start + stage1 + stage2
answer = filled - drain
if answer < 30:
return None
ctx = (
f"A tank held {start} litres. A pipe added {r1} litres per minute for {t1} minutes, "
f"then {r2} litres per minute for {t2} minutes. A drain then removed {drain} litres. "
f"The tank then held"
)
steps = [
(f"first fill: {r1} x {t1} = {stage1} litres", stage1),
(f"second fill: {r2} x {t2} = {stage2} litres", stage2),
(f"before draining: {start} + {stage1} + {stage2} = {filled}", filled),
(f"after draining: {filled} - {drain} = {answer}", answer),
]
pool = [
("forgot the drain", filled),
("added the drain instead of removing it", filled + drain),
("forgot the second fill", start + stage1 - drain),
("forgot the first fill", start + stage2 - drain),
("used the first rate for both stages", start + r1 * (t1 + t2) - drain),
("added the rates and multiplied once", start + (r1 + r2) * (t1 + t2) - drain),
("drained twice", filled - 2 * drain),
]
return Draft(
ctx=ctx,
answer=answer,
pool=pool,
fmt=lambda v: num(v, "litres"),
unit="litres",
topic="rate",
grade_band="grades_6_7",
difficulty="hard",
depth=4,
steps=steps,
)
def fam_schedule_sessions(rng: random.Random) -> Draft | None:
"""depth 4 - two sessions and a break across the hour (time)."""
start = rng.randrange(6 * 60, 8 * 60 + 30)
m1 = rng.choice([45, 50, 55, 60, 70])
brk = rng.choice([10, 15, 20, 25])
m2 = rng.choice([35, 40, 45, 50])
end = start + m1 + brk + m2
if not 6 * 60 <= end <= 10 * 60 + 45:
return None
ctx = (
f"Rehearsal began at {_clock(start).strip()}. The first session lasted {m1} minutes, "
f"the break lasted {brk} minutes, and the second session lasted {m2} minutes. "
f"Rehearsal ended at"
)
steps = [
(f"after the first session: {start} + {m1} = {start + m1} minutes after midnight", start + m1),
(f"after the break: {start + m1} + {brk} = {start + m1 + brk}", start + m1 + brk),
(f"after the second session: {start + m1 + brk} + {m2} = {end}", end),
]
def fmt(v: int) -> str:
return _clock(v)
pool = [
("forgot the break", start + m1 + m2),
("counted the break twice", end + brk),
("forgot the second session", start + m1 + brk),
("counted the first session twice", start + 2 * m1 + brk + m2),
("counted the break as hours, not minutes", end + brk * 60),
("dropped the hour carry", start - (start % 60) + (end % 60)),
("added the minutes but not the hours", start + (m1 + brk + m2) % 60),
("counted the first session as hours, not minutes", start + m1 * 60 + brk + m2),
("finished half an hour late on top of the break", end + brk + 30),
("forgot the last session and the break", start + m1),
]
pool = _same_period(pool, 0)
return Draft(
ctx=ctx,
answer=end,
pool=pool,
fmt=fmt,
unit="clock time",
topic="time",
grade_band="grades_6_7",
difficulty="hard",
depth=3, # three dependent additions across the hour
steps=steps,
render_is_number=False,
)
def fam_salary_overtime_tax(rng: random.Random) -> Draft | None:
"""depth 5 - base pay, overtime at 1.5x, bonus, then tax (money)."""
hours = rng.choice([32, 36, 38, 40])
ot_hours = rng.choice([4, 6, 8, 10])
rate = rng.choice([1200, 1400, 1600, 1800, 2000])
bonus = rng.choice([2000, 3000, 4000, 5000])
tax = rng.choice([10, 15, 20, 25])
base = hours * rate
ot_rate = rate * 3 // 2
overtime = ot_hours * ot_rate
gross = base + overtime + bonus
if gross * tax % 100:
return None
withheld = gross * tax // 100
answer = gross - withheld
ctx = (
f"Jo worked {hours} regular hours at {dollars(rate)} an hour and {ot_hours} "
f"overtime hours at one and a half times that rate. A {dollars(bonus)} bonus was "
f"added, and then {tax}% of the total was withheld for tax. Jo took home"
)
steps = [
(f"regular pay: {hours} x {rate} = {base}", base),
(f"overtime rate: {rate} x 1.5 = {ot_rate}", ot_rate),
(f"overtime pay: {ot_hours} x {ot_rate} = {overtime}", overtime),
(f"gross with bonus: {base} + {overtime} + {bonus} = {gross}", gross),
(f"take-home: {gross} - {withheld} = {answer}", answer),
]
gross_no_bonus = base + overtime
pool = [
("forgot the tax", gross),
("added the tax instead of withholding it", gross + withheld),
("forgot the bonus", gross_no_bonus - gross_no_bonus * tax // 100),
("paid overtime at the normal rate", (base + ot_hours * rate + bonus) - (base + ot_hours * rate + bonus) * tax // 100),
("taxed only the regular pay", gross - base * tax // 100),
("paid overtime at double rate", (base + 2 * ot_hours * rate + bonus) - (base + 2 * ot_hours * rate + bonus) * tax // 100),
("forgot the overtime", (base + bonus) - (base + bonus) * tax // 100),
("taxed twice", gross - 2 * withheld),
]
return Draft(
ctx=ctx,
answer=answer,
pool=pool,
fmt=money,
unit="dollars",
topic="money_rate",
grade_band="grades_7_8",
difficulty="hard",
depth=5,
steps=steps,
)
def fam_inventory_percent_chain(rng: random.Random) -> Draft | None:
"""depth 5 - two percentage days, then palletising."""
stock = rng.choice([600, 800, 1000, 1200, 1400, 1600])
p1 = rng.choice([10, 20, 25, 30])
p2 = rng.choice([10, 20, 25, 40])
pallet = rng.choice([8, 10, 12, 15])
monday = stock * p1 // 100
rem1 = stock - monday
tuesday = rem1 * p2 // 100
rem2 = rem1 - tuesday
answer = rem2 // pallet
if answer < 3 or rem2 < 40:
return None
ctx = (
f"A depot held {stock} sacks. It sent out {p1}% of them on Monday and {p2}% of the "
f"remainder on Tuesday. The rest were stacked on pallets of {pallet}. "
f"The number of full pallets was"
)
steps = [
(f"Monday: {p1}% of {stock} = {monday}", monday),
(f"left after Monday: {stock} - {monday} = {rem1}", rem1),
(f"Tuesday: {p2}% of {rem1} = {tuesday}", tuesday),
(f"left after Tuesday: {rem1} - {tuesday} = {rem2}", rem2),
(f"full pallets: {rem2} / {pallet} = {answer}", answer),
]
pool = [
(
"took both percentages off the original stock",
(stock - stock * p1 // 100 - stock * p2 // 100) // pallet,
),
("forgot Tuesday", rem1 // pallet),
("forgot Monday", (stock - tuesday) // pallet),
(
"took the second percentage off the original stock",
(rem1 - stock * p2 // 100) // pallet,
),
("counted the loose sacks as a pallet", rem2 // pallet + 1),
("stopped before palletising", rem2),
("stacked on larger pallets", rem2 // (pallet + 1)),
("added the two percentages", (stock - stock * (p1 + p2) // 100) // pallet),
("took both percentages twice", (stock - 2 * monday - 2 * tuesday) // pallet),
]
return Draft(
ctx=ctx,
answer=answer,
pool=pool,
fmt=lambda v: num(v, "pallets"),
unit="pallets",
topic="percent_multi_step",
grade_band="grades_7_8",
difficulty="hard",
depth=5, # two percentage days, then palletising
steps=steps,
)
def fam_prize_ratio_charity(rng: random.Random) -> Draft | None:
"""depth 5 - fee, ratio split, charity cut, then split among players."""
parts_a = rng.choice([2, 3, 4, 5])
parts_b = rng.choice([1, 2, 3])
if parts_a <= parts_b:
return None
unit = rng.choice([30, 40, 50, 60, 70])
fee = rng.choice([200, 300, 400, 500])
charity = rng.choice([10, 20, 25, 50])
players = rng.choice([4, 5, 8])
prize = (parts_a + parts_b) * unit + fee
share = parts_a * unit
charity_cut = share * charity // 100
kept = share - charity_cut
if kept % players or kept == 0:
return None
answer = kept // players
if answer < 4:
return None
ctx = (
f"A prize of {dollars(prize)} was split between two teams in the ratio "
f"{parts_a}:{parts_b} after a {dollars(fee)} fee was deducted. The larger team gave "
f"{charity}% of its share to charity and split the rest equally among its {players} "
f"players. Each player got"
)
steps = [
(f"after the fee: {prize} - {fee} = {prize - fee}", prize - fee),
(f"one ratio part: {prize - fee} / {parts_a + parts_b} = {unit}", unit),
(f"larger share: {parts_a} x {unit} = {share}", share),
(f"after charity: {share} - {charity_cut} = {kept}", kept),
(f"per player: {kept} / {players} = {answer}", answer),
]
pre_fee = prize // (parts_a + parts_b)
pool = [
("forgot to deduct the fee", (pre_fee * parts_a) // players),
("gave the larger share to the smaller ratio", (parts_b * unit) // players),
("forgot the charity cut", share // players),
("split the whole prize among one team", (prize - fee) // players),
("divided between the teams instead of the players", kept // 2),
(
"took the charity cut off the whole prize",
((prize - fee) - (prize - fee) * charity // 100) // players,
),
(
"swapped the ratio parts",
((parts_b * unit) - (parts_b * unit) * charity // 100) // players,
),
("split among one more player", kept // (players + 1)),
("gave twice the share away to charity", (share - 2 * charity_cut) // players),
("forgot the fee and the charity cut", ((prize - fee) // 2) // players),
]
return Draft(
ctx=ctx,
answer=answer,
pool=pool,
fmt=money,
unit="dollars",
topic="ratio",
grade_band="grades_7_8",
difficulty="hard",
depth=5,
steps=steps,
)
FAMILIES: dict[int, list[Callable[[random.Random], Draft | None]]] = {
2: [fam_money_discount_fee, fam_time_clock_end],
3: [
fam_measure_cm_cut,
fam_share_then_split,
fam_two_rate_pay,
fam_stock_percent_pack,
fam_trip_minutes,
fam_schedule_sessions,
],
4: [
fam_inventory_boxes,
fam_discount_tax_coupon_split,
fam_tank_fill,
fam_mix_split,
],
5: [fam_salary_overtime_tax, fam_inventory_percent_chain, fam_prize_ratio_charity],
}
# ---------------------------------------------------------------------------
# assembling four options from a draft
# ---------------------------------------------------------------------------
@dataclass
class Assembled:
draft: Draft
decoys: list[tuple[str, int]] # exactly 3 wrong-path (kind, value) pairs
@property
def rank(self) -> int:
"""0 = answer is the smallest of the four, 3 = the largest."""
answer = self.draft.answer
return sum(1 for _, v in self.decoys if v < answer)
def slots(self, label: int) -> tuple[list[int], list[str]]:
"""Lay the answer at `label` and the decoys in the remaining slots."""
values: list[int] = []
sources: list[str] = []
remaining = list(self.decoys)
for slot in range(4):
if slot == label:
values.append(self.draft.answer)
sources.append("correct")
else:
kind, value = remaining.pop(0)
values.append(value)
sources.append(kind)
return values, sources
def roundness(v: int) -> int:
"""How "prototypical" a number looks: trailing zeros, capped at 3."""
if v == 0:
return 3
score = 0
while v % 10 == 0 and score < 3:
v //= 10
score += 1
return score
def _implausible(value: int, answer: int) -> bool:
"""Reject decoys a reader would eliminate without doing any arithmetic.
A decoy that is an order of magnitude off, or several powers of ten rounder
than the answer, is not a reasoning trap -- it is a surface cue, and a base
model will simply pick whichever option looks most prototypical. Both cases
showed up in error analysis (gpt2 picked a "roundest option" on 84 % of
items and scored far below chance as a result).
"""
if answer > 0 and (value > 4 * answer or value * 4 < answer):
return True
# Same roundness class as the answer. A number's "naturalness" (trailing
# zeros) is the one surface feature a base model reliably smooths toward, so
# if the correct option is systematically the least round one, a model that
# cannot compute scores *below* chance. Keeping all four in one class makes
# the options exchangeable under the model's no-skill prior.
return roundness(value) != roundness(answer)
def _too_clustered(values: list[int]) -> bool:
"""Reject option sets where three or more values are consecutive integers.
One near-miss is a legitimate boundary error (floor vs ceil). A whole run of
adjacent integers is ArithMark 3.0's shortcut and is what we are removing.
"""
ordered = sorted(values)
gaps_of_one = sum(1 for a, b in zip(ordered, ordered[1:]) if b - a == 1)
return gaps_of_one >= 2
def assemble(
draft: Draft, rng: random.Random, target_rank: int, max_tries: int = 40
) -> Assembled | None:
"""Pick three wrong-path values so the answer lands at `target_rank`."""
answer = draft.answer
seen: set[int] = set()
pool: list[tuple[str, int]] = []
for kind, value in draft.pool:
if not isinstance(value, int) or value == answer or value in seen:
continue
if draft.render_is_number and not _ok_value(value):
continue
if _implausible(value, answer):
continue
seen.add(value)
pool.append((kind, value))
below = [(k, v) for k, v in pool if v < answer]
above = [(k, v) for k, v in pool if v > answer]
want_below = target_rank
want_above = 3 - target_rank
if len(below) < want_below or len(above) < want_above:
return None
for _ in range(max_tries):
chosen = rng.sample(below, want_below) + rng.sample(above, want_above)
values = [answer] + [v for _, v in chosen]
if len(set(values)) != 4:
continue
if draft.render_is_number and any(not _ok_value(v) for v in values):
continue
if _too_clustered(values):
continue
return Assembled(draft=draft, decoys=chosen)
return None
# ---------------------------------------------------------------------------
# dataset build
# ---------------------------------------------------------------------------
def _activity_label(draft: Draft) -> str:
return (
f"deeparithmark::{DATASET_NAME}::{draft.topic}::"
f"depth{draft.depth}::{draft.difficulty}"
)
def _record(a: Assembled, index: int, label: int, template_id: str) -> dict:
d = a.draft
values, sources = a.slots(label)
endings = [d.fmt(v) for v in values]
assert sources[label] == "correct"
assert values[label] == d.answer
return {
"ind": index,
"activity_label": _activity_label(d),
"ctx_a": d.ctx,
"ctx_b": "",
"ctx": d.ctx,
"endings": endings,
"source_id": f"deeparithmark_v1_{d.topic}_depth{d.depth}_{index:04d}",
"split": "test",
"split_type": "synthetic",
"label": str(label),
"metadata": {
"answer": str(d.answer),
"unit": d.unit,
"topic": d.topic,
"difficulty": d.difficulty,
"grade_band": d.grade_band,
"template_id": template_id,
"depth": d.depth,
"option_sources": sources,
"solution_steps": [text for text, _ in d.steps],
"option_values": values,
"answer_rank": a.rank,
"format_note": (
"Continuation-style prompt for base-model log-likelihood scoring; "
"endings include leading spaces and share one unit phrase."
),
},
}
def template_id_for(fn: Callable) -> str:
return fn.__name__.removeprefix("fam_")
def build(seed: int = 20261027, total_depths: int = PER_DEPTH) -> list[dict]:
"""Generate the balanced dataset, deterministically for a given seed."""
rng = random.Random(seed)
records: list[dict] = []
used_ctx: set[str] = set()
shortfall: Counter = Counter()
index = 0
for depth in DEPTHS:
families = FAMILIES[depth]
slot_rotation = 0
for rank, quota in enumerate(RANK_QUOTAS):
need = round(quota * total_depths / PER_DEPTH)
produced = 0
# stagger which family leads each rank bucket, so no topic is
# confined to one rank, then split the cell evenly across families
rotation = rank % len(families)
order = families[rotation:] + families[:rotation]
shares = [need // len(order)] * len(order)
for i in range(need - sum(shares)):
shares[i] += 1
for family, want in zip(order, shares):
got = 0
attempts = 0
while got < want and attempts < 8000:
attempts += 1
draft = family(rng)
if draft is None:
continue
a = assemble(draft, rng, rank)
if a is None:
continue
if draft.ctx in used_ctx:
continue
if not draft.steps or draft.steps[-1][1] != draft.answer:
raise AssertionError(
f"{family.__name__} produced an inconsistent chain"
)
used_ctx.add(draft.ctx)
# the answer slot rotates so label counts stay flat per depth
label = slot_rotation % 4
slot_rotation += 1
records.append(_record(a, index, label, template_id_for(family)))
index += 1
got += 1
produced += 1
# a family that cannot reach this rank hands its share to the others
attempts = 0
while produced < need and attempts < 60000:
attempts += 1
family = order[attempts % len(order)]
draft = family(rng)
if draft is None:
continue
a = assemble(draft, rng, rank)
if a is None or draft.ctx in used_ctx:
continue
if not draft.steps or draft.steps[-1][1] != draft.answer:
raise AssertionError(
f"{family.__name__} produced an inconsistent chain"
)
used_ctx.add(draft.ctx)
label = slot_rotation % 4
slot_rotation += 1
records.append(_record(a, index, label, template_id_for(family)))
index += 1
produced += 1
if produced < need:
shortfall[(depth, rank)] = need - produced
if shortfall:
raise RuntimeError(
"could not fill every (depth, rank) cell; widen the parameter ranges: "
f"{dict(shortfall)}"
)
rng.shuffle(records)
for i, rec in enumerate(records):
rec["ind"] = i
rec["source_id"] = (
f"deeparithmark_v1_{rec['metadata']['topic']}_"
f"depth{rec['metadata']['depth']}_{i:04d}"
)
return records
# ---------------------------------------------------------------------------
# validation
# ---------------------------------------------------------------------------
def load_jsonl(path: Path) -> list[dict]:
out = []
with path.open(encoding="utf-8-sig") as fh:
for line_no, line in enumerate(fh, 1):
if not line.strip():
continue
try:
out.append(json.loads(line))
except json.JSONDecodeError as exc:
raise ValueError(f"{path}:{line_no}: invalid JSON") from exc
return out
def validate(records: list[dict], verbose: bool = True) -> dict:
"""Assert every structural invariant the benchmark claims to have."""
problems: list[str] = []
ctx_seen: Counter = Counter()
depth_c: Counter = Counter()
rank_c: Counter = Counter()
label_c: Counter = Counter()
topic_c: Counter = Counter()
template_c: Counter = Counter()
grid: Counter = Counter()
adjacent_items = 0
for rec in records:
rid = rec.get("ind")
ctx = rec.get("ctx")
endings = rec.get("endings")
try:
label = int(rec.get("label"))
except (TypeError, ValueError):
problems.append(f"{rid}: label is not an int")
continue
if not isinstance(ctx, str) or not ctx.strip():
problems.append(f"{rid}: empty ctx")
continue
if not isinstance(endings, list) or len(endings) != 4:
problems.append(f"{rid}: expected exactly 4 endings")
continue
if not 0 <= label < 4:
problems.append(f"{rid}: label out of range")
continue
if not all(isinstance(e, str) and e.startswith(" ") for e in endings):
problems.append(f"{rid}: an ending lost its leading space")
if len(set(endings)) != 4:
problems.append(f"{rid}: duplicate endings")
# every option must share the unit phrase: strip the leading number/time
tails = {_unit_of(e) for e in endings}
if len(tails) != 1:
problems.append(f"{rid}: options have different unit phrases {tails}")
if re_has_value_one(endings):
problems.append(f"{rid}: option value 1 with a plural unit")
meta = rec["metadata"]
values = meta.get("option_values")
if not isinstance(values, list) or len(values) != 4:
problems.append(f"{rid}: option_values missing")
values = None
elif int(meta["answer"]) != values[label]:
problems.append(f"{rid}: label does not point at the answer value")
if values:
rank = sum(1 for v in values if v < values[label])
if rank != meta.get("answer_rank"):
problems.append(f"{rid}: answer_rank does not match values")
ordered = sorted(values)
if sum(1 for a, b in zip(ordered, ordered[1:]) if b - a == 1) >= 2:
adjacent_items += 1
problems.append(f"{rid}: options cluster on consecutive integers")
if len(set(values)) != 4:
problems.append(f"{rid}: duplicate option values")
sources = meta.get("option_sources")
if not isinstance(sources, list) or len(sources) != 4:
problems.append(f"{rid}: option_sources missing")
elif sources[label] != "correct":
problems.append(f"{rid}: option_sources is not aligned with the label")
if not meta.get("depth") in DEPTHS:
problems.append(f"{rid}: bad depth")
steps = meta.get("solution_steps")
if not steps:
problems.append(f"{rid}: missing solution_steps")
elif len(steps) != meta.get("depth"):
problems.append(
f"{rid}: {len(steps)} solution steps but declared depth {meta.get('depth')}"
)
ctx_seen[ctx] += 1
depth_c[meta.get("depth")] += 1
rank_c[meta.get("answer_rank")] += 1
label_c[label] += 1
topic_c[meta.get("topic")] += 1
template_c[meta.get("template_id")] += 1
grid[(meta.get("depth"), meta.get("answer_rank"), label)] += 1
dupes = [c for c, n in ctx_seen.items() if n > 1]
if dupes:
problems.append(f"{len(dupes)} duplicated prompts")
n = len(records)
balance = {
"n": n,
"depth": dict(sorted(depth_c.items())),
"rank": dict(sorted(rank_c.items())),
"label": dict(sorted(label_c.items())),
"topic": dict(sorted(topic_c.items())),
"templates": len(template_c),
"worst_grid_cell": min(grid.values()) if grid else 0,
"best_grid_cell": max(grid.values()) if grid else 0,
"adjacent_option_items": adjacent_items,
}
if verbose:
print(f"items: {n}")
print(f"depth: {balance['depth']}")
print(f"answer rank: {balance['rank']}")
print(f"label slot: {balance['label']}")
print(f"topics: {balance['topic']}")
print(f"templates: {balance['templates']}")
print(
f"(depth, rank, slot) grid: {balance['worst_grid_cell']}"
f"..{balance['best_grid_cell']} items per cell"
)
print(f"options clustering on consecutive ints: {adjacent_items} items")
if problems:
print(f"\nPROBLEMS ({len(problems)}):")
for p in problems[:20]:
print(" -", p)
return {"problems": problems, "balance": balance}
def _unit_of(ending: str) -> str:
"""The part of an ending after its leading numeric/time token."""
text = ending.strip()
parts = text.split(" ")
return " ".join(parts[1:]) if len(parts) > 1 else ""
def re_has_value_one(endings: list[str]) -> bool:
for e in endings:
head = e.strip().split(" ")[0]
if head == "1":
return True
return False
# ---------------------------------------------------------------------------
# shortcut audit: prove the options cannot be gamed without arithmetic
# ---------------------------------------------------------------------------
def audit(records: list[dict], seeds: int = 5) -> dict:
"""Measure what a model can score without doing any arithmetic.
Baselines that need no reasoning at all (pick largest / pick a fixed slot /
pick the longest string) plus a trained character-n-gram classifier over the
option text. If the last one clears ~25 % the option strings leak the answer
and the benchmark is broken, whatever the model scores say.
"""
import numpy as np
n = len(records)
report: dict = {}
def acc(picker) -> float:
hits = 0
for rec in records:
if picker(rec) == int(rec["label"]):
hits += 1
return 100.0 * hits / n
def numeric(rec):
return rec["metadata"].get("option_values")
def pick_largest(rec):
v = numeric(rec)
return max(range(4), key=lambda i: v[i]) if v else 0
def pick_smallest(rec):
v = numeric(rec)
return min(range(4), key=lambda i: v[i]) if v else 0
def pick_median(rec):
v = numeric(rec)
if not v:
return 0
order = sorted(range(4), key=lambda i: v[i])
return order[1]
def pick_roundest(rec):
values = numeric(rec)
if not values:
return 0
return max(range(4), key=lambda i: roundness(values[i]))
def pick_longest(rec):
return max(range(4), key=lambda i: len(rec["endings"][i]))
def pick_shortest(rec):
return min(range(4), key=lambda i: len(rec["endings"][i]))
report["pick_largest"] = acc(pick_largest)
report["pick_smallest"] = acc(pick_smallest)
report["pick_second_smallest"] = acc(pick_median)
report["pick_roundest"] = acc(pick_roundest)
report["pick_longest"] = acc(pick_longest)
report["pick_shortest"] = acc(pick_shortest)
report["fixed_slot"] = [
acc(lambda rec, s=s: s) for s in range(4)
]
# character n-gram logistic regression over the option text only
def features(text: str) -> np.ndarray:
text = text.strip().lower()
grams = [text[i : i + 3] for i in range(max(1, len(text) - 2))]
grams += [f"#{g}" for g in text.split(" ")[0][:4]]
return grams
def run_probe(seed: int) -> float:
rng = random.Random(seed)
idx = list(range(n))
rng.shuffle(idx)
cut = int(0.7 * n)
train, test = idx[:cut], idx[cut:]
vocab: dict[str, int] = {}
X, y = [], []
for i in train:
rec = records[i]
for slot in range(4):
y.append(1 if slot == int(rec["label"]) else 0)
X.append(features(rec["endings"][slot]))
for gs in X:
for g in gs:
if g not in vocab:
vocab[g] = len(vocab)
dim = len(vocab) + 1
Xm = np.zeros((len(X), dim), dtype=np.float32)
for r, gs in enumerate(X):
for g in gs:
Xm[r, vocab[g]] += 1.0
Xm[:, -1] = 1.0 # bias
Xm /= np.maximum(1.0, Xm.sum(axis=1, keepdims=True))
ym = np.array(y, dtype=np.float32)
w = np.zeros(dim, dtype=np.float32)
lr, l2 = 0.5, 1e-4
for _ in range(300):
p = 1.0 / (1.0 + np.exp(-(Xm @ w)))
grad = Xm.T @ (p - ym) / len(ym) + l2 * w
w -= lr * grad
hits = 0
for i in test:
rec = records[i]
scores = []
for slot in range(4):
gs = features(rec["endings"][slot])
vec = np.zeros(dim, dtype=np.float32)
for g in gs:
if g in vocab:
vec[vocab[g]] += 1.0
vec[-1] = 1.0
vec /= max(1.0, vec.sum())
scores.append(float(vec @ w))
if max(range(4), key=lambda s: scores[s]) == int(rec["label"]):
hits += 1
return 100.0 * hits / len(test)
probe = [run_probe(1000 + s) for s in range(seeds)]
report["ngram_probe"] = probe
report["ngram_probe_mean"] = statistics.mean(probe)
report["ngram_probe_max"] = max(probe)
report["chance"] = 25.0
print("\nshortcut audit (chance = 25.00%)")
print(f" pick largest value {report['pick_largest']:6.2f}%")
print(f" pick smallest value {report['pick_smallest']:6.2f}%")
print(f" pick second smallest {report['pick_second_smallest']:6.2f}%")
print(f" pick roundest number {report['pick_roundest']:6.2f}%")
print(f" pick longest option text {report['pick_longest']:6.2f}%")
print(f" pick shortest option text {report['pick_shortest']:6.2f}%")
print(" fixed slot " + " ".join(f"{v:6.2f}%" for v in report["fixed_slot"]))
print(
f" char-3gram probe (mean) {report['ngram_probe_mean']:6.2f}%"
f" (max {report['ngram_probe_max']:.2f}% over {seeds} splits)"
)
worst = max(
[
report["pick_largest"],
report["pick_smallest"],
report["pick_roundest"],
report["ngram_probe_mean"],
]
)
report["worst_shortcut"] = worst
if worst > 30.0:
print(f" WARNING: a shortcut reaches {worst:.2f}% -- options leak the answer")
else:
print(" OK: no shortcut materially beats chance")
return report
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def cmd_build(args) -> None:
records = build(seed=args.seed, total_depths=args.per_depth)
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
with out.open("w", encoding="utf-8") as fh:
for rec in records:
fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
digest = hashlib.sha256(out.read_bytes()).hexdigest()
print(f"wrote {len(records)} items to {out}")
print(f"sha256: {digest}")
def cmd_selftest(args) -> None:
path = Path(args.data)
if not path.exists():
raise SystemExit(f"missing {path}; run `build` first")
records = load_jsonl(path)
result = validate(records)
if result["problems"]:
raise SystemExit(f"{len(result['problems'])} validation problems")
# ArithMark 3.0's own loader rules, repeated here so compatibility is checked
for rec in records:
assert rec["ctx"] and rec["endings"] and len(rec["endings"]) >= 2
assert all(e.startswith(" ") for e in rec["endings"])
assert all(isinstance(e, str) and e for e in rec["endings"])
int(rec["label"])
print("\nselftest: OK (schema matches ArithMark 3.0; all invariants hold)")
if not args.no_audit:
audit(records)
def cmd_audit(args) -> None:
records = load_jsonl(Path(args.data))
validate(records, verbose=False)
audit(records)
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__)
sub = ap.add_subparsers(dest="cmd", required=True)
b = sub.add_parser("build", help="generate the dataset")
b.add_argument("--out", default=f"deeparithmark-dataset/data/{DATASET_NAME}.jsonl")
b.add_argument("--seed", type=int, default=20261027)
b.add_argument("--per-depth", type=int, default=PER_DEPTH)
b.set_defaults(func=cmd_build)
s = sub.add_parser("selftest", help="validate the dataset and audit shortcuts")
s.add_argument("--data", default=f"deeparithmark-dataset/data/{DATASET_NAME}.jsonl")
s.add_argument("--no-audit", action="store_true")
s.set_defaults(func=cmd_selftest)
a = sub.add_parser("audit", help="shortcut audit only")
a.add_argument("--data", default=f"deeparithmark-dataset/data/{DATASET_NAME}.jsonl")
a.set_defaults(func=cmd_audit)
args = ap.parse_args()
args.func(args)
if __name__ == "__main__":
main()
|