Download deeparithmark.py from OPENGCM/DeepArithmark-1: direct link, hf CLI and curl.
- Browser
- Download file 59.1 kB
-
https://huggingface.co/datasets/OPENGCM/DeepArithmark-1/resolve/main/deeparithmark.py
- Command line
-
hf download hf://datasets/OPENGCM/DeepArithmark-1/deeparithmark.py
-
curl -L -o deeparithmark.py https://huggingface.co/datasets/OPENGCM/DeepArithmark-1/resolve/main/deeparithmark.py
59.1 kB
| #!/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 | |
| # --------------------------------------------------------------------------- | |
| 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 | |
| # --------------------------------------------------------------------------- | |
| class Assembled: | |
| draft: Draft | |
| decoys: list[tuple[str, int]] # exactly 3 wrong-path (kind, value) pairs | |
| 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() | |