TeamNull commited on
Commit
d765c14
·
verified ·
1 Parent(s): 2aeda16

Add Deep Arithmark 1: 1,000 long-horizon arithmetic items, generator, scorer, design notes

Browse files
DEEPARITHMARK_DESIGN.md ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Deep Arithmark — design
2
+
3
+ > **Unofficial.** Deep Arithmark is an independent companion tier, not an
4
+ > AxiomicLabs release. It is not affiliated with, endorsed by, or published by
5
+ > AxiomicLabs, the authors of [ArithMark 3.0](https://huggingface.co/datasets/AxiomicLabs/Arithmark-3.0),
6
+ > and the name is used descriptively. Any errors here are the author's. See
7
+ > §10 for what is and is not reused from the upstream benchmark.
8
+
9
+ Deep Arithmark is the long-horizon tier *of* ArithMark 3.0: the same task
10
+ contract, the same scoring protocol, and a much harder item. This document
11
+ records what changed, why, and what the measurements actually say.
12
+
13
+ * Dataset: [`deeparithmark-dataset/data/deeparithmark-1.jsonl`](deeparithmark-dataset/data/deeparithmark-1.jsonl)
14
+ (1,000 items, sha256 `8a54eb90b66b142b7fea422b34d851746d1cabc476dcba906c7f3ad5ddc66ee0`)
15
+ * Generator / auditor: [`deeparithmark.py`](deeparithmark.py)
16
+ * Scorer: [`bench_deeparithmark.py`](bench_deeparithmark.py)
17
+ * Baselines: [`benchmarks/deeparithmark_4models.json`](benchmarks/deeparithmark_4models.json),
18
+ [`benchmarks/deeparithmark_2models.json`](benchmarks/deeparithmark_2models.json),
19
+ [`benchmarks/deeparithmark_1models.json`](benchmarks/deeparithmark_1models.json)
20
+
21
+ ---
22
+
23
+ ## 1. Why a "Deep" ArithMark
24
+
25
+ ArithMark 3.0 is a clean benchmark: 1,000 continuation-style word problems,
26
+ four endings, chance 25 %, graded by length-normalised continuation
27
+ log-likelihood with no chain-of-thought and no instruction following. It also
28
+ saturates at both ends for the models it is meant to rank.
29
+
30
+ Two properties do that.
31
+
32
+ **The options are adjacent integers.** Every item looks like
33
+
34
+ ```
35
+ Sam had 43 rubber bands. A friend gave Sam 19 more. Afterward, Sam had
36
+ 0 ' 63 rubber bands.'
37
+ 1 ' 62 rubber bands.' <- correct
38
+ 2 ' 61 rubber bands.'
39
+ 3 ' 60 rubber bands.'
40
+ ```
41
+
42
+ The four continuations differ by ±1, so a model never has to compute `43 + 19`.
43
+ It only has to land in the right neighbourhood, and digit priors from
44
+ pretraining are enough. That is why pythia-70m scores 27.0 % — barely above
45
+ chance on 62 — while a 0.5B model scores 60.9 %.
46
+
47
+ **Every item is one or two dependent operations.** Nothing requires holding an
48
+ intermediate result across more than one step.
49
+
50
+ Measured on the same weights and protocol as this repo (see §6), **Qwen2.5-0.5B
51
+ scores 60.9 % on ArithMark 3.0**. There is no headroom left in the sub-1B band.
52
+
53
+ Deep Arithmark is the same instrument aimed one tier up. Borrowing the DeepSWE
54
+ framing — original tasks, longer horizon per item, short prompts, graded by
55
+ outcome rather than process — it keeps the 4-way continuation contract but
56
+ requires a chain of arithmetic to answer.
57
+
58
+ ---
59
+
60
+ ## 2. The three changes
61
+
62
+ ### 2.1 Depth
63
+
64
+ Every item needs **2–5 dependent operations**, with 250 items per depth tier. A
65
+ later operation consumes the result of an earlier one, so no single memorised
66
+ pattern gets you the ending.
67
+
68
+ Depth is defined as **the number of operations in the reference solution**, and
69
+ that reference solution is shipped in the item (`metadata.solution_steps`), so
70
+ the claim is checkable rather than asserted. `selftest` fails the build if
71
+ `len(solution_steps) != depth` for any item. Examples:
72
+
73
+ | depth | item |
74
+ |---:|---|
75
+ | 2 | a percentage off a price, then a handling fee added |
76
+ | 3 | convert metres+centimetres to cm, add the remainder, subtract a cut |
77
+ | 4 | receive, ship out, remove damaged units, then divide into crates |
78
+ | 5 | two percentage days on a shrinking base, then palletise |
79
+
80
+ ### 2.2 Decoys with provenance
81
+
82
+ No decoy is "answer ± 1", and no decoy is a random plausible number. Every
83
+ decoy is the exact value a *specific* plausible wrong reasoning produces:
84
+
85
+ * the state after step 2 instead of step 5 ("stopped before palletising"),
86
+ * the percentage applied to the wrong base ("taxed the price before the discount"),
87
+ * the divisor `n` instead of `n + 1` ("split among one more person"),
88
+ * the unit conversion left out ("used 10 cm to the metre"),
89
+ * the boundary handled the wrong way (ceil instead of floor),
90
+ * the operation run the wrong direction ("added the cut instead of removing it").
91
+
92
+ To reject a wrong option you must know *which step* was botched. Ranking the
93
+ options by size is no longer enough, which is exactly the ±1 shortcut removed.
94
+
95
+ Every record carries the provenance per ending:
96
+
97
+ ```json
98
+ "metadata": {
99
+ "answer": "324",
100
+ "depth": 4,
101
+ "option_values": [180, 324, 252, 216],
102
+ "option_sources": ["forgot the discount", "correct", "taxed before discount", "split among one more person"],
103
+ "answer_rank": 3,
104
+ "solution_steps": ["...", "...", "...", "..."]
105
+ }
106
+ ```
107
+
108
+ `option_sources` is aligned to `endings`, so an error analysis can ask *which
109
+ mistake the model made*, not just whether it was wrong.
110
+
111
+ ### 2.3 Balancing on three axes
112
+
113
+ A multiple-choice benchmark is only measuring arithmetic if the option set
114
+ carries no cheaper signal. Three axes are balanced, all enforced by `selftest`:
115
+
116
+ | Axis | What it prevents | Achieved (of 1,000) |
117
+ |---|---|---|
118
+ | Correct slot (`label`) | position priors | 248–252 per slot |
119
+ | Numeric rank of the answer | "pick the largest / smallest / median" | 248–252 per rank |
120
+ | Roundness class of all four options | digit-prior smoothing toward round numbers | 100 % same class |
121
+
122
+ `label` × `rank` × `depth` is a 64-cell grid filled at **15–16 items per cell**,
123
+ so the axes cannot drift apart.
124
+
125
+ The roundness axis was not in the first draft, and finding it is the most useful
126
+ thing this build produced — see §4.
127
+
128
+ ---
129
+
130
+ ## 3. Composition
131
+
132
+ | Property | Value |
133
+ |---|---|
134
+ | Items | 1,000 |
135
+ | Answer choices | 4 (chance 25 %) |
136
+ | Templates | 15 |
137
+ | Topic labels | 14 |
138
+ | Depth tiers | 2, 3, 4, 5 — 250 each |
139
+ | Mean prompt length | 29.2 words (max 43) |
140
+ | Mean ending length | 9.7 characters |
141
+ | Splits | `test` (single split; never train on it) |
142
+
143
+ | Template | Depth | Items | What it exercises |
144
+ |---|---:|---:|---|
145
+ | `money_discount_fee` | 2 | 122 | percent off, then a fixed fee |
146
+ | `time_clock_end` | 2 | 128 | clock time + duration, hour carry |
147
+ | `measure_cm_cut` | 3 | 33 | unit conversion, then subtraction |
148
+ | `share_then_split` | 3 | 44 | fraction removed, remainder divided |
149
+ | `two_rate_pay` | 3 | 45 | two rates, then a sum |
150
+ | `stock_percent_pack` | 3 | 48 | percent sold, remainder packed |
151
+ | `trip_minutes` | 3 | 33 | two legs at different speeds + a rest |
152
+ | `schedule_sessions` | 3 | 47 | three durations across the hour |
153
+ | `inventory_boxes` | 4 | 62 | receive, ship, damage, pack |
154
+ | `mix_split` | 4 | 63 | two products, sum, then split |
155
+ | `tank_fill` | 4 | 62 | two fill stages, then a drain |
156
+ | `discount_tax_coupon_split` | 4 | 63 | discount, tax, coupon, split |
157
+ | `salary_overtime_tax` | 5 | 84 | base + 1.5× overtime + bonus − tax |
158
+ | `inventory_percent_chain` | 5 | 83 | two percentage days, then palletise |
159
+ | `prize_ratio_charity` | 5 | 83 | fee, ratio split, charity cut, split |
160
+
161
+ ---
162
+
163
+ ## 4. Fairness audit (and the bug it caught)
164
+
165
+ `python deeparithmark.py audit` measures what a model can score **without doing
166
+ arithmetic**: fixed-slot priors, magnitude picks, text-length picks, roundness
167
+ picks, and a trained character-3-gram classifier over the option text.
168
+
169
+ Current build:
170
+
171
+ | Shortcut | Score |
172
+ |---|---:|
173
+ | pick largest value | 25.20 % |
174
+ | pick smallest value | 24.80 % |
175
+ | pick second smallest | 25.20 % |
176
+ | **pick roundest number** | **25.20 %** |
177
+ | pick longest / shortest text | 25.50 % / 24.00 % |
178
+ | fixed slot 0 / 1 / 2 / 3 | 25.20 / 25.20 / 24.80 / 24.80 % |
179
+ | char-3-gram classifier (5 splits) | 25.47 % mean, 28.00 % max |
180
+
181
+ All at chance (25 %). That was not true of the first build.
182
+
183
+ **The bug.** The first build balanced slot and rank but not surface shape, and
184
+ several decoy paths produced structurally rounder numbers than the answer (a
185
+ "reported in whole metres" decoy, ×10 and ×100 unit-conversion artifacts). gpt2
186
+ then behaved as a pure round-number picker — it chose a roundest option on 84 %
187
+ of items — and scored **21.1 %**, *below* chance. Splitting by whether the
188
+ correct answer happened to be the roundest option isolates the cause:
189
+
190
+ | Where the answer sits by roundness | items | gpt2 acc |
191
+ |---|---:|---:|
192
+ | answer is the roundest option | 615 | 28.5 % |
193
+ | a decoy is rounder | 385 | 9.4 % |
194
+
195
+ So the option set was leaking a signal that was *anti-correlated* with
196
+ correctness. A benchmark in which a stronger model scores lower than a coin flip
197
+ is broken regardless of how hard its items are.
198
+
199
+ **The fix.** All four options must share the answer's roundness class
200
+ (trailing-zero count), so "which number looks most natural" carries exactly no
201
+ information. That moved gpt2 from 21.1 % to 24.0 % and put every shortcut back
202
+ at chance. Any future family added must satisfy the same constraint; `assemble`
203
+ enforces it automatically.
204
+
205
+ Two smaller items this audit forced:
206
+
207
+ * `share_then_split` rendered "cookies" in the endings even when the prompt said
208
+ "muffins" — a unit mismatch that is both a grammar bug and a cue.
209
+ * Time items originally mixed a.m. and p.m. among the options, which makes "the
210
+ odd one out" a free answer. All clock options are now inside the answer's half
211
+ of the day.
212
+
213
+ ---
214
+
215
+ ## 5. What is actually being measured
216
+
217
+ With well-separated options, 4-way accuracy is all-or-nothing: a model either
218
+ lands the exact number or not. There is no partial credit mechanism in a
219
+ log-likelihood comparison — "roughly right" is not a thing the scorer can see.
220
+ So the design reports two numbers:
221
+
222
+ * **`acc_norm`** — hard accuracy, directly comparable to ArithMark 3.0.
223
+ * **`soft`** — mean probability a proper scoring rule assigns to the correct
224
+ option after a softmax over the four continuation scores. This is the graded
225
+ signal; it is not comparable to ArithMark's accuracy, it is a different
226
+ statistic.
227
+
228
+ §6 makes clear why both are needed: for sub-1B models, *both* sit at chance.
229
+
230
+ ---
231
+
232
+ ## 6. Measured baselines
233
+
234
+ Protocol: zero-shot, `acc_norm` as the headline, bf16, batch 32,
235
+ `--max-context 1024` — ArithMark 3.0's own protocol (`bencharithmark-3.py`).
236
+ ArithMark 3.0 numbers below are produced by this repo on the same weights in the
237
+ same run, not copied from the baseline table. gpt2 reproducing 34.7 % against
238
+ the published 35.7 % validates the scorer.
239
+
240
+ | Model | Params | Deep `acc_norm` | Deep `soft` | ArithMark-3 `acc_norm` | Δ |
241
+ |---|---:|---:|---:|---:|---:|
242
+ | Qwen2.5-1.5B-Instruct | 1.54 B | **38.00** | 27.23 | — | — |
243
+ | Qwen2.5-0.5B | 494 M | 24.60 | 25.50 | 60.90 | −36.30 |
244
+ | SmolLM2-360M-Instruct | 362 M | 23.80 | 25.19 | — | — |
245
+ | GPT-X3-150M | 149 M | 25.20 | 25.07 | 49.60 | −24.40 |
246
+ | SmolLM2-135M | 135 M | 24.80 | 25.21 | 38.60 | −13.80 |
247
+ | gpt2 | 124 M | 24.00 | 24.98 | 34.70 | −10.70 |
248
+ | EleutherAI/pythia-70m | 70 M | 22.70 | 24.34 | 28.80 | −6.10 |
249
+
250
+ ### The depth ladder works — above the sub-1B band
251
+
252
+ Qwen2.5-1.5B-Instruct, per depth tier (n = 250 each):
253
+
254
+ | Depth | `acc_norm` | `soft` |
255
+ |---:|---:|---:|
256
+ | 2 | 60.4 % | 30.5 % |
257
+ | 3 | 40.8 % | 27.3 % |
258
+ | 4 | 28.4 % | 26.1 % |
259
+ | 5 | 22.4 % | 25.0 % |
260
+
261
+ Monotone, and it collapses to chance exactly at depth 5. That is the intended
262
+ behaviour: the items are solvable, the depth axis is real, and the benchmark has
263
+ a definable ceiling. It also shows the benchmark is not degenerate — it is not
264
+ "impossible", it is *out of reach for one forward pass of a small base model*.
265
+
266
+ ### The honest headline: sub-1B base models sit at chance
267
+
268
+ Every sub-1B **base** model measures 22.7–25.2 % — chance, with pythia-70m
269
+ slightly below. The `soft` score confirms this is not a metric artifact: if the
270
+ models had any partial skill, the softmax probability of the correct option
271
+ would drift above 25 %. It does not (24.3–25.5 %).
272
+
273
+ That is the geometric consequence of the design, not a tuning failure: with
274
+ well-separated options, scoring requires chaining the operations in a single
275
+ forward pass, and 70M–500M base models cannot. ArithMark 3.0's ±1 options hid
276
+ this by rewarding a magnitude prior instead of arithmetic.
277
+
278
+ **Practical consequence:** use Deep Arithmark as a ceiling tier with the per-depth
279
+ curve reported, not as a single number that gates a leaderboard. For a sub-1B
280
+ model the useful reading is "still at chance, and here is how far into the depth
281
+ tiers the first real signal appears". The benchmark becomes discriminative from
282
+ roughly the 1.5B-instruct class upward; the 0.5B row shows the 36-point gap to
283
+ ArithMark 3.0, which is the measured version of "harder".
284
+
285
+ ### Chance is not always guessing: GPT-X3-150M
286
+
287
+ GPT-X3-150M is the sharpest case. It scores 49.6 % on ArithMark 3.0 — the best
288
+ 150M-class result in this table, 11 points above SmolLM2-135M — and lands on
289
+ 25.20 % here, a 24.4-point drop, the largest in the set.
290
+
291
+ But it is *not* sampling uniformly. Its per-template accuracy spans 3.0 %
292
+ (`trip_minutes`, n = 33) to 54.5 % (`share_then_split`, n = 44), and that spread
293
+ is far beyond binomial noise: χ² = 63.2, df = 14, p < 1e-4 (20k-draw Monte Carlo,
294
+ null of independent binomials at the observed rate). Two mechanisms produce it:
295
+
296
+ 1. **A small-number prior.** It selects the numerically smallest of the four
297
+ options 34.8 % of the time and the largest only 15.8 % (rank distribution
298
+ 348 / 281 / 213 / 158 from smallest to largest).
299
+ 2. **A stable wrong path per family.** Where a single named mistake is the
300
+ attractive one, it picks it consistently and scores *below* chance —
301
+ `money_discount_fee` 16.4 %, `two_rate_pay` 11.1 %, `tank_fill` 14.5 %.
302
+
303
+ The two cancel to exactly chance at the aggregate. `trip_minutes` is the clear
304
+ illustration: the answer is never the smallest option there (rank distribution
305
+ 0 / 30 / 30 / 39), the model picks smallest 75.8 % of the time, so it scores
306
+ 3.0 %; `measure_cm_cut`, where the answer is never the largest (39 / 30 / 30 /
307
+ 0), scores 18.2 %.
308
+
309
+ **What this implies.** The rank balance is enforced globally (248–252 per rank),
310
+ not within each template — `measure_cm_cut` and `trip_minutes` are the extreme
311
+ cases at 39/30/30/0 and 0/30/30/39. A per-template surface policy therefore has
312
+ free signal that nets to zero across the dataset. That is harmless for the
313
+ headline number, which no surface shortcut beats, but it means per-template
314
+ accuracy rows should be read as "what does it prefer here", never as a partial
315
+ skill estimate, and it is the one place where a per-template rank balance would
316
+ buy a cleaner diagnostic.
317
+
318
+ If a low-scoring tier is needed for a sub-1B leaderboard today, the depth-2
319
+ families are where signal first appears, and `share_then_split` /
320
+ `time_clock_end` are the two templates a 1.5B instruct model already solves
321
+ (86.4 % and 85.9 %) — i.e. the ladder has a bottom rung, it is just above 1B.
322
+
323
+ ---
324
+
325
+ ## 7. Reproducing
326
+
327
+ ```bash
328
+ # regenerate the dataset (deterministic for a fixed seed)
329
+ python deeparithmark.py build
330
+
331
+ # validate every structural claim + run the shortcut audit
332
+ python deeparithmark.py selftest
333
+
334
+ # score models (add --compare for ArithMark 3.0 on the same weights)
335
+ python bench_deeparithmark.py --compare \
336
+ --model gpt2 --model HuggingFaceTB/SmolLM2-135M --model Qwen/Qwen2.5-0.5B \
337
+ --out benchmarks
338
+
339
+ # per-item predictions, for the per-template / option-rank analysis in §6
340
+ python bench_deeparithmark.py --model AxiomicLabs/GPT-X3-150M \
341
+ --dump-predictions preds.jsonl --no-save
342
+ ```
343
+
344
+ The resulting JSONL is scored unchanged by ArithMark 3.0's own
345
+ `bencharithmark-3.py --data-path deeparithmark-1.jsonl`; the loader is verified
346
+ against that script, not just "schema-similar".
347
+
348
+ ---
349
+
350
+ ## 8. Known limitations
351
+
352
+ * **1,000 items** → a 95 % confidence interval of about ±2.7 points at p = 25 %.
353
+ Treat differences smaller than ~4 points as noise.
354
+ * **No partial credit** in the hard metric, by construction (see §5). The `soft`
355
+ score exists to recover a gradient but is a different statistic.
356
+ * **A single split.** No train/dev split is provided on purpose: this is an
357
+ evaluation set, and the generator is the training-avoidance mechanism.
358
+ * **Template-bound.** A model fine-tuned on these 15 templates would overfit
359
+ them. The seed makes the *item instances* contamination-free, not the template
360
+ shapes.
361
+ * **Clock items are a.m.-only** across their four options (a fairness constraint
362
+ from §4), so time items never exercise a noon or midnight rollover.
363
+ * **Grade bands are nominal.** "grades_7_8" describes the arithmetic, not a
364
+ curriculum claim.
365
+ * **Cents vs dollars.** Money is integer cents internally, rendered as whole
366
+ dollars; options within an item always share a format.
367
+ * **Rank balance is global, not per-template.** Overall each numeric rank is the
368
+ answer 248–252 times, so "pick the largest" gains nothing, but individual
369
+ templates can be lopsided (`measure_cm_cut` 39/30/30/0, `trip_minutes`
370
+ 0/30/30/39). A per-template surface policy therefore shifts per-template
371
+ accuracy while netting to zero across the set — see the GPT-X3-150M note.
372
+ * **A model that reports inside the noise band on the aggregate is not
373
+ necessarily guessing.** Check `--dump-predictions` before reading a chance score
374
+ as "no signal"; GPT-X3-150M is the worked example.
375
+
376
+ ---
377
+
378
+ ## 9. Adding a family
379
+
380
+ A new family is a function `fam_x(rng) -> Draft | None` that returns the prompt,
381
+ the answer, the reference `steps` (one per dependent operation), and a pool of
382
+ `(kind, value)` wrong-path values. Requirements, enforced by `build`/`selftest`:
383
+
384
+ 1. `len(steps) == depth`, and `answer == steps[-1][1]`.
385
+ 2. At least three pool values on **each** side of the answer (so every rank is
386
+ reachable).
387
+ 3. No pool value that a reader would discard without arithmetic — `assemble`
388
+ rejects values whose roundness class differs from the answer's, or that are
389
+ more than 4× off.
390
+ 4. Every option must render with the same unit phrase, and no option may be
391
+ exactly `1` with a plural unit.
392
+ 5. Enough parameter variety for ~60+ distinct prompts (add names/nouns if the
393
+ arithmetic parameters are few).
394
+
395
+ Then add it to `FAMILIES` under the tier matching its step count, rebuild, and
396
+ run `selftest` — the audit and every balance table must still pass.
397
+
398
+ ---
399
+
400
+ ## 10. Attribution and licence
401
+
402
+ **Upstream.** Deep Arithmark follows [ArithMark 3.0](https://huggingface.co/datasets/AxiomicLabs/Arithmark-3.0)
403
+ by AxiomicLabs (Apache-2.0). Please cite ArithMark 3.0 as well as this work.
404
+
405
+ **What is reused.** The *task contract* — one unfinished sentence, four
406
+ continuations with a leading space, a single correct index, and scoring by
407
+ length-normalised continuation log-likelihood — and the JSONL schema, which is
408
+ why ArithMark 3.0's own `bencharithmark-3.py` scores this file unchanged.
409
+
410
+ **What is not reused.** No upstream item appears here: all 1,000 prompts are
411
+ generated by [`deeparithmark.py`](deeparithmark.py), and the released file shares
412
+ zero identical contexts and zero eight-word n-grams with the upstream data.
413
+ [`bench_deeparithmark.py`](bench_deeparithmark.py) is an independent
414
+ implementation of the same protocol, not copied code — it shares only import and
415
+ boilerplate lines with `bencharithmark-3.py`. `--compare` downloads the upstream
416
+ dataset from `AxiomicLabs/Arithmark-3.0`, which is where it lives; Deep Arithmark
417
+ is not published under that org.
418
+
419
+ **Licence.** Apache License 2.0, matching upstream. "ArithMark" and
420
+ "AxiomicLabs" remain the property of their owner; this use is descriptive and
421
+ implies no affiliation or endorsement.
README.md ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ size_categories:
6
+ - 1K<n<10K
7
+ task_categories:
8
+ - question-answering
9
+ pretty_name: Deep Arithmark 1
10
+ tags:
11
+ - arithmetic
12
+ - multiple-choice
13
+ - synthetic
14
+ - language-model-evaluation
15
+ - long-horizon
16
+ configs:
17
+ - config_name: default
18
+ data_files:
19
+ - split: test
20
+ path: data/deeparithmark-1.jsonl
21
+ ---
22
+
23
+ # Deep Arithmark 1
24
+
25
+ **The long-horizon tier of [ArithMark 3.0](https://huggingface.co/datasets/AxiomicLabs/Arithmark-3.0).**
26
+
27
+ > **Unofficial.** Deep Arithmark is an independent, community-built companion
28
+ > tier. It is not affiliated with, endorsed by, or published by AxiomicLabs, the
29
+ > authors of ArithMark 3.0, and it is not an official ArithMark release. It
30
+ > follows their task contract and credits them throughout; any errors are the
31
+ > author's. If you use this benchmark, cite ArithMark 3.0 as well.
32
+
33
+ ArithMark 3.0 asks a base model to finish a one- or two-step word problem whose
34
+ four continuations are **adjacent integers** (43 / 44 / 45 / 46). To reject a
35
+ wrong option you only need to know the answer is "about 44", so a magnitude
36
+ prior is enough and arithmetic is optional.
37
+
38
+ Deep Arithmark keeps ArithMark's contract exactly — one unfinished sentence, four
39
+ continuations with a leading space, one correct index, scored by
40
+ length-normalised continuation log-likelihood, chance 25 % — and changes three
41
+ things:
42
+
43
+ 1. **Depth.** Every item needs **2–5 dependent operations** (250 items per tier).
44
+ Later operations consume earlier results, so no single memorised template
45
+ yields the continuation.
46
+ 2. **Decoys with provenance.** No decoy is "answer ± 1". Every decoy is the exact
47
+ value some specific plausible wrong reasoning produces — the state after step
48
+ 2 instead of step 5, the percentage on the wrong base, the divisor `n` instead
49
+ of `n + 1`, the unit conversion left out. `metadata.option_sources` records
50
+ which mistake each ending encodes, so error analysis can ask *which* step a
51
+ model botches.
52
+ 3. **Balanced on three axes.** The correct slot, the answer's *numeric rank* and
53
+ the *roundness class* of all four options are all balanced, so "pick the
54
+ largest" and "pick the roundest number" are worth exactly 25 %.
55
+
56
+ Full design notes, the fairness audit and the measurement discussion are in
57
+ `DEEPARITHMARK_DESIGN.md`, which ships in this repository next to the generator
58
+ (`deeparithmark.py`) and the scorer (`bench_deeparithmark.py`).
59
+
60
+ ## At a glance
61
+
62
+ | Property | Value |
63
+ | --- | ---: |
64
+ | Examples | 1,000 |
65
+ | Answer choices per example | 4 |
66
+ | Random-choice accuracy | 25 % |
67
+ | Templates | 15 |
68
+ | Topic labels | 14 |
69
+ | Depth tiers | 2, 3, 4, 5 — 250 each |
70
+ | Mean prompt length | 29.2 words (max 43) |
71
+ | Mean ending length | 9.7 characters |
72
+ | Language | English |
73
+ | Data source | Synthetic (generated, deterministic seed) |
74
+ | Dataset file | `data/deeparithmark-1.jsonl` |
75
+ | SHA-256 | `8a54eb90b66b142b7fea422b34d851746d1cabc476dcba906c7f3ad5ddc66ee0` |
76
+
77
+ ## Repository contents
78
+
79
+ | File | What it is |
80
+ | --- | --- |
81
+ | `data/deeparithmark-1.jsonl` | The dataset — 1,000 items, one JSON object per line |
82
+ | `README.md` | This card |
83
+ | `deeparithmark.py` | Deterministic generator, plus `selftest` and the shortcut `audit` |
84
+ | `bench_deeparithmark.py` | Scorer with per-depth and per-template breakdowns and an ArithMark 3.0 comparison |
85
+ | `DEEPARITHMARK_DESIGN.md` | Design rationale, fairness audit, measurement discussion |
86
+
87
+ ## Task format
88
+
89
+ Identical to ArithMark 3.0, so `bencharithmark-3.py --data-path
90
+ data/deeparithmark-1.jsonl` scores it unchanged (verified against that script's
91
+ own loader).
92
+
93
+ ```json
94
+ {
95
+ "ind": 3,
96
+ "activity_label": "deeparithmark::deeparithmark-1::multi_step_inventory::depth4::hard",
97
+ "ctx": "A warehouse held 420 units. A delivery added 260, then 210 units were shipped out, and 40 were found damaged. The rest were packed into crates of 16. The number of full crates packed was",
98
+ "endings": [" 26 crates.", " 29 crates.", " 27 crates.", " 31 crates."],
99
+ "label": "0",
100
+ "source_id": "deeparithmark_v1_multi_step_inventory_depth4_0003",
101
+ "split": "test",
102
+ "split_type": "synthetic",
103
+ "metadata": {
104
+ "answer": "26",
105
+ "unit": "crates",
106
+ "topic": "multi_step_inventory",
107
+ "depth": 4,
108
+ "option_values": [26, 29, 27, 31],
109
+ "option_sources": ["correct", "forgot the damaged units", "counted the loose units as a crate", "added the damaged units"],
110
+ "answer_rank": 0,
111
+ "solution_steps": [
112
+ "after delivery: 420 + 260 = 680",
113
+ "after shipping: 680 - 210 = 470",
114
+ "good units: 470 - 40 = 430",
115
+ "full crates: 430 / 16 = 26 (remainder 14)"
116
+ ]
117
+ }
118
+ }
119
+ ```
120
+
121
+ The correct continuation is ` 26 crates.` — `420 + 260 − 210 − 40 = 430`, and
122
+ `430 // 16 = 26` full crates. Every wrong ending is the result of a named
123
+ mistake, not a perturbation of 26.
124
+
125
+ ## Composition
126
+
127
+ ### Depth
128
+
129
+ | Depth | Examples | Share | Typical item |
130
+ | ---: | ---: | ---: | --- |
131
+ | 2 | 250 | 25.0 % | percent off a price, then a fee |
132
+ | 3 | 250 | 25.0 % | unit conversion, add, subtract |
133
+ | 4 | 250 | 25.0 % | receive / ship / damage / pack |
134
+ | 5 | 250 | 25.0 % | two percentage days, then palletise |
135
+
136
+ `depth` equals the number of operations in `metadata.solution_steps` for every
137
+ item; the build fails if that is not true.
138
+
139
+ ### Templates
140
+
141
+ | Template | Depth | Examples | Topic |
142
+ | --- | ---: | ---: | --- |
143
+ | `money_discount_fee` | 2 | 122 | money_percent |
144
+ | `time_clock_end` | 2 | 128 | time |
145
+ | `measure_cm_cut` | 3 | 33 | measurement |
146
+ | `share_then_split` | 3 | 44 | fractions |
147
+ | `two_rate_pay` | 3 | 45 | rate_pay |
148
+ | `stock_percent_pack` | 3 | 48 | percent |
149
+ | `trip_minutes` | 3 | 33 | rate_time |
150
+ | `schedule_sessions` | 3 | 47 | time |
151
+ | `inventory_boxes` | 4 | 62 | multi_step_inventory |
152
+ | `mix_split` | 4 | 63 | money |
153
+ | `tank_fill` | 4 | 62 | rate |
154
+ | `discount_tax_coupon_split` | 4 | 63 | percent_money |
155
+ | `salary_overtime_tax` | 5 | 84 | money_rate |
156
+ | `inventory_percent_chain` | 5 | 83 | percent_multi_step |
157
+ | `prize_ratio_charity` | 5 | 83 | ratio |
158
+
159
+ ### Correct-answer positions and numeric rank
160
+
161
+ Both balanced, so neither slot priors nor magnitude priors are worth anything:
162
+
163
+ | Axis | Distribution |
164
+ | --- | --- |
165
+ | Correct slot | 252 / 252 / 248 / 248 |
166
+ | Answer numeric rank (smallest → largest) | 248 / 252 / 248 / 252 |
167
+
168
+ The `slot × rank × depth` grid is filled at 15–16 items per cell.
169
+
170
+ ## Shortcut audit
171
+
172
+ Measured on this file (`python deeparithmark.py audit`); chance is 25.00 %:
173
+
174
+ | Strategy that needs no arithmetic | Score |
175
+ | --- | ---: |
176
+ | pick largest value | 25.20 % |
177
+ | pick smallest value | 24.80 % |
178
+ | pick second smallest | 25.20 % |
179
+ | pick the roundest number | 25.20 % |
180
+ | pick longest / shortest text | 25.50 % / 24.00 % |
181
+ | fixed slot 0 / 1 / 2 / 3 | 25.20 / 25.20 / 24.80 / 24.80 % |
182
+ | char-3-gram classifier over option text | 25.47 % (max 28.00 % over 5 splits) |
183
+
184
+ Nothing clears chance. This matters: an early build of this dataset scored gpt2
185
+ **below** chance (21.1 %) because several decoys were structurally rounder than
186
+ the answer, so a round-number prior was anti-correlated with correctness. The
187
+ fix — all four options in the same roundness class — is documented in the design
188
+ notes, and it is now a build constraint.
189
+
190
+ ## Baselines
191
+
192
+ Zero-shot, `acc_norm`, bf16, batch 32, `--max-context 1024` (ArithMark 3.0's
193
+ protocol). ArithMark 3.0 numbers were produced on the same weights in the same
194
+ run, not copied from a table.
195
+
196
+ | Model | Params | Deep | soft | d2 | d3 | d4 | d5 | ArithMark-3 | Δ |
197
+ | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
198
+ | Qwen2.5-1.5B-Instruct | 1.54 B | **38.00 %** | 27.23 % | 60.4 | 40.8 | 28.4 | 22.4 | — | — |
199
+ | Qwen2.5-0.5B | 494 M | 24.60 % | 25.50 % | 24.8 | 26.4 | 23.6 | 23.6 | 60.90 % | −36.30 |
200
+ | SmolLM2-360M-Instruct | 362 M | 23.80 % | 25.19 % | 24.8 | 26.8 | 26.4 | 17.2 | — | — |
201
+ | GPT-X3-150M | 149 M | 25.20 % | 25.07 % | 23.6 | 24.0 | 25.6 | 27.6 | 49.60 % | −24.40 |
202
+ | SmolLM2-135M | 135 M | 24.80 % | 25.21 % | 18.0 | 29.2 | 26.4 | 25.6 | 38.60 % | −13.80 |
203
+ | gpt2 | 124 M | 24.00 % | 24.98 % | 22.0 | 23.2 | 25.2 | 25.6 | 34.70 % | −10.70 |
204
+ | EleutherAI/pythia-70m | 70 M | 22.70 % | 24.34 % | 21.6 | 26.0 | 21.6 | 21.6 | 28.80 % | −6.10 |
205
+
206
+ `d2`–`d5` are `acc_norm` per depth tier (250 items each, chance 25 %). `soft` is
207
+ the mean probability a proper scoring rule gives the correct option after a
208
+ softmax over the four continuation scores — the graded companion to hard
209
+ accuracy. Δ is Deep Arithmark minus ArithMark 3.0 on the same weights.
210
+
211
+ **Read the baselines carefully.** Every sub-1B *base* model sits at chance
212
+ (22.7–25.2 %), and the soft score agrees (24.3–25.5 %), so it is not a metric
213
+ artifact: a single forward pass of a sub-1B base model cannot chain 2+ operations.
214
+
215
+ GPT-X3-150M (149 M) makes that concrete. It is the strongest 150M-class model
216
+ here on ArithMark 3.0 — **49.60 %**, 11 points above SmolLM2-135M — and drops
217
+ **24.4 points** to 25.20 % on this dataset. But it is not guessing uniformly:
218
+ per-template accuracy runs from 3.0 % to 54.5 % (χ² = 63.2, df = 14, p < 1e-4),
219
+ driven by a small-number prior (it picks the smallest option 34.8 % of the time,
220
+ the largest 15.8 %) plus one stable wrong path per family in others. Those
221
+ cancel to chance in aggregate, so the 25.20 % is a real reading of "cannot solve
222
+ these", not noise — but treat per-template rows as preference, not skill.
223
+ Full breakdown in the design notes, §6.
224
+
225
+ What proves the dataset is nonetheless real and graded is the depth curve of a
226
+ model that can: Qwen2.5-1.5B-Instruct runs **60.4 → 40.8 → 28.4 → 22.4 %** across
227
+ d2–d5. Monotone, reaching chance exactly at depth 5. The items are solvable, the
228
+ depth axis is genuine, and the ceiling is well defined — it is just above the
229
+ sub-1B base class. Against ArithMark 3.0, Qwen2.5-0.5B loses **36.3 points**,
230
+ which is the measured form of "harder".
231
+
232
+ No sub-1B model shows a monotone curve in the other direction, and where one
233
+ drifts above 25 % on a tier it does not survive the set as a whole — see the
234
+ GPT-X3-150M discussion above.
235
+
236
+ For a sub-1B leaderboard, report the per-depth curve rather than only the single
237
+ number: the first real signal appears at the depth-2 rung, and at 1.5B-instruct
238
+ the two solvable templates are `share_then_split` (86.4 %) and `time_clock_end`
239
+ (85.9 %).
240
+
241
+ ## Usage
242
+
243
+ ```python
244
+ from datasets import load_dataset
245
+
246
+ ds = load_dataset("OPENGCM/DeepArithmark-1", split="test")
247
+ item = ds[0]
248
+ # score the four continuations of item["ctx"] by length-normalised
249
+ # log-likelihood and take the argmax; compare it with int(item["label"])
250
+ ```
251
+
252
+ Or score Hugging Face models directly, including a side-by-side ArithMark 3.0
253
+ comparison on the same weights:
254
+
255
+ ```bash
256
+ python bench_deeparithmark.py --compare --model HuggingFaceTB/SmolLM2-135M
257
+ python bench_deeparithmark.py --model Qwen/Qwen2.5-0.5B --out benchmarks
258
+ ```
259
+
260
+ ArithMark 3.0's own script works unchanged:
261
+
262
+ ```bash
263
+ python bencharithmark-3.py --data-path data/deeparithmark-1.jsonl --model gpt2
264
+ ```
265
+
266
+ ## How it was generated
267
+
268
+ `deeparithmark.py build` renders the file deterministically from seed
269
+ `20261027`: 15 parameterised families, exact integer arithmetic, and a decoy
270
+ pool per family of plausible wrong paths. `python deeparithmark.py selftest`
271
+ re-checks every claim on this page — schema, unit consistency, option
272
+ distinctness, step count vs depth, all three balance axes, and the shortcut
273
+ audit.
274
+
275
+ The seed makes the *instances* reproducible and unseen; it does not make the
276
+ template shapes novel. Do not train on this file.
277
+
278
+ ## Limitations
279
+
280
+ - 1,000 items → roughly ±2.7 points (95 % CI) at chance. Differences under ~4
281
+ points are noise.
282
+ - Hard 4-way accuracy gives no partial credit by design; use the soft score for
283
+ a gradient.
284
+ - Single `test` split, no train split (evaluation set).
285
+ - 15 templates only: fine-tuning on them would overfit.
286
+ - Clock items keep all four options inside one half of the day, so no noon
287
+ rollover is exercised.
288
+ - Grade bands (`grades_4_5` … `grades_7_8`) describe the arithmetic, not a
289
+ curriculum.
290
+
291
+ ## Licence and attribution
292
+
293
+ This dataset is released under the **Apache License 2.0**.
294
+
295
+ **Upstream work.** Deep Arithmark follows [ArithMark 3.0](https://huggingface.co/datasets/AxiomicLabs/Arithmark-3.0)
296
+ by AxiomicLabs, also Apache-2.0. What is reused is the *task contract*: one
297
+ unfinished sentence, four continuations with a leading space, a single correct
298
+ index, and scoring by length-normalised continuation log-likelihood — plus the
299
+ JSONL schema, so ArithMark 3.0's own scorer runs on this file unchanged.
300
+
301
+ **What is not reused.** No ArithMark 3.0 item appears here. Every prompt is
302
+ generated from the parameterised families in `deeparithmark.py`,
303
+ and the released file shares **0 identical contexts and 0 eight-word n-grams**
304
+ with the 1,000 upstream items. The accompanying scorer is an independent
305
+ implementation of the same protocol, not copied code.
306
+
307
+ **Trademarks.** "ArithMark" and "AxiomicLabs" remain the property of their
308
+ owner. Their use here is descriptive, to state which benchmark this one extends.
309
+ It does not imply affiliation or endorsement — see the notice at the top.
bench_deeparithmark.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Score Hugging Face causal LMs on Deep Arithmark (and, side by side, ArithMark 3.0).
4
+
5
+ The scoring protocol follows ArithMark 3.0's (AxiomicLabs) so the two numbers
6
+ are directly comparable. This file is an independent implementation, not copied
7
+ code; it shares only imports and boilerplate with `bencharithmark-3.py`:
8
+
9
+ * zero-shot continuation log-likelihood -- the model never generates text;
10
+ * context and continuation tokenized separately, so the continuation cannot
11
+ be scored through the context's tokenization;
12
+ * `acc` sums the token log-probabilities, `acc_norm` averages them;
13
+ * bf16, batch 32, `--max-context 1024`, by default.
14
+
15
+ On top of that it reports the profile the depth tiers are for:
16
+
17
+ * a per-depth curve (2, 3, 4, 5 dependent operations), so a sub-1B model has
18
+ something to climb instead of a single number pinned at chance;
19
+ * per-template and per-topic accuracy, so a regression is attributable;
20
+ * the share of items where `acc` and `acc_norm` disagree (a near-tie signal).
21
+
22
+ Usage
23
+ -----
24
+ python bench_deeparithmark.py --model HuggingFaceTB/SmolLM2-135M
25
+ python bench_deeparithmark.py --model gpt2 --compare # ArithMark 3.0 too
26
+ python bench_deeparithmark.py --models-file models.txt --out benchmarks/
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import argparse
32
+ import gc
33
+ import hashlib
34
+ import json
35
+ import math
36
+ import time
37
+ from collections import defaultdict
38
+ from pathlib import Path
39
+
40
+ import torch
41
+ import torch.nn.functional as F
42
+ from huggingface_hub import hf_hub_download
43
+ from transformers import AutoModelForCausalLM, AutoTokenizer
44
+
45
+ # Our own data is read from disk; this repo is not published under AxiomicLabs.
46
+ DATA_DEFAULT = "deeparithmark-dataset/data/deeparithmark-1.jsonl"
47
+ # The one AxiomicLabs reference that must stay: `--compare` downloads the upstream
48
+ # benchmark from its authors' org, which is where it actually lives. Changing this
49
+ # to another namespace would break the head-to-head.
50
+ ARITHMARK3_REPO = "AxiomicLabs/Arithmark-3.0"
51
+ ARITHMARK3_FILE = "arithmark-3.jsonl"
52
+ BATCH_SIZE = 32
53
+ MAX_CONTEXT = 1024
54
+ DEPTHS = (2, 3, 4, 5)
55
+
56
+ # every model here is under 1B parameters, which is the target of this benchmark
57
+ DEFAULT_MODELS = [
58
+ "gpt2",
59
+ "EleutherAI/pythia-70m",
60
+ "HuggingFaceTB/SmolLM2-135M",
61
+ "Qwen/Qwen2.5-0.5B",
62
+ ]
63
+
64
+
65
+ def load_items(path: Path) -> list[dict]:
66
+ items = []
67
+ with path.open(encoding="utf-8-sig") as fh:
68
+ for line_no, line in enumerate(fh, 1):
69
+ if not line.strip():
70
+ continue
71
+ item = json.loads(line)
72
+ label = item["label"]
73
+ items.append(
74
+ {
75
+ "id": str(item.get("ind", line_no)),
76
+ "ctx": item["ctx"],
77
+ "endings": item["endings"],
78
+ "label": int(label),
79
+ "depth": item.get("metadata", {}).get("depth"),
80
+ "topic": item.get("metadata", {}).get("topic"),
81
+ "template": item.get("metadata", {}).get("template_id"),
82
+ }
83
+ )
84
+ if not items:
85
+ raise SystemExit(f"no items in {path}")
86
+ return items
87
+
88
+
89
+ def resolve_device(requested: str) -> str:
90
+ if requested != "auto":
91
+ return requested
92
+ return "cuda" if torch.cuda.is_available() else "cpu"
93
+
94
+
95
+ def load_model(model_name: str, device: str, dtype_name: str):
96
+ dtype = {"float32": torch.float32, "float16": torch.float16, "bfloat16": torch.bfloat16}[
97
+ dtype_name
98
+ ]
99
+ if device == "cpu":
100
+ dtype = torch.float32
101
+ model = AutoModelForCausalLM.from_pretrained(
102
+ model_name, dtype=dtype, trust_remote_code=True
103
+ ).to(device)
104
+ model.eval()
105
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True, use_fast=False)
106
+ if tokenizer.pad_token_id is None:
107
+ tokenizer.pad_token = tokenizer.eos_token or 0
108
+ return model, tokenizer, dtype
109
+
110
+
111
+ @torch.inference_mode()
112
+ def score_items(model, tokenizer, device, dtype, items, batch_size: int, max_context: int):
113
+ """Return (items, labels, raw_scores, norm_scores) -- 4 scores per item.
114
+
115
+ Results follow the length-sorted order used for batching, so the returned
116
+ item list is what the labels and scores line up with.
117
+ """
118
+ prepared = []
119
+ for item in items:
120
+ requests = []
121
+ for ending in item["endings"]:
122
+ ctx_ids = tokenizer(item["ctx"], add_special_tokens=False).input_ids
123
+ end_ids = tokenizer(ending, add_special_tokens=False).input_ids
124
+ if not ctx_ids or not end_ids:
125
+ raise SystemExit(f"empty tokenization in item {item['id']}")
126
+ ctx_ids = ctx_ids[-(max_context - len(end_ids)) :]
127
+ requests.append((ctx_ids + end_ids, len(end_ids)))
128
+ prepared.append((item, requests))
129
+ # similar lengths together: less padding, fewer wasted logits
130
+ prepared.sort(key=lambda pair: max(len(t) for t, _ in pair[1]))
131
+
132
+ labels, raw, norm = [], [], []
133
+ for start in range(0, len(prepared), batch_size):
134
+ batch = prepared[start : start + batch_size]
135
+ flats, lengths, cont_lens = [], [], []
136
+ for _, requests in batch:
137
+ for tokens, cont_len in requests:
138
+ flats.append(tokens)
139
+ lengths.append(len(tokens))
140
+ cont_lens.append(cont_len)
141
+ width = max(lengths)
142
+ ids = torch.tensor(
143
+ [t + [tokenizer.pad_token_id] * (width - len(t)) for t in flats],
144
+ dtype=torch.long,
145
+ device=device,
146
+ )
147
+ mask = torch.arange(width, device=device)[None, :] < torch.tensor(
148
+ lengths, device=device
149
+ )[:, None]
150
+ starts = torch.tensor(
151
+ [len(t) - c for t, c in zip(flats, cont_lens)], dtype=torch.long, device=device
152
+ )
153
+ with (
154
+ torch.autocast("cuda", dtype=dtype) if device == "cuda" and dtype != torch.float32 else torch.no_grad()
155
+ ):
156
+ logits = model(ids, attention_mask=mask, use_cache=False).logits
157
+ positions = torch.arange(1, width, device=device)[None, :]
158
+ score_mask = (positions >= starts[:, None]) & (
159
+ positions < torch.tensor(lengths, device=device)[:, None]
160
+ )
161
+ row_idx, rel = score_mask.nonzero(as_tuple=True)
162
+ tok_pos = rel + 1
163
+ picked = logits[row_idx, tok_pos - 1, :]
164
+ targets = ids[row_idx, tok_pos]
165
+ tok_ll = -F.cross_entropy(picked.float(), targets, reduction="none")
166
+ raw_t = torch.zeros(len(flats), device=device).scatter_add_(0, row_idx, tok_ll)
167
+ cnt_t = torch.zeros(len(flats), device=device).scatter_add_(
168
+ 0, row_idx, torch.ones_like(tok_ll)
169
+ )
170
+ raw_f = raw_t.cpu().tolist()
171
+ norm_f = (raw_t / cnt_t.clamp_min(1)).cpu().tolist()
172
+ for i, (item, _) in enumerate(batch):
173
+ base = 4 * i
174
+ labels.append(item["label"])
175
+ raw.append(raw_f[base : base + 4])
176
+ norm.append(norm_f[base : base + 4])
177
+ del logits, ids, mask
178
+ return [item for item, _ in prepared], labels, raw, norm
179
+
180
+
181
+ def summarize(items, labels, raw, norm) -> dict:
182
+ def pick(scores, i):
183
+ return max(range(4), key=lambda k: scores[i][k])
184
+
185
+ hit_raw = [int(pick(raw, i) == labels[i]) for i in range(len(items))]
186
+ hit_norm = [int(pick(norm, i) == labels[i]) for i in range(len(items))]
187
+
188
+ # Soft score: the probability a proper scoring rule assigns to the correct
189
+ # option after a softmax over the four continuations. Hard accuracy is
190
+ # all-or-nothing (a model either lands the exact number or not), so it sits
191
+ # at 25 % for sub-1B models; this keeps the graded signal visible.
192
+ def soft(row, label):
193
+ top = max(row)
194
+ exps = [math.exp(s - top) for s in row]
195
+ return exps[label] / sum(exps)
196
+
197
+ soft_norm = [soft(norm[i], labels[i]) for i in range(len(items))]
198
+ soft_by_depth = defaultdict(lambda: [0.0, 0])
199
+ for i, item in enumerate(items):
200
+ if item.get("depth"):
201
+ soft_by_depth[item["depth"]][0] += soft_norm[i]
202
+ soft_by_depth[item["depth"]][1] += 1
203
+
204
+ def pct(correct: int, n: int) -> float:
205
+ return 100.0 * correct / n if n else 0.0
206
+
207
+ by_depth = defaultdict(lambda: [0, 0])
208
+ by_topic = defaultdict(lambda: [0, 0])
209
+ by_template = defaultdict(lambda: [0, 0])
210
+ for i, item in enumerate(items):
211
+ if item.get("depth"):
212
+ by_depth[item["depth"]][0] += hit_norm[i]
213
+ by_depth[item["depth"]][1] += 1
214
+ by_topic[item.get("topic") or "n/a"][0] += hit_norm[i]
215
+ by_topic[item.get("topic") or "n/a"][1] += 1
216
+ by_template[item.get("template") or "n/a"][0] += hit_norm[i]
217
+ by_template[item.get("template") or "n/a"][1] += 1
218
+
219
+ n = len(items)
220
+ return {
221
+ "n": n,
222
+ "acc": pct(sum(hit_raw), n),
223
+ "acc_norm": pct(sum(hit_norm), n),
224
+ "soft": 100.0 * sum(soft_norm) / n,
225
+ "disagreements": sum(1 for a, b in zip(hit_raw, hit_norm) if a != b),
226
+ "by_depth": {
227
+ d: {
228
+ "acc_norm": pct(v[0], v[1]),
229
+ "soft": 100.0 * soft_by_depth[d][0] / soft_by_depth[d][1],
230
+ "n": v[1],
231
+ }
232
+ for d, v in sorted(by_depth.items())
233
+ },
234
+ "by_topic": {
235
+ t: {"acc_norm": pct(v[0], v[1]), "n": v[1]} for t, v in sorted(by_topic.items())
236
+ },
237
+ "by_template": {
238
+ t: {"acc_norm": pct(v[0], v[1]), "n": v[1]} for t, v in sorted(by_template.items())
239
+ },
240
+ }
241
+
242
+
243
+ def print_report(name, params, res) -> None:
244
+ print(f"\n{name} ({params:,} parameters)")
245
+ print(f" Deep Arithmark score (acc_norm) {res['acc_norm']:6.2f}%")
246
+ print(f" soft score (P[correct]) {res['soft']:6.2f}%")
247
+ print(f" raw token-sum accuracy (acc) {res['acc']:6.2f}%")
248
+ if res["by_depth"]:
249
+ print(" depth curve (acc_norm / soft):")
250
+ for depth, vals in res["by_depth"].items():
251
+ print(
252
+ f" depth {depth}: {vals['acc_norm']:6.2f}% / {vals['soft']:6.2f}%"
253
+ f" (n={vals['n']})"
254
+ )
255
+ print(" by template:")
256
+ for template, vals in sorted(res["by_template"].items(), key=lambda kv: -kv[1]["acc_norm"]):
257
+ print(f" {template:34s} {vals['acc_norm']:6.2f}% (n={vals['n']})")
258
+
259
+
260
+ def arithmark3_path() -> Path:
261
+ return Path(hf_hub_download(ARITHMARK3_REPO, ARITHMARK3_FILE, repo_type="dataset"))
262
+
263
+
264
+ def run_model(model_name, args, device, deep_items, am3_items):
265
+ model, tokenizer, dtype = load_model(model_name, device, args.dtype)
266
+ params = sum(p.numel() for p in model.parameters())
267
+ out = {"model": model_name, "params": params, "protocol": {
268
+ "dtype": str(dtype), "batch_size": args.batch_size,
269
+ "max_context": args.max_context, "shots": 0,
270
+ }}
271
+ t0 = time.perf_counter()
272
+ ordered, labels, raw, norm = score_items(
273
+ model, tokenizer, device, dtype, deep_items, args.batch_size, args.max_context
274
+ )
275
+ res = summarize(ordered, labels, raw, norm)
276
+ out["deeparithmark"] = res
277
+ print_report(model_name, params, res)
278
+ if args.dump_predictions:
279
+ target = Path(args.dump_predictions)
280
+ target.parent.mkdir(parents=True, exist_ok=True)
281
+ with target.open("a", encoding="utf-8") as fh:
282
+ for i, item in enumerate(ordered):
283
+ fh.write(
284
+ json.dumps(
285
+ {
286
+ "model": model_name,
287
+ "id": item["id"],
288
+ "depth": item.get("depth"),
289
+ "template": item.get("template"),
290
+ "label": labels[i],
291
+ "raw_pick": max(range(4), key=lambda k: raw[i][k]),
292
+ "norm_pick": max(range(4), key=lambda k: norm[i][k]),
293
+ "raw": raw[i],
294
+ "norm": norm[i],
295
+ }
296
+ )
297
+ + "\n"
298
+ )
299
+ if am3_items is not None:
300
+ ordered, labels, raw, norm = score_items(
301
+ model, tokenizer, device, dtype, am3_items, args.batch_size, args.max_context
302
+ )
303
+ am3 = summarize(ordered, labels, raw, norm)
304
+ out["arithmark3"] = am3
305
+ print(f" ArithMark 3.0 (acc_norm) {am3['acc_norm']:6.2f}% [same weights, same protocol]")
306
+ print(f" drop {am3['acc_norm'] - res['acc_norm']:+6.2f} points")
307
+ out["seconds"] = round(time.perf_counter() - t0, 2)
308
+ del model, tokenizer
309
+ gc.collect()
310
+ if device == "cuda":
311
+ torch.cuda.empty_cache()
312
+ return out
313
+
314
+
315
+ def main() -> None:
316
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
317
+ ap.add_argument("--model", action="append", help="HF model id; repeatable")
318
+ ap.add_argument("--data", default=DATA_DEFAULT)
319
+ ap.add_argument("--compare", action="store_true", help="also score ArithMark 3.0")
320
+ ap.add_argument("--arithmark3", help="local path to arithmark-3.jsonl")
321
+ ap.add_argument("--batch-size", type=int, default=BATCH_SIZE)
322
+ ap.add_argument("--max-context", type=int, default=MAX_CONTEXT)
323
+ ap.add_argument("--dtype", choices=("float32", "float16", "bfloat16"), default="bfloat16")
324
+ ap.add_argument("--device", choices=("auto", "cpu", "cuda"), default="auto")
325
+ ap.add_argument("--out", default="benchmarks")
326
+ ap.add_argument("--no-save", action="store_true")
327
+ ap.add_argument(
328
+ "--dump-predictions",
329
+ help="write per-item scores to this JSONL path for error analysis",
330
+ )
331
+ args = ap.parse_args()
332
+
333
+ torch.set_float32_matmul_precision("high")
334
+ if torch.cuda.is_available():
335
+ torch.backends.cuda.matmul.allow_tf32 = True
336
+
337
+ data_path = Path(args.data)
338
+ if not data_path.exists():
339
+ raise SystemExit(f"missing {data_path}; run `python deeparithmark.py build`")
340
+ deep_items = load_items(data_path)
341
+ sha = hashlib.sha256(data_path.read_bytes()).hexdigest()
342
+ device = resolve_device(args.device)
343
+ print(f"device: {device} | items: {len(deep_items)} | sha256: {sha[:16]}...")
344
+
345
+ am3_items = None
346
+ if args.compare or args.arithmark3:
347
+ am3_file = Path(args.arithmark3) if args.arithmark3 else arithmark3_path()
348
+ am3_items = load_items(am3_file)
349
+ print(f"comparing against ArithMark 3.0 ({len(am3_items)} items): {am3_file}")
350
+
351
+ models = args.model or DEFAULT_MODELS
352
+ results = []
353
+ for name in models:
354
+ try:
355
+ results.append(run_model(name, args, device, deep_items, am3_items))
356
+ except Exception as exc: # a broken hub repo should not kill the sweep
357
+ print(f"\n{name}: FAILED -- {str(exc).splitlines()[0]}")
358
+
359
+ if results:
360
+ print("\n" + "=" * 84)
361
+ print(f"{'model':40s} {'deep':>8s} {'soft':>8s} {'arith3':>8s}")
362
+ for r in results:
363
+ am3 = r.get("arithmark3", {}).get("acc_norm")
364
+ print(
365
+ f"{r['model']:40s} {r['deeparithmark']['acc_norm']:7.2f}%"
366
+ f" {r['deeparithmark']['soft']:7.2f}%"
367
+ + (f" {am3:7.2f}%" if am3 is not None else " -")
368
+ )
369
+ print("=" * 84)
370
+
371
+ if not args.no_save and results:
372
+ out_dir = Path(args.out)
373
+ out_dir.mkdir(parents=True, exist_ok=True)
374
+ payload = {
375
+ "dataset": {"name": "deeparithmark-1", "path": str(data_path), "sha256": sha,
376
+ "items": len(deep_items)},
377
+ "protocol": {
378
+ "shots": 0, "dtype": args.dtype, "batch_size": args.batch_size,
379
+ "max_context": args.max_context, "metric": "acc_norm",
380
+ },
381
+ "results": results,
382
+ }
383
+ target = out_dir / f"deeparithmark_{len(results)}models.json"
384
+ target.write_text(json.dumps(payload, indent=2), encoding="utf-8")
385
+ print(f"\nresults -> {target}")
386
+
387
+
388
+ if __name__ == "__main__":
389
+ main()
data/deeparithmark-1.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
deeparithmark.py ADDED
@@ -0,0 +1,1545 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Deep Arithmark — the long-horizon tier of ArithMark.
4
+
5
+ ArithMark 3.0 asks a base model to finish a two-clause word problem whose four
6
+ continuations are **adjacent integers** (43 / 44 / 45 / 46). That design has a
7
+ measurable shortcut: to reject a wrong option you only need to know that the
8
+ answer is "about 44", so magnitude smoothing wins points without arithmetic.
9
+ Every item is also one or two dependent operations, which is why the best
10
+ sub-1B model (MobileLLM-R1-140M) sits at 65.7 %.
11
+
12
+ Deep Arithmark keeps ArithMark's contract exactly -- one unfinished sentence,
13
+ four continuations with a leading space, one correct index, scored by
14
+ length-normalised continuation log-likelihood, chance 25 % -- and changes three
15
+ things:
16
+
17
+ * **Depth.** Every item needs 2-5 *dependent* operations. Later steps consume
18
+ the result of earlier steps, so you cannot get the ending by matching a
19
+ phrase to a memorised one-step template.
20
+ * **Decoys with provenance.** No decoy is "answer ± 1". Every decoy is the
21
+ exact value some specific plausible wrong reasoning produces: the state
22
+ after step 2 instead of step 4, the percentage applied to the wrong base,
23
+ the divisor n instead of n+1, the unit conversion left out, ceil instead of
24
+ floor, the a.m./p.m. carry dropped. Each ending therefore has to be judged,
25
+ not merely ranked by size. `metadata.option_sources` records, per ending,
26
+ which wrong path produced it -- the dataset is auditable, not a black box.
27
+ * **Balanced rank, not just balanced position.** ArithMark balances which
28
+ slot holds the answer, but leaves the answer's *numeric* rank free, so
29
+ "pick the largest" is worth points on the easy tiers. Here the answer's
30
+ rank among the four values is balanced too: 25 % of items have it as the
31
+ smallest, 25 % as the second, and so on. Picking a magnitude is worth 25 %.
32
+
33
+ Why this is still fair to a sub-1B model: scoring is pure continuation
34
+ log-likelihood (no chain-of-thought, no tools, no generation), items stay under
35
+ ~45 words, the whole set is 1,000 items, and it is graded in four depth tiers so
36
+ a 100M model still has a readable curve to climb instead of a single number
37
+ pinned at chance.
38
+
39
+ Usage
40
+ -----
41
+ python deeparithmark.py selftest
42
+ python deeparithmark.py build --out deeparithmark-dataset/data/deeparithmark-1.jsonl
43
+ python deeparithmark.py audit --data deeparithmark-dataset/data/deeparithmark-1.jsonl
44
+
45
+ Grading a model on it is `bench_deeparithmark.py`; the file below is also scored
46
+ unchanged by ArithMark 3.0's own `bencharithmark-3.py --data-path`, because the
47
+ record schema is identical.
48
+ """
49
+
50
+ from __future__ import annotations
51
+
52
+ import argparse
53
+ import hashlib
54
+ import json
55
+ import random
56
+ import statistics
57
+ from collections import Counter
58
+ from dataclasses import dataclass
59
+ from pathlib import Path
60
+ from typing import Callable
61
+
62
+ VERSION = "1.0"
63
+ DATASET_NAME = "deeparithmark-1"
64
+ DEPTHS = (2, 3, 4, 5)
65
+ PER_DEPTH = 250
66
+ # ranks are split 62/63/62/63 so each depth still totals exactly PER_DEPTH
67
+ RANK_QUOTAS = (62, 63, 62, 63)
68
+
69
+
70
+ # ---------------------------------------------------------------------------
71
+ # drafts: what a problem family produces before options are laid out
72
+ # ---------------------------------------------------------------------------
73
+
74
+
75
+ @dataclass
76
+ class Draft:
77
+ """One generated problem, before decoy selection and slot assignment."""
78
+
79
+ ctx: str
80
+ answer: int
81
+ # (kind, value) for every plausible wrong reasoning path we can compute.
82
+ # `kind` is a short human-readable description of the mistake.
83
+ pool: list[tuple[str, int]]
84
+ fmt: Callable[[int], str]
85
+ unit: str
86
+ topic: str
87
+ grade_band: str
88
+ difficulty: str
89
+ depth: int
90
+ steps: list[tuple[str, int]]
91
+ # number-valued options need the "no 1" rule (all endings share one plural
92
+ # unit, so " 1 boxes." would be ungrammatical *and* a giveaway).
93
+ render_is_number: bool = True
94
+
95
+
96
+ NAMES = [
97
+ "Amara", "Ben", "Chen", "Dara", "Eli", "Farid", "Greta", "Hana",
98
+ "Ivo", "Jae", "Kofi", "Lena", "Milo", "Nia", "Omar", "Priya",
99
+ "Quinn", "Rosa", "Samir", "Tara", "Umar", "Vera", "Wes", "Yara",
100
+ ]
101
+
102
+
103
+ def num(v: int, unit: str) -> str:
104
+ return f" {v} {unit}."
105
+
106
+
107
+ def dollars(v: int) -> str:
108
+ """Render an integer number of cents as a dollar amount."""
109
+ return f"${v // 100}.{v % 100:02d}"
110
+
111
+
112
+ def money(v: int) -> str:
113
+ return f" {dollars(v)}."
114
+
115
+
116
+ def _same_period(
117
+ pool: list[tuple[str, int]], window: int
118
+ ) -> list[tuple[str, int]]:
119
+ """Keep only options inside one half of the day (all a.m., or all p.m.).
120
+
121
+ Every option in a time item has to carry the same a.m./p.m. marker, or the
122
+ marker itself becomes an "odd one out" cue that needs no arithmetic.
123
+ """
124
+ low = window * 720
125
+ return [(k, v) for k, v in pool if low <= v < low + 720]
126
+
127
+
128
+ def _clock(total_minutes: int) -> str:
129
+ """Render minutes past midnight as a 12-hour clock time."""
130
+ minutes = total_minutes % (24 * 60)
131
+ hour, minute = divmod(minutes, 60)
132
+ suffix = "a.m." if hour < 12 else "p.m."
133
+ display = hour % 12 or 12
134
+ return f" {display}:{minute:02d} {suffix}"
135
+
136
+
137
+ def _ok_value(v: int) -> bool:
138
+ return v >= 0 and v != 1
139
+
140
+
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # problem families
145
+ #
146
+ # Each family returns a Draft or None when the random parameters landed on a
147
+ # degenerate case (colliding values, non-integer division, an ungrammatical
148
+ # option). The caller retries. `steps` is the real computation, so
149
+ # `answer == steps[-1][1]` by construction and selftest can assert it.
150
+ # ---------------------------------------------------------------------------
151
+
152
+
153
+ def fam_money_discount_fee(rng: random.Random) -> Draft | None:
154
+ """depth 2 - percent off, then a fixed fee (money)."""
155
+ price = rng.choice([240, 320, 380, 460, 540, 680, 720, 840, 960])
156
+ pct = rng.choice([10, 20, 25, 50])
157
+ fee = rng.choice([15, 25, 35, 45, 60])
158
+ discount = price * pct // 100
159
+ reduced = price - discount
160
+ answer = reduced + fee
161
+ ctx = (
162
+ f"At the fair, a ride pass cost {dollars(price)}. The booth took {pct}% off the pass "
163
+ f"and then charged a handling fee of {dollars(fee)}. In total, the pass cost"
164
+ )
165
+ steps = [
166
+ (f"take {pct}% of {price} off: {price} - {discount} = {reduced}", reduced),
167
+ (f"add the {fee}-cent fee: {reduced} + {fee} = {answer}", answer),
168
+ ]
169
+ flat = price - pct + fee # read "20%" as "20 cents"
170
+ pool = [
171
+ ("forgot the fee", price - discount),
172
+ ("forgot the discount", price + fee),
173
+ ("added the discount instead of removing it", price + discount + fee),
174
+ ("took the percentage off twice", price - 2 * discount + fee),
175
+ ("read the percentage as a flat number of cents", flat),
176
+ ("charged the handling fee twice", reduced + 2 * fee),
177
+ (
178
+ "took the discount off the fee as well",
179
+ (price + fee) - (price + fee) * pct // 100,
180
+ ),
181
+ ]
182
+ return Draft(
183
+ ctx=ctx,
184
+ answer=answer,
185
+ pool=pool,
186
+ fmt=money,
187
+ unit="dollars",
188
+ topic="money_percent",
189
+ grade_band="grades_4_5",
190
+ difficulty="medium",
191
+ depth=2,
192
+ steps=steps,
193
+ )
194
+
195
+
196
+ def fam_measure_cm_cut(rng: random.Random) -> Draft | None:
197
+ """depth 2 - metres+centimetres converted, then cut (measurement)."""
198
+ meters = rng.randint(2, 6)
199
+ extra = rng.choice([12, 25, 38, 47, 55, 68, 74])
200
+ cut = rng.choice([45, 60, 75, 90, 115, 130])
201
+ total = meters * 100 + extra
202
+ answer = total - cut
203
+ if answer < 20:
204
+ return None
205
+ ctx = (
206
+ f"A board was {meters} metres and {extra} centimetres long. A worker cut off "
207
+ f"{cut} centimetres. The board left was"
208
+ )
209
+ steps = [
210
+ (f"convert metres: {meters} x 100 = {meters * 100} cm", meters * 100),
211
+ (f"add the extra centimetres: {meters * 100} + {extra} = {total} cm", total),
212
+ (f"subtract the cut: {total} - {cut} = {answer} cm", answer),
213
+ ]
214
+ pool = [
215
+ ("forgot the extra centimetres", meters * 100 - cut),
216
+ ("used 10 cm to the metre", meters * 10 + extra - cut),
217
+ ("used 1000 cm to the metre", meters * 1000 + extra - cut),
218
+ ("added the cut instead of removing it", total + cut),
219
+ ("cut a whole metre off as well", total - cut - 100),
220
+ ("reported the length in whole metres", (answer // 100) * 100),
221
+ ("subtracted the cut from the centimetres only", meters * 100 + (extra - cut)),
222
+ ("added the cut and a whole metre", total + cut + 100),
223
+ ("counted the extra centimetres twice", total + extra - cut),
224
+ ("stopped ten centimetres short of the cut", total - cut + 10),
225
+ ]
226
+ return Draft(
227
+ ctx=ctx,
228
+ answer=answer,
229
+ pool=pool,
230
+ fmt=lambda v: num(v, "centimetres"),
231
+ unit="centimetres",
232
+ topic="measurement",
233
+ grade_band="grades_4_5",
234
+ difficulty="medium",
235
+ depth=3, # convert, add the extra centimetres, subtract the cut
236
+ steps=steps,
237
+ )
238
+
239
+
240
+ def fam_time_clock_end(rng: random.Random) -> Draft | None:
241
+ """depth 2 - clock time plus a duration (time)."""
242
+ start = rng.randrange(6 * 60, 8 * 60 + 45) # 06:00 .. 08:44
243
+ duration = rng.choice([50, 65, 80, 95, 110, 125])
244
+ end = start + duration
245
+ # keep the whole item inside the morning: every option has to share the
246
+ # a.m. marker, or the marker itself becomes an "odd one out" cue
247
+ if not 6 * 60 <= end <= 10 * 60 + 50:
248
+ return None
249
+ ctx = (
250
+ f"The hall was booked from {_clock(start).strip()} for {duration} minutes. "
251
+ f"The booking ended at"
252
+ )
253
+ steps = [
254
+ (f"convert the start: {start} minutes after midnight", start),
255
+ (f"add the duration: {start} + {duration} = {end} minutes", end),
256
+ ]
257
+
258
+ def fmt(v: int) -> str:
259
+ return _clock(v)
260
+
261
+ pool = [
262
+ ("dropped the hour carry", start - (start % 60) + ((start + duration) % 60)),
263
+ ("added an extra hour", end + 60),
264
+ ("subtracted the duration instead of adding it", start - duration),
265
+ ("counted the duration as hours, not minutes", start + duration * 60),
266
+ ("added the minutes without the hours", start + duration % 60),
267
+ ("counted the duration as ten minutes an hour", start + duration * 10),
268
+ ("forgot the last full hour", end - 60),
269
+ ("ran half an hour long", end + 30),
270
+ ("stopped a quarter of an hour early", end - 15),
271
+ ("ran an hour and a half long", end + 90),
272
+ ]
273
+ pool = _same_period(pool, 0)
274
+ return Draft(
275
+ ctx=ctx,
276
+ answer=end,
277
+ pool=pool,
278
+ fmt=fmt,
279
+ unit="clock time",
280
+ topic="time",
281
+ grade_band="grades_4_5",
282
+ difficulty="medium",
283
+ depth=2,
284
+ steps=steps,
285
+ render_is_number=False,
286
+ )
287
+
288
+
289
+ def fam_share_then_split(rng: random.Random) -> Draft | None:
290
+ """depth 3 - give away a third, then split the rest (fractions)."""
291
+ k = rng.choice([4, 5, 6])
292
+ # a larger per-child share keeps the four candidate values far enough apart
293
+ # that "about this big" smoothing cannot separate them
294
+ share = rng.choice([12, 15, 18, 20, 24])
295
+ rest = k * share
296
+ # rest must be two thirds of the total
297
+ total = rest * 3 // 2
298
+ if rest * 3 % 2 or total % 3:
299
+ return None
300
+ given = total // 3
301
+ if given != total - rest:
302
+ return None
303
+ if total > 400 or given < 6:
304
+ return None
305
+ baker = rng.choice(NAMES)
306
+ noun = rng.choice(["cookies", "muffins", "biscuits", "buns"])
307
+ ctx = (
308
+ f"{baker} baked {total} {noun}. One third went to a neighbour, and the rest were "
309
+ f"split equally among {k} grandchildren. Each grandchild got"
310
+ )
311
+ describe = noun
312
+ steps = [
313
+ (f"one third given away: {total} / 3 = {given}", given),
314
+ (f"rest kept: {total} - {given} = {rest}", rest),
315
+ (f"split among {k}: {rest} / {k} = {share}", share),
316
+ ]
317
+ pool = [
318
+ ("split all the cookies, not the rest", total // k),
319
+ ("gave away a half instead of a third", (total - total // 2) // k),
320
+ ("stopped after giving the third away", rest),
321
+ ("split the rest among one more child", rest // (k + 1)),
322
+ ("gave away a third twice", (rest - rest // 3) // k),
323
+ ("multiplied instead of dividing", rest * k),
324
+ ("split the given-away cookies too", given // k),
325
+ ("gave away a half and split among one more child", (total - total // 2) // (k + 1)),
326
+ ("gave away two thirds", (total - 2 * given) // k),
327
+ ("split all the cookies among one more child", total // (k + 1)),
328
+ ("split the rest among twice as many children", rest // (2 * k)),
329
+ ("gave away two thirds and split among one more child", (total - 2 * given) // (k + 1)),
330
+ ("gave away a third twice and split among one more child", (rest - rest // 3) // (k + 1)),
331
+ ("split all the cookies among two more children", total // (k + 2)),
332
+ ]
333
+ return Draft(
334
+ ctx=ctx,
335
+ answer=share,
336
+ pool=pool,
337
+ fmt=lambda v: num(v, describe),
338
+ unit=describe,
339
+ topic="fractions",
340
+ grade_band="grades_5_6",
341
+ difficulty="hard",
342
+ depth=3,
343
+ steps=steps,
344
+ )
345
+
346
+
347
+ def fam_two_rate_pay(rng: random.Random) -> Draft | None:
348
+ """depth 3 - two different hourly rates (rate/money)."""
349
+ h1 = rng.choice([3, 4, 5, 6])
350
+ h2 = rng.choice([2, 3, 4])
351
+ r1 = rng.choice([900, 1100, 1250, 1400, 1500])
352
+ r2 = r1 + rng.choice([200, 300, 400, 500])
353
+ part1 = h1 * r1
354
+ part2 = h2 * r2
355
+ answer = part1 + part2
356
+ ctx = (
357
+ f"Ravi worked {h1} hours at {dollars(r1)} an hour, and then {h2} hours at "
358
+ f"{dollars(r2)} an hour. He earned"
359
+ )
360
+ steps = [
361
+ (f"first stretch: {h1} x {r1} = {part1}", part1),
362
+ (f"second stretch: {h2} x {r2} = {part2}", part2),
363
+ (f"total pay: {part1} + {part2} = {answer}", answer),
364
+ ]
365
+ pool = [
366
+ ("paid every hour at the first rate", (h1 + h2) * r1),
367
+ ("paid every hour at the second rate", (h1 + h2) * r2),
368
+ ("forgot the second stretch", part1),
369
+ ("forgot the first stretch", part2),
370
+ ("swapped the two rates", h1 * r2 + h2 * r1),
371
+ ("added the rates together", (h1 + h2) * (r1 + r2)),
372
+ ("worked one hour less in the first stretch", (h1 - 1) * r1 + part2),
373
+ ("worked one hour less in each stretch", (h1 - 1) * r1 + (h2 - 1) * r2),
374
+ ("paid the slower rate for the whole day", (h1 + h2) * r1 // 2),
375
+ ]
376
+ return Draft(
377
+ ctx=ctx,
378
+ answer=answer,
379
+ pool=pool,
380
+ fmt=money,
381
+ unit="dollars",
382
+ topic="rate_pay",
383
+ grade_band="grades_5_6",
384
+ difficulty="hard",
385
+ depth=3,
386
+ steps=steps,
387
+ )
388
+
389
+
390
+ def fam_mix_split(rng: random.Random) -> Draft | None:
391
+ """depth 3 - mixed basket, then split (money)."""
392
+ a = rng.choice([4, 5, 6, 7, 8])
393
+ b = rng.choice([3, 4, 5, 6])
394
+ x = rng.choice([45, 60, 75, 80, 95, 120])
395
+ y = rng.choice([30, 35, 50, 65, 70])
396
+ friends = rng.choice([2, 3, 4, 5])
397
+ total = a * x + b * y
398
+ people = friends + 1
399
+ if total % people:
400
+ return None
401
+ answer = total // people
402
+ if answer < 4:
403
+ return None
404
+ ctx = (
405
+ f"Priya bought {a} markers at {dollars(x)} each and {b} erasers at {dollars(y)} "
406
+ f"each. She split the total cost equally between herself and {friends} friends. "
407
+ f"Each person paid"
408
+ )
409
+ steps = [
410
+ (f"markers: {a} x {x} = {a * x}", a * x),
411
+ (f"erasers: {b} x {y} = {b * y}", b * y),
412
+ (f"total cost: {a * x} + {b * y} = {total}", total),
413
+ (f"split between {people} people: {total} / {people} = {answer}", answer),
414
+ ]
415
+ pool = [
416
+ ("split only between the friends", total // friends),
417
+ ("divided by one person too few", total // (people - 1)),
418
+ ("forgot the erasers", (a * x) // people),
419
+ ("charged the marker price for everything", ((a + b) * x) // people),
420
+ ("swapped the two unit prices", (a * y + b * x) // people),
421
+ ("did not split the total at all", total),
422
+ ("added the unit prices instead of multiplying", (a * (x + 1) + b * (y + 1)) // people),
423
+ ("split among one more person", total // (people + 1)),
424
+ ("bought one extra of each item", ((a + 1) * x + (b + 1) * y) // people),
425
+ ("split among two more people", total // (people + 2)),
426
+ ]
427
+ return Draft(
428
+ ctx=ctx,
429
+ answer=answer,
430
+ pool=pool,
431
+ fmt=money,
432
+ unit="dollars",
433
+ topic="money",
434
+ grade_band="grades_5_6",
435
+ difficulty="hard",
436
+ depth=4, # two products, a sum, then the split
437
+ steps=steps,
438
+ )
439
+
440
+
441
+ def fam_stock_percent_pack(rng: random.Random) -> Draft | None:
442
+ """depth 3 - sell a percentage, pack the rest (percent / packing)."""
443
+ stock = rng.choice([240, 280, 320, 360, 400, 440, 480])
444
+ pct = rng.choice([15, 25, 30, 40, 55])
445
+ crate = rng.choice([6, 7, 8, 9, 12])
446
+ sold = stock * pct // 100
447
+ rest = stock - sold
448
+ answer = rest // crate
449
+ if answer < 3:
450
+ return None
451
+ ctx = (
452
+ f"A shop had {stock} shirts. It sold {pct}% of them, then packed the rest into "
453
+ f"boxes of {crate}. The number of full boxes filled was"
454
+ )
455
+ steps = [
456
+ (f"sold: {pct}% of {stock} = {sold}", sold),
457
+ (f"left over: {stock} - {sold} = {rest}", rest),
458
+ (f"full boxes: {rest} / {crate} = {answer} (remainder {rest % crate})", answer),
459
+ ]
460
+ pool = [
461
+ ("packed the whole stock, not the rest", stock // crate),
462
+ ("packed the sold shirts", sold // crate),
463
+ ("rounded the box count up", -(-rest // crate)),
464
+ ("sold twice as many", (stock - 2 * sold) // crate),
465
+ ("took the percentage off the remainder again", (rest * (100 - pct) // 100) // crate),
466
+ ("divided by the number of boxes left over", rest // max(1, rest % crate)),
467
+ ("counted the loose shirts as a box", rest // crate + 1),
468
+ ("sold half the stock regardless of the percentage", (stock - stock // 2) // crate),
469
+ ("sold only a tenth of the stock", (stock - stock // 10) // crate),
470
+ ]
471
+ return Draft(
472
+ ctx=ctx,
473
+ answer=answer,
474
+ pool=pool,
475
+ fmt=lambda v: num(v, "boxes"),
476
+ unit="boxes",
477
+ topic="percent",
478
+ grade_band="grades_6",
479
+ difficulty="hard",
480
+ depth=3,
481
+ steps=steps,
482
+ )
483
+
484
+
485
+ def fam_inventory_boxes(rng: random.Random) -> Draft | None:
486
+ """depth 4 - receive, ship, damage, then pack (multi-step)."""
487
+ start = rng.choice([420, 480, 560, 620, 700, 760, 840])
488
+ add = rng.choice([130, 180, 240, 260, 310])
489
+ ship = rng.choice([90, 140, 170, 210, 250])
490
+ damaged = rng.choice([12, 18, 24, 32, 40])
491
+ crate = rng.choice([8, 9, 12, 14, 16])
492
+ after_add = start + add
493
+ after_ship = after_add - ship
494
+ good = after_ship - damaged
495
+ answer = good // crate
496
+ if answer < 3 or good < 30:
497
+ return None
498
+ ctx = (
499
+ f"A warehouse held {start} units. A delivery added {add}, then {ship} units were "
500
+ f"shipped out, and {damaged} were found damaged. The rest were packed into crates "
501
+ f"of {crate}. The number of full crates packed was"
502
+ )
503
+ steps = [
504
+ (f"after delivery: {start} + {add} = {after_add}", after_add),
505
+ (f"after shipping: {after_add} - {ship} = {after_ship}", after_ship),
506
+ (f"good units: {after_ship} - {damaged} = {good}", good),
507
+ (f"full crates: {good} / {crate} = {answer} (remainder {good % crate})", answer),
508
+ ]
509
+ pool = [
510
+ ("forgot the damaged units", after_ship // crate),
511
+ ("forgot the shipping", (after_add - damaged) // crate),
512
+ ("added the damaged units", (after_ship + damaged) // crate),
513
+ ("shipped out twice", (after_add - 2 * ship - damaged) // crate),
514
+ ("counted the loose units as a crate", good // crate + 1),
515
+ ("stopped before packing", good),
516
+ ("packed the arriving units only", (add - damaged) // crate),
517
+ ("packed into larger crates", good // (crate + 1)),
518
+ ("shipped twice and damaged twice", (after_add - 2 * ship - 2 * damaged) // crate),
519
+ ("forgot the delivery", (start - ship - damaged) // crate),
520
+ ]
521
+ return Draft(
522
+ ctx=ctx,
523
+ answer=answer,
524
+ pool=pool,
525
+ fmt=lambda v: num(v, "crates"),
526
+ unit="crates",
527
+ topic="multi_step_inventory",
528
+ grade_band="grades_6_7",
529
+ difficulty="hard",
530
+ depth=4,
531
+ steps=steps,
532
+ )
533
+
534
+
535
+ def fam_trip_minutes(rng: random.Random) -> Draft | None:
536
+ """depth 4 - two legs at different speeds plus a rest (rate/time)."""
537
+ v1 = rng.choice([12, 15, 18, 20])
538
+ v2 = rng.choice([4, 5, 6])
539
+ d1 = v1 * rng.choice([1, 2, 3])
540
+ d2 = v2 * rng.choice([1, 2, 3])
541
+ rest = rng.choice([12, 15, 20, 25, 30])
542
+ t1 = 60 * d1 // v1
543
+ t2 = 60 * d2 // v2
544
+ answer = t1 + rest + t2
545
+ if answer < 20 or (d1 + d2) < 6:
546
+ return None
547
+ ctx = (
548
+ f"Nadia cycled {d1} km at {v1} km/h, rested {rest} minutes, then walked {d2} km "
549
+ f"at {v2} km/h. Her total time, in minutes, was"
550
+ )
551
+ steps = [
552
+ (f"cycling time: 60 x {d1} / {v1} = {t1} minutes", t1),
553
+ (f"walking time: 60 x {d2} / {v2} = {t2} minutes", t2),
554
+ (f"add the rest: {t1} + {rest} + {t2} = {answer} minutes", answer),
555
+ ]
556
+ pool = [
557
+ ("forgot the rest", t1 + t2),
558
+ ("counted the rest twice", t1 + 2 * rest + t2),
559
+ ("counted the rest as hours", t1 + t2 + 60 * rest),
560
+ ("used the cycling speed for both legs", 60 * (d1 + d2) // v1 + rest),
561
+ ("used the walking speed for both legs", 60 * (d1 + d2) // v2 + rest),
562
+ ("forgot the walking leg", t1 + rest),
563
+ ("divided by the speed twice", (t1 + t2) // max(1, v2) + rest),
564
+ ]
565
+ return Draft(
566
+ ctx=ctx,
567
+ answer=answer,
568
+ pool=pool,
569
+ fmt=lambda v: num(v, "minutes"),
570
+ unit="minutes",
571
+ topic="rate_time",
572
+ grade_band="grades_6_7",
573
+ difficulty="hard",
574
+ depth=3, # cycling time, walking time, then add the rest
575
+ steps=steps,
576
+ )
577
+
578
+
579
+ def fam_discount_tax_coupon_split(rng: random.Random) -> Draft | None:
580
+ """depth 4 - discount, tax, coupon, then split (percent/money)."""
581
+ price = rng.choice([1200, 1600, 2000, 2400, 2800, 3600])
582
+ pct = rng.choice([10, 20, 25, 30])
583
+ tax = rng.choice([5, 8, 10, 15])
584
+ coupon = rng.choice([40, 60, 80, 120])
585
+ group = rng.choice([2, 3, 4, 5])
586
+ discount = price * pct // 100
587
+ reduced = price - discount
588
+ taxed = reduced * (100 + tax)
589
+ if taxed % 100:
590
+ return None
591
+ taxed //= 100
592
+ total = taxed - coupon
593
+ if total <= 0 or total % group:
594
+ return None
595
+ answer = total // group
596
+ if answer < 4:
597
+ return None
598
+ ctx = (
599
+ f"An order cost {dollars(price)}. A {pct}% discount came off it, then {tax}% tax "
600
+ f"was added to the discounted price, and a {dollars(coupon)} coupon was applied "
601
+ f"last. {group} people split the final cost equally. Each paid"
602
+ )
603
+ steps = [
604
+ (f"discount: {price} - {discount} = {reduced}", reduced),
605
+ (f"tax on the discounted price: {reduced} + {taxed - reduced} = {taxed}", taxed),
606
+ (f"coupon: {taxed} - {coupon} = {total}", total),
607
+ (f"split {group} ways: {total} / {group} = {answer}", answer),
608
+ ]
609
+ pool = [
610
+ ("forgot the coupon", taxed // group),
611
+ ("forgot the discount", ((price * (100 + tax) // 100) - coupon) // group),
612
+ (
613
+ "taxed the price before the discount",
614
+ (((price * (100 + tax) // 100) * (100 - pct) // 100) - coupon) // group,
615
+ ),
616
+ ("forgot the discount and the coupon", (price * (100 + tax) // 100) // group),
617
+ ("split the total among one fewer person", total // (group - 1) if group > 1 else total),
618
+ ("did not split the cost at all", total),
619
+ ("added the coupon instead of subtracting it", (taxed + coupon) // group),
620
+ ("split the price before the discount", price // group),
621
+ ("used the coupon twice", (taxed - 2 * coupon) // group),
622
+ ("split the total among one more person", total // (group + 1)),
623
+ (
624
+ "applied the discount twice",
625
+ (((price - 2 * discount) * (100 + tax) // 100) - coupon) // group,
626
+ ),
627
+ ]
628
+ return Draft(
629
+ ctx=ctx,
630
+ answer=answer,
631
+ pool=pool,
632
+ fmt=money,
633
+ unit="dollars",
634
+ topic="percent_money",
635
+ grade_band="grades_7_8",
636
+ difficulty="hard",
637
+ depth=4,
638
+ steps=steps,
639
+ )
640
+
641
+
642
+ def fam_tank_fill(rng: random.Random) -> Draft | None:
643
+ """depth 4 - two fill stages, then a drain (rate)."""
644
+ start = rng.choice([120, 180, 240, 300])
645
+ r1 = rng.choice([6, 9, 12, 15])
646
+ t1 = rng.choice([4, 6, 8, 10])
647
+ r2 = rng.choice([3, 5, 7])
648
+ t2 = rng.choice([5, 7, 9])
649
+ drain = rng.choice([25, 40, 55, 70])
650
+ stage1 = r1 * t1
651
+ stage2 = r2 * t2
652
+ filled = start + stage1 + stage2
653
+ answer = filled - drain
654
+ if answer < 30:
655
+ return None
656
+ ctx = (
657
+ f"A tank held {start} litres. A pipe added {r1} litres per minute for {t1} minutes, "
658
+ f"then {r2} litres per minute for {t2} minutes. A drain then removed {drain} litres. "
659
+ f"The tank then held"
660
+ )
661
+ steps = [
662
+ (f"first fill: {r1} x {t1} = {stage1} litres", stage1),
663
+ (f"second fill: {r2} x {t2} = {stage2} litres", stage2),
664
+ (f"before draining: {start} + {stage1} + {stage2} = {filled}", filled),
665
+ (f"after draining: {filled} - {drain} = {answer}", answer),
666
+ ]
667
+ pool = [
668
+ ("forgot the drain", filled),
669
+ ("added the drain instead of removing it", filled + drain),
670
+ ("forgot the second fill", start + stage1 - drain),
671
+ ("forgot the first fill", start + stage2 - drain),
672
+ ("used the first rate for both stages", start + r1 * (t1 + t2) - drain),
673
+ ("added the rates and multiplied once", start + (r1 + r2) * (t1 + t2) - drain),
674
+ ("drained twice", filled - 2 * drain),
675
+ ]
676
+ return Draft(
677
+ ctx=ctx,
678
+ answer=answer,
679
+ pool=pool,
680
+ fmt=lambda v: num(v, "litres"),
681
+ unit="litres",
682
+ topic="rate",
683
+ grade_band="grades_6_7",
684
+ difficulty="hard",
685
+ depth=4,
686
+ steps=steps,
687
+ )
688
+
689
+
690
+ def fam_schedule_sessions(rng: random.Random) -> Draft | None:
691
+ """depth 4 - two sessions and a break across the hour (time)."""
692
+ start = rng.randrange(6 * 60, 8 * 60 + 30)
693
+ m1 = rng.choice([45, 50, 55, 60, 70])
694
+ brk = rng.choice([10, 15, 20, 25])
695
+ m2 = rng.choice([35, 40, 45, 50])
696
+ end = start + m1 + brk + m2
697
+ if not 6 * 60 <= end <= 10 * 60 + 45:
698
+ return None
699
+ ctx = (
700
+ f"Rehearsal began at {_clock(start).strip()}. The first session lasted {m1} minutes, "
701
+ f"the break lasted {brk} minutes, and the second session lasted {m2} minutes. "
702
+ f"Rehearsal ended at"
703
+ )
704
+ steps = [
705
+ (f"after the first session: {start} + {m1} = {start + m1} minutes after midnight", start + m1),
706
+ (f"after the break: {start + m1} + {brk} = {start + m1 + brk}", start + m1 + brk),
707
+ (f"after the second session: {start + m1 + brk} + {m2} = {end}", end),
708
+ ]
709
+
710
+ def fmt(v: int) -> str:
711
+ return _clock(v)
712
+
713
+ pool = [
714
+ ("forgot the break", start + m1 + m2),
715
+ ("counted the break twice", end + brk),
716
+ ("forgot the second session", start + m1 + brk),
717
+ ("counted the first session twice", start + 2 * m1 + brk + m2),
718
+ ("counted the break as hours, not minutes", end + brk * 60),
719
+ ("dropped the hour carry", start - (start % 60) + (end % 60)),
720
+ ("added the minutes but not the hours", start + (m1 + brk + m2) % 60),
721
+ ("counted the first session as hours, not minutes", start + m1 * 60 + brk + m2),
722
+ ("finished half an hour late on top of the break", end + brk + 30),
723
+ ("forgot the last session and the break", start + m1),
724
+ ]
725
+ pool = _same_period(pool, 0)
726
+ return Draft(
727
+ ctx=ctx,
728
+ answer=end,
729
+ pool=pool,
730
+ fmt=fmt,
731
+ unit="clock time",
732
+ topic="time",
733
+ grade_band="grades_6_7",
734
+ difficulty="hard",
735
+ depth=3, # three dependent additions across the hour
736
+ steps=steps,
737
+ render_is_number=False,
738
+ )
739
+
740
+
741
+ def fam_salary_overtime_tax(rng: random.Random) -> Draft | None:
742
+ """depth 5 - base pay, overtime at 1.5x, bonus, then tax (money)."""
743
+ hours = rng.choice([32, 36, 38, 40])
744
+ ot_hours = rng.choice([4, 6, 8, 10])
745
+ rate = rng.choice([1200, 1400, 1600, 1800, 2000])
746
+ bonus = rng.choice([2000, 3000, 4000, 5000])
747
+ tax = rng.choice([10, 15, 20, 25])
748
+ base = hours * rate
749
+ ot_rate = rate * 3 // 2
750
+ overtime = ot_hours * ot_rate
751
+ gross = base + overtime + bonus
752
+ if gross * tax % 100:
753
+ return None
754
+ withheld = gross * tax // 100
755
+ answer = gross - withheld
756
+ ctx = (
757
+ f"Jo worked {hours} regular hours at {dollars(rate)} an hour and {ot_hours} "
758
+ f"overtime hours at one and a half times that rate. A {dollars(bonus)} bonus was "
759
+ f"added, and then {tax}% of the total was withheld for tax. Jo took home"
760
+ )
761
+ steps = [
762
+ (f"regular pay: {hours} x {rate} = {base}", base),
763
+ (f"overtime rate: {rate} x 1.5 = {ot_rate}", ot_rate),
764
+ (f"overtime pay: {ot_hours} x {ot_rate} = {overtime}", overtime),
765
+ (f"gross with bonus: {base} + {overtime} + {bonus} = {gross}", gross),
766
+ (f"take-home: {gross} - {withheld} = {answer}", answer),
767
+ ]
768
+ gross_no_bonus = base + overtime
769
+ pool = [
770
+ ("forgot the tax", gross),
771
+ ("added the tax instead of withholding it", gross + withheld),
772
+ ("forgot the bonus", gross_no_bonus - gross_no_bonus * tax // 100),
773
+ ("paid overtime at the normal rate", (base + ot_hours * rate + bonus) - (base + ot_hours * rate + bonus) * tax // 100),
774
+ ("taxed only the regular pay", gross - base * tax // 100),
775
+ ("paid overtime at double rate", (base + 2 * ot_hours * rate + bonus) - (base + 2 * ot_hours * rate + bonus) * tax // 100),
776
+ ("forgot the overtime", (base + bonus) - (base + bonus) * tax // 100),
777
+ ("taxed twice", gross - 2 * withheld),
778
+ ]
779
+ return Draft(
780
+ ctx=ctx,
781
+ answer=answer,
782
+ pool=pool,
783
+ fmt=money,
784
+ unit="dollars",
785
+ topic="money_rate",
786
+ grade_band="grades_7_8",
787
+ difficulty="hard",
788
+ depth=5,
789
+ steps=steps,
790
+ )
791
+
792
+
793
+ def fam_inventory_percent_chain(rng: random.Random) -> Draft | None:
794
+ """depth 5 - two percentage days, then palletising."""
795
+ stock = rng.choice([600, 800, 1000, 1200, 1400, 1600])
796
+ p1 = rng.choice([10, 20, 25, 30])
797
+ p2 = rng.choice([10, 20, 25, 40])
798
+ pallet = rng.choice([8, 10, 12, 15])
799
+ monday = stock * p1 // 100
800
+ rem1 = stock - monday
801
+ tuesday = rem1 * p2 // 100
802
+ rem2 = rem1 - tuesday
803
+ answer = rem2 // pallet
804
+ if answer < 3 or rem2 < 40:
805
+ return None
806
+ ctx = (
807
+ f"A depot held {stock} sacks. It sent out {p1}% of them on Monday and {p2}% of the "
808
+ f"remainder on Tuesday. The rest were stacked on pallets of {pallet}. "
809
+ f"The number of full pallets was"
810
+ )
811
+ steps = [
812
+ (f"Monday: {p1}% of {stock} = {monday}", monday),
813
+ (f"left after Monday: {stock} - {monday} = {rem1}", rem1),
814
+ (f"Tuesday: {p2}% of {rem1} = {tuesday}", tuesday),
815
+ (f"left after Tuesday: {rem1} - {tuesday} = {rem2}", rem2),
816
+ (f"full pallets: {rem2} / {pallet} = {answer}", answer),
817
+ ]
818
+ pool = [
819
+ (
820
+ "took both percentages off the original stock",
821
+ (stock - stock * p1 // 100 - stock * p2 // 100) // pallet,
822
+ ),
823
+ ("forgot Tuesday", rem1 // pallet),
824
+ ("forgot Monday", (stock - tuesday) // pallet),
825
+ (
826
+ "took the second percentage off the original stock",
827
+ (rem1 - stock * p2 // 100) // pallet,
828
+ ),
829
+ ("counted the loose sacks as a pallet", rem2 // pallet + 1),
830
+ ("stopped before palletising", rem2),
831
+ ("stacked on larger pallets", rem2 // (pallet + 1)),
832
+ ("added the two percentages", (stock - stock * (p1 + p2) // 100) // pallet),
833
+ ("took both percentages twice", (stock - 2 * monday - 2 * tuesday) // pallet),
834
+ ]
835
+ return Draft(
836
+ ctx=ctx,
837
+ answer=answer,
838
+ pool=pool,
839
+ fmt=lambda v: num(v, "pallets"),
840
+ unit="pallets",
841
+ topic="percent_multi_step",
842
+ grade_band="grades_7_8",
843
+ difficulty="hard",
844
+ depth=5, # two percentage days, then palletising
845
+ steps=steps,
846
+ )
847
+
848
+
849
+ def fam_prize_ratio_charity(rng: random.Random) -> Draft | None:
850
+ """depth 5 - fee, ratio split, charity cut, then split among players."""
851
+ parts_a = rng.choice([2, 3, 4, 5])
852
+ parts_b = rng.choice([1, 2, 3])
853
+ if parts_a <= parts_b:
854
+ return None
855
+ unit = rng.choice([30, 40, 50, 60, 70])
856
+ fee = rng.choice([200, 300, 400, 500])
857
+ charity = rng.choice([10, 20, 25, 50])
858
+ players = rng.choice([4, 5, 8])
859
+ prize = (parts_a + parts_b) * unit + fee
860
+ share = parts_a * unit
861
+ charity_cut = share * charity // 100
862
+ kept = share - charity_cut
863
+ if kept % players or kept == 0:
864
+ return None
865
+ answer = kept // players
866
+ if answer < 4:
867
+ return None
868
+ ctx = (
869
+ f"A prize of {dollars(prize)} was split between two teams in the ratio "
870
+ f"{parts_a}:{parts_b} after a {dollars(fee)} fee was deducted. The larger team gave "
871
+ f"{charity}% of its share to charity and split the rest equally among its {players} "
872
+ f"players. Each player got"
873
+ )
874
+ steps = [
875
+ (f"after the fee: {prize} - {fee} = {prize - fee}", prize - fee),
876
+ (f"one ratio part: {prize - fee} / {parts_a + parts_b} = {unit}", unit),
877
+ (f"larger share: {parts_a} x {unit} = {share}", share),
878
+ (f"after charity: {share} - {charity_cut} = {kept}", kept),
879
+ (f"per player: {kept} / {players} = {answer}", answer),
880
+ ]
881
+ pre_fee = prize // (parts_a + parts_b)
882
+ pool = [
883
+ ("forgot to deduct the fee", (pre_fee * parts_a) // players),
884
+ ("gave the larger share to the smaller ratio", (parts_b * unit) // players),
885
+ ("forgot the charity cut", share // players),
886
+ ("split the whole prize among one team", (prize - fee) // players),
887
+ ("divided between the teams instead of the players", kept // 2),
888
+ (
889
+ "took the charity cut off the whole prize",
890
+ ((prize - fee) - (prize - fee) * charity // 100) // players,
891
+ ),
892
+ (
893
+ "swapped the ratio parts",
894
+ ((parts_b * unit) - (parts_b * unit) * charity // 100) // players,
895
+ ),
896
+ ("split among one more player", kept // (players + 1)),
897
+ ("gave twice the share away to charity", (share - 2 * charity_cut) // players),
898
+ ("forgot the fee and the charity cut", ((prize - fee) // 2) // players),
899
+ ]
900
+ return Draft(
901
+ ctx=ctx,
902
+ answer=answer,
903
+ pool=pool,
904
+ fmt=money,
905
+ unit="dollars",
906
+ topic="ratio",
907
+ grade_band="grades_7_8",
908
+ difficulty="hard",
909
+ depth=5,
910
+ steps=steps,
911
+ )
912
+
913
+
914
+ FAMILIES: dict[int, list[Callable[[random.Random], Draft | None]]] = {
915
+ 2: [fam_money_discount_fee, fam_time_clock_end],
916
+ 3: [
917
+ fam_measure_cm_cut,
918
+ fam_share_then_split,
919
+ fam_two_rate_pay,
920
+ fam_stock_percent_pack,
921
+ fam_trip_minutes,
922
+ fam_schedule_sessions,
923
+ ],
924
+ 4: [
925
+ fam_inventory_boxes,
926
+ fam_discount_tax_coupon_split,
927
+ fam_tank_fill,
928
+ fam_mix_split,
929
+ ],
930
+ 5: [fam_salary_overtime_tax, fam_inventory_percent_chain, fam_prize_ratio_charity],
931
+ }
932
+
933
+
934
+ # ---------------------------------------------------------------------------
935
+ # assembling four options from a draft
936
+ # ---------------------------------------------------------------------------
937
+
938
+
939
+ @dataclass
940
+ class Assembled:
941
+ draft: Draft
942
+ decoys: list[tuple[str, int]] # exactly 3 wrong-path (kind, value) pairs
943
+
944
+ @property
945
+ def rank(self) -> int:
946
+ """0 = answer is the smallest of the four, 3 = the largest."""
947
+ answer = self.draft.answer
948
+ return sum(1 for _, v in self.decoys if v < answer)
949
+
950
+ def slots(self, label: int) -> tuple[list[int], list[str]]:
951
+ """Lay the answer at `label` and the decoys in the remaining slots."""
952
+ values: list[int] = []
953
+ sources: list[str] = []
954
+ remaining = list(self.decoys)
955
+ for slot in range(4):
956
+ if slot == label:
957
+ values.append(self.draft.answer)
958
+ sources.append("correct")
959
+ else:
960
+ kind, value = remaining.pop(0)
961
+ values.append(value)
962
+ sources.append(kind)
963
+ return values, sources
964
+
965
+
966
+ def roundness(v: int) -> int:
967
+ """How "prototypical" a number looks: trailing zeros, capped at 3."""
968
+ if v == 0:
969
+ return 3
970
+ score = 0
971
+ while v % 10 == 0 and score < 3:
972
+ v //= 10
973
+ score += 1
974
+ return score
975
+
976
+
977
+ def _implausible(value: int, answer: int) -> bool:
978
+ """Reject decoys a reader would eliminate without doing any arithmetic.
979
+
980
+ A decoy that is an order of magnitude off, or several powers of ten rounder
981
+ than the answer, is not a reasoning trap -- it is a surface cue, and a base
982
+ model will simply pick whichever option looks most prototypical. Both cases
983
+ showed up in error analysis (gpt2 picked a "roundest option" on 84 % of
984
+ items and scored far below chance as a result).
985
+ """
986
+ if answer > 0 and (value > 4 * answer or value * 4 < answer):
987
+ return True
988
+ # Same roundness class as the answer. A number's "naturalness" (trailing
989
+ # zeros) is the one surface feature a base model reliably smooths toward, so
990
+ # if the correct option is systematically the least round one, a model that
991
+ # cannot compute scores *below* chance. Keeping all four in one class makes
992
+ # the options exchangeable under the model's no-skill prior.
993
+ return roundness(value) != roundness(answer)
994
+
995
+
996
+ def _too_clustered(values: list[int]) -> bool:
997
+ """Reject option sets where three or more values are consecutive integers.
998
+
999
+ One near-miss is a legitimate boundary error (floor vs ceil). A whole run of
1000
+ adjacent integers is ArithMark 3.0's shortcut and is what we are removing.
1001
+ """
1002
+ ordered = sorted(values)
1003
+ gaps_of_one = sum(1 for a, b in zip(ordered, ordered[1:]) if b - a == 1)
1004
+ return gaps_of_one >= 2
1005
+
1006
+
1007
+ def assemble(
1008
+ draft: Draft, rng: random.Random, target_rank: int, max_tries: int = 40
1009
+ ) -> Assembled | None:
1010
+ """Pick three wrong-path values so the answer lands at `target_rank`."""
1011
+ answer = draft.answer
1012
+ seen: set[int] = set()
1013
+ pool: list[tuple[str, int]] = []
1014
+ for kind, value in draft.pool:
1015
+ if not isinstance(value, int) or value == answer or value in seen:
1016
+ continue
1017
+ if draft.render_is_number and not _ok_value(value):
1018
+ continue
1019
+ if _implausible(value, answer):
1020
+ continue
1021
+ seen.add(value)
1022
+ pool.append((kind, value))
1023
+ below = [(k, v) for k, v in pool if v < answer]
1024
+ above = [(k, v) for k, v in pool if v > answer]
1025
+ want_below = target_rank
1026
+ want_above = 3 - target_rank
1027
+ if len(below) < want_below or len(above) < want_above:
1028
+ return None
1029
+ for _ in range(max_tries):
1030
+ chosen = rng.sample(below, want_below) + rng.sample(above, want_above)
1031
+ values = [answer] + [v for _, v in chosen]
1032
+ if len(set(values)) != 4:
1033
+ continue
1034
+ if draft.render_is_number and any(not _ok_value(v) for v in values):
1035
+ continue
1036
+ if _too_clustered(values):
1037
+ continue
1038
+ return Assembled(draft=draft, decoys=chosen)
1039
+ return None
1040
+
1041
+
1042
+ # ---------------------------------------------------------------------------
1043
+ # dataset build
1044
+ # ---------------------------------------------------------------------------
1045
+
1046
+
1047
+ def _activity_label(draft: Draft) -> str:
1048
+ return (
1049
+ f"deeparithmark::{DATASET_NAME}::{draft.topic}::"
1050
+ f"depth{draft.depth}::{draft.difficulty}"
1051
+ )
1052
+
1053
+
1054
+ def _record(a: Assembled, index: int, label: int, template_id: str) -> dict:
1055
+ d = a.draft
1056
+ values, sources = a.slots(label)
1057
+ endings = [d.fmt(v) for v in values]
1058
+ assert sources[label] == "correct"
1059
+ assert values[label] == d.answer
1060
+ return {
1061
+ "ind": index,
1062
+ "activity_label": _activity_label(d),
1063
+ "ctx_a": d.ctx,
1064
+ "ctx_b": "",
1065
+ "ctx": d.ctx,
1066
+ "endings": endings,
1067
+ "source_id": f"deeparithmark_v1_{d.topic}_depth{d.depth}_{index:04d}",
1068
+ "split": "test",
1069
+ "split_type": "synthetic",
1070
+ "label": str(label),
1071
+ "metadata": {
1072
+ "answer": str(d.answer),
1073
+ "unit": d.unit,
1074
+ "topic": d.topic,
1075
+ "difficulty": d.difficulty,
1076
+ "grade_band": d.grade_band,
1077
+ "template_id": template_id,
1078
+ "depth": d.depth,
1079
+ "option_sources": sources,
1080
+ "solution_steps": [text for text, _ in d.steps],
1081
+ "option_values": values,
1082
+ "answer_rank": a.rank,
1083
+ "format_note": (
1084
+ "Continuation-style prompt for base-model log-likelihood scoring; "
1085
+ "endings include leading spaces and share one unit phrase."
1086
+ ),
1087
+ },
1088
+ }
1089
+
1090
+
1091
+ def template_id_for(fn: Callable) -> str:
1092
+ return fn.__name__.removeprefix("fam_")
1093
+
1094
+
1095
+ def build(seed: int = 20261027, total_depths: int = PER_DEPTH) -> list[dict]:
1096
+ """Generate the balanced dataset, deterministically for a given seed."""
1097
+ rng = random.Random(seed)
1098
+ records: list[dict] = []
1099
+ used_ctx: set[str] = set()
1100
+ shortfall: Counter = Counter()
1101
+ index = 0
1102
+ for depth in DEPTHS:
1103
+ families = FAMILIES[depth]
1104
+ slot_rotation = 0
1105
+ for rank, quota in enumerate(RANK_QUOTAS):
1106
+ need = round(quota * total_depths / PER_DEPTH)
1107
+ produced = 0
1108
+ # stagger which family leads each rank bucket, so no topic is
1109
+ # confined to one rank, then split the cell evenly across families
1110
+ rotation = rank % len(families)
1111
+ order = families[rotation:] + families[:rotation]
1112
+ shares = [need // len(order)] * len(order)
1113
+ for i in range(need - sum(shares)):
1114
+ shares[i] += 1
1115
+ for family, want in zip(order, shares):
1116
+ got = 0
1117
+ attempts = 0
1118
+ while got < want and attempts < 8000:
1119
+ attempts += 1
1120
+ draft = family(rng)
1121
+ if draft is None:
1122
+ continue
1123
+ a = assemble(draft, rng, rank)
1124
+ if a is None:
1125
+ continue
1126
+ if draft.ctx in used_ctx:
1127
+ continue
1128
+ if not draft.steps or draft.steps[-1][1] != draft.answer:
1129
+ raise AssertionError(
1130
+ f"{family.__name__} produced an inconsistent chain"
1131
+ )
1132
+ used_ctx.add(draft.ctx)
1133
+ # the answer slot rotates so label counts stay flat per depth
1134
+ label = slot_rotation % 4
1135
+ slot_rotation += 1
1136
+ records.append(_record(a, index, label, template_id_for(family)))
1137
+ index += 1
1138
+ got += 1
1139
+ produced += 1
1140
+ # a family that cannot reach this rank hands its share to the others
1141
+ attempts = 0
1142
+ while produced < need and attempts < 60000:
1143
+ attempts += 1
1144
+ family = order[attempts % len(order)]
1145
+ draft = family(rng)
1146
+ if draft is None:
1147
+ continue
1148
+ a = assemble(draft, rng, rank)
1149
+ if a is None or draft.ctx in used_ctx:
1150
+ continue
1151
+ if not draft.steps or draft.steps[-1][1] != draft.answer:
1152
+ raise AssertionError(
1153
+ f"{family.__name__} produced an inconsistent chain"
1154
+ )
1155
+ used_ctx.add(draft.ctx)
1156
+ label = slot_rotation % 4
1157
+ slot_rotation += 1
1158
+ records.append(_record(a, index, label, template_id_for(family)))
1159
+ index += 1
1160
+ produced += 1
1161
+ if produced < need:
1162
+ shortfall[(depth, rank)] = need - produced
1163
+ if shortfall:
1164
+ raise RuntimeError(
1165
+ "could not fill every (depth, rank) cell; widen the parameter ranges: "
1166
+ f"{dict(shortfall)}"
1167
+ )
1168
+ rng.shuffle(records)
1169
+ for i, rec in enumerate(records):
1170
+ rec["ind"] = i
1171
+ rec["source_id"] = (
1172
+ f"deeparithmark_v1_{rec['metadata']['topic']}_"
1173
+ f"depth{rec['metadata']['depth']}_{i:04d}"
1174
+ )
1175
+ return records
1176
+
1177
+
1178
+ # ---------------------------------------------------------------------------
1179
+ # validation
1180
+ # ---------------------------------------------------------------------------
1181
+
1182
+
1183
+ def load_jsonl(path: Path) -> list[dict]:
1184
+ out = []
1185
+ with path.open(encoding="utf-8-sig") as fh:
1186
+ for line_no, line in enumerate(fh, 1):
1187
+ if not line.strip():
1188
+ continue
1189
+ try:
1190
+ out.append(json.loads(line))
1191
+ except json.JSONDecodeError as exc:
1192
+ raise ValueError(f"{path}:{line_no}: invalid JSON") from exc
1193
+ return out
1194
+
1195
+
1196
+ def validate(records: list[dict], verbose: bool = True) -> dict:
1197
+ """Assert every structural invariant the benchmark claims to have."""
1198
+ problems: list[str] = []
1199
+ ctx_seen: Counter = Counter()
1200
+ depth_c: Counter = Counter()
1201
+ rank_c: Counter = Counter()
1202
+ label_c: Counter = Counter()
1203
+ topic_c: Counter = Counter()
1204
+ template_c: Counter = Counter()
1205
+ grid: Counter = Counter()
1206
+ adjacent_items = 0
1207
+
1208
+ for rec in records:
1209
+ rid = rec.get("ind")
1210
+ ctx = rec.get("ctx")
1211
+ endings = rec.get("endings")
1212
+ try:
1213
+ label = int(rec.get("label"))
1214
+ except (TypeError, ValueError):
1215
+ problems.append(f"{rid}: label is not an int")
1216
+ continue
1217
+ if not isinstance(ctx, str) or not ctx.strip():
1218
+ problems.append(f"{rid}: empty ctx")
1219
+ continue
1220
+ if not isinstance(endings, list) or len(endings) != 4:
1221
+ problems.append(f"{rid}: expected exactly 4 endings")
1222
+ continue
1223
+ if not 0 <= label < 4:
1224
+ problems.append(f"{rid}: label out of range")
1225
+ continue
1226
+ if not all(isinstance(e, str) and e.startswith(" ") for e in endings):
1227
+ problems.append(f"{rid}: an ending lost its leading space")
1228
+ if len(set(endings)) != 4:
1229
+ problems.append(f"{rid}: duplicate endings")
1230
+ # every option must share the unit phrase: strip the leading number/time
1231
+ tails = {_unit_of(e) for e in endings}
1232
+ if len(tails) != 1:
1233
+ problems.append(f"{rid}: options have different unit phrases {tails}")
1234
+ if re_has_value_one(endings):
1235
+ problems.append(f"{rid}: option value 1 with a plural unit")
1236
+ meta = rec["metadata"]
1237
+ values = meta.get("option_values")
1238
+ if not isinstance(values, list) or len(values) != 4:
1239
+ problems.append(f"{rid}: option_values missing")
1240
+ values = None
1241
+ elif int(meta["answer"]) != values[label]:
1242
+ problems.append(f"{rid}: label does not point at the answer value")
1243
+ if values:
1244
+ rank = sum(1 for v in values if v < values[label])
1245
+ if rank != meta.get("answer_rank"):
1246
+ problems.append(f"{rid}: answer_rank does not match values")
1247
+ ordered = sorted(values)
1248
+ if sum(1 for a, b in zip(ordered, ordered[1:]) if b - a == 1) >= 2:
1249
+ adjacent_items += 1
1250
+ problems.append(f"{rid}: options cluster on consecutive integers")
1251
+ if len(set(values)) != 4:
1252
+ problems.append(f"{rid}: duplicate option values")
1253
+ sources = meta.get("option_sources")
1254
+ if not isinstance(sources, list) or len(sources) != 4:
1255
+ problems.append(f"{rid}: option_sources missing")
1256
+ elif sources[label] != "correct":
1257
+ problems.append(f"{rid}: option_sources is not aligned with the label")
1258
+ if not meta.get("depth") in DEPTHS:
1259
+ problems.append(f"{rid}: bad depth")
1260
+ steps = meta.get("solution_steps")
1261
+ if not steps:
1262
+ problems.append(f"{rid}: missing solution_steps")
1263
+ elif len(steps) != meta.get("depth"):
1264
+ problems.append(
1265
+ f"{rid}: {len(steps)} solution steps but declared depth {meta.get('depth')}"
1266
+ )
1267
+ ctx_seen[ctx] += 1
1268
+ depth_c[meta.get("depth")] += 1
1269
+ rank_c[meta.get("answer_rank")] += 1
1270
+ label_c[label] += 1
1271
+ topic_c[meta.get("topic")] += 1
1272
+ template_c[meta.get("template_id")] += 1
1273
+ grid[(meta.get("depth"), meta.get("answer_rank"), label)] += 1
1274
+
1275
+ dupes = [c for c, n in ctx_seen.items() if n > 1]
1276
+ if dupes:
1277
+ problems.append(f"{len(dupes)} duplicated prompts")
1278
+
1279
+ n = len(records)
1280
+ balance = {
1281
+ "n": n,
1282
+ "depth": dict(sorted(depth_c.items())),
1283
+ "rank": dict(sorted(rank_c.items())),
1284
+ "label": dict(sorted(label_c.items())),
1285
+ "topic": dict(sorted(topic_c.items())),
1286
+ "templates": len(template_c),
1287
+ "worst_grid_cell": min(grid.values()) if grid else 0,
1288
+ "best_grid_cell": max(grid.values()) if grid else 0,
1289
+ "adjacent_option_items": adjacent_items,
1290
+ }
1291
+ if verbose:
1292
+ print(f"items: {n}")
1293
+ print(f"depth: {balance['depth']}")
1294
+ print(f"answer rank: {balance['rank']}")
1295
+ print(f"label slot: {balance['label']}")
1296
+ print(f"topics: {balance['topic']}")
1297
+ print(f"templates: {balance['templates']}")
1298
+ print(
1299
+ f"(depth, rank, slot) grid: {balance['worst_grid_cell']}"
1300
+ f"..{balance['best_grid_cell']} items per cell"
1301
+ )
1302
+ print(f"options clustering on consecutive ints: {adjacent_items} items")
1303
+ if problems:
1304
+ print(f"\nPROBLEMS ({len(problems)}):")
1305
+ for p in problems[:20]:
1306
+ print(" -", p)
1307
+ return {"problems": problems, "balance": balance}
1308
+
1309
+
1310
+ def _unit_of(ending: str) -> str:
1311
+ """The part of an ending after its leading numeric/time token."""
1312
+ text = ending.strip()
1313
+ parts = text.split(" ")
1314
+ return " ".join(parts[1:]) if len(parts) > 1 else ""
1315
+
1316
+
1317
+ def re_has_value_one(endings: list[str]) -> bool:
1318
+ for e in endings:
1319
+ head = e.strip().split(" ")[0]
1320
+ if head == "1":
1321
+ return True
1322
+ return False
1323
+
1324
+
1325
+ # ---------------------------------------------------------------------------
1326
+ # shortcut audit: prove the options cannot be gamed without arithmetic
1327
+ # ---------------------------------------------------------------------------
1328
+
1329
+
1330
+ def audit(records: list[dict], seeds: int = 5) -> dict:
1331
+ """Measure what a model can score without doing any arithmetic.
1332
+
1333
+ Baselines that need no reasoning at all (pick largest / pick a fixed slot /
1334
+ pick the longest string) plus a trained character-n-gram classifier over the
1335
+ option text. If the last one clears ~25 % the option strings leak the answer
1336
+ and the benchmark is broken, whatever the model scores say.
1337
+ """
1338
+ import numpy as np
1339
+
1340
+ n = len(records)
1341
+ report: dict = {}
1342
+
1343
+ def acc(picker) -> float:
1344
+ hits = 0
1345
+ for rec in records:
1346
+ if picker(rec) == int(rec["label"]):
1347
+ hits += 1
1348
+ return 100.0 * hits / n
1349
+
1350
+ def numeric(rec):
1351
+ return rec["metadata"].get("option_values")
1352
+
1353
+ def pick_largest(rec):
1354
+ v = numeric(rec)
1355
+ return max(range(4), key=lambda i: v[i]) if v else 0
1356
+
1357
+ def pick_smallest(rec):
1358
+ v = numeric(rec)
1359
+ return min(range(4), key=lambda i: v[i]) if v else 0
1360
+
1361
+ def pick_median(rec):
1362
+ v = numeric(rec)
1363
+ if not v:
1364
+ return 0
1365
+ order = sorted(range(4), key=lambda i: v[i])
1366
+ return order[1]
1367
+
1368
+ def pick_roundest(rec):
1369
+ values = numeric(rec)
1370
+ if not values:
1371
+ return 0
1372
+ return max(range(4), key=lambda i: roundness(values[i]))
1373
+
1374
+ def pick_longest(rec):
1375
+ return max(range(4), key=lambda i: len(rec["endings"][i]))
1376
+
1377
+ def pick_shortest(rec):
1378
+ return min(range(4), key=lambda i: len(rec["endings"][i]))
1379
+
1380
+ report["pick_largest"] = acc(pick_largest)
1381
+ report["pick_smallest"] = acc(pick_smallest)
1382
+ report["pick_second_smallest"] = acc(pick_median)
1383
+ report["pick_roundest"] = acc(pick_roundest)
1384
+ report["pick_longest"] = acc(pick_longest)
1385
+ report["pick_shortest"] = acc(pick_shortest)
1386
+ report["fixed_slot"] = [
1387
+ acc(lambda rec, s=s: s) for s in range(4)
1388
+ ]
1389
+
1390
+ # character n-gram logistic regression over the option text only
1391
+ def features(text: str) -> np.ndarray:
1392
+ text = text.strip().lower()
1393
+ grams = [text[i : i + 3] for i in range(max(1, len(text) - 2))]
1394
+ grams += [f"#{g}" for g in text.split(" ")[0][:4]]
1395
+ return grams
1396
+
1397
+ def run_probe(seed: int) -> float:
1398
+ rng = random.Random(seed)
1399
+ idx = list(range(n))
1400
+ rng.shuffle(idx)
1401
+ cut = int(0.7 * n)
1402
+ train, test = idx[:cut], idx[cut:]
1403
+ vocab: dict[str, int] = {}
1404
+ X, y = [], []
1405
+ for i in train:
1406
+ rec = records[i]
1407
+ for slot in range(4):
1408
+ y.append(1 if slot == int(rec["label"]) else 0)
1409
+ X.append(features(rec["endings"][slot]))
1410
+ for gs in X:
1411
+ for g in gs:
1412
+ if g not in vocab:
1413
+ vocab[g] = len(vocab)
1414
+ dim = len(vocab) + 1
1415
+ Xm = np.zeros((len(X), dim), dtype=np.float32)
1416
+ for r, gs in enumerate(X):
1417
+ for g in gs:
1418
+ Xm[r, vocab[g]] += 1.0
1419
+ Xm[:, -1] = 1.0 # bias
1420
+ Xm /= np.maximum(1.0, Xm.sum(axis=1, keepdims=True))
1421
+ ym = np.array(y, dtype=np.float32)
1422
+ w = np.zeros(dim, dtype=np.float32)
1423
+ lr, l2 = 0.5, 1e-4
1424
+ for _ in range(300):
1425
+ p = 1.0 / (1.0 + np.exp(-(Xm @ w)))
1426
+ grad = Xm.T @ (p - ym) / len(ym) + l2 * w
1427
+ w -= lr * grad
1428
+ hits = 0
1429
+ for i in test:
1430
+ rec = records[i]
1431
+ scores = []
1432
+ for slot in range(4):
1433
+ gs = features(rec["endings"][slot])
1434
+ vec = np.zeros(dim, dtype=np.float32)
1435
+ for g in gs:
1436
+ if g in vocab:
1437
+ vec[vocab[g]] += 1.0
1438
+ vec[-1] = 1.0
1439
+ vec /= max(1.0, vec.sum())
1440
+ scores.append(float(vec @ w))
1441
+ if max(range(4), key=lambda s: scores[s]) == int(rec["label"]):
1442
+ hits += 1
1443
+ return 100.0 * hits / len(test)
1444
+
1445
+ probe = [run_probe(1000 + s) for s in range(seeds)]
1446
+ report["ngram_probe"] = probe
1447
+ report["ngram_probe_mean"] = statistics.mean(probe)
1448
+ report["ngram_probe_max"] = max(probe)
1449
+ report["chance"] = 25.0
1450
+
1451
+ print("\nshortcut audit (chance = 25.00%)")
1452
+ print(f" pick largest value {report['pick_largest']:6.2f}%")
1453
+ print(f" pick smallest value {report['pick_smallest']:6.2f}%")
1454
+ print(f" pick second smallest {report['pick_second_smallest']:6.2f}%")
1455
+ print(f" pick roundest number {report['pick_roundest']:6.2f}%")
1456
+ print(f" pick longest option text {report['pick_longest']:6.2f}%")
1457
+ print(f" pick shortest option text {report['pick_shortest']:6.2f}%")
1458
+ print(" fixed slot " + " ".join(f"{v:6.2f}%" for v in report["fixed_slot"]))
1459
+ print(
1460
+ f" char-3gram probe (mean) {report['ngram_probe_mean']:6.2f}%"
1461
+ f" (max {report['ngram_probe_max']:.2f}% over {seeds} splits)"
1462
+ )
1463
+ worst = max(
1464
+ [
1465
+ report["pick_largest"],
1466
+ report["pick_smallest"],
1467
+ report["pick_roundest"],
1468
+ report["ngram_probe_mean"],
1469
+ ]
1470
+ )
1471
+ report["worst_shortcut"] = worst
1472
+ if worst > 30.0:
1473
+ print(f" WARNING: a shortcut reaches {worst:.2f}% -- options leak the answer")
1474
+ else:
1475
+ print(" OK: no shortcut materially beats chance")
1476
+ return report
1477
+
1478
+
1479
+ # ---------------------------------------------------------------------------
1480
+ # CLI
1481
+ # ---------------------------------------------------------------------------
1482
+
1483
+
1484
+ def cmd_build(args) -> None:
1485
+ records = build(seed=args.seed, total_depths=args.per_depth)
1486
+ out = Path(args.out)
1487
+ out.parent.mkdir(parents=True, exist_ok=True)
1488
+ with out.open("w", encoding="utf-8") as fh:
1489
+ for rec in records:
1490
+ fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
1491
+ digest = hashlib.sha256(out.read_bytes()).hexdigest()
1492
+ print(f"wrote {len(records)} items to {out}")
1493
+ print(f"sha256: {digest}")
1494
+
1495
+
1496
+ def cmd_selftest(args) -> None:
1497
+ path = Path(args.data)
1498
+ if not path.exists():
1499
+ raise SystemExit(f"missing {path}; run `build` first")
1500
+ records = load_jsonl(path)
1501
+ result = validate(records)
1502
+ if result["problems"]:
1503
+ raise SystemExit(f"{len(result['problems'])} validation problems")
1504
+ # ArithMark 3.0's own loader rules, repeated here so compatibility is checked
1505
+ for rec in records:
1506
+ assert rec["ctx"] and rec["endings"] and len(rec["endings"]) >= 2
1507
+ assert all(e.startswith(" ") for e in rec["endings"])
1508
+ assert all(isinstance(e, str) and e for e in rec["endings"])
1509
+ int(rec["label"])
1510
+ print("\nselftest: OK (schema matches ArithMark 3.0; all invariants hold)")
1511
+ if not args.no_audit:
1512
+ audit(records)
1513
+
1514
+
1515
+ def cmd_audit(args) -> None:
1516
+ records = load_jsonl(Path(args.data))
1517
+ validate(records, verbose=False)
1518
+ audit(records)
1519
+
1520
+
1521
+ def main() -> None:
1522
+ ap = argparse.ArgumentParser(description=__doc__)
1523
+ sub = ap.add_subparsers(dest="cmd", required=True)
1524
+
1525
+ b = sub.add_parser("build", help="generate the dataset")
1526
+ b.add_argument("--out", default=f"deeparithmark-dataset/data/{DATASET_NAME}.jsonl")
1527
+ b.add_argument("--seed", type=int, default=20261027)
1528
+ b.add_argument("--per-depth", type=int, default=PER_DEPTH)
1529
+ b.set_defaults(func=cmd_build)
1530
+
1531
+ s = sub.add_parser("selftest", help="validate the dataset and audit shortcuts")
1532
+ s.add_argument("--data", default=f"deeparithmark-dataset/data/{DATASET_NAME}.jsonl")
1533
+ s.add_argument("--no-audit", action="store_true")
1534
+ s.set_defaults(func=cmd_selftest)
1535
+
1536
+ a = sub.add_parser("audit", help="shortcut audit only")
1537
+ a.add_argument("--data", default=f"deeparithmark-dataset/data/{DATASET_NAME}.jsonl")
1538
+ a.set_defaults(func=cmd_audit)
1539
+
1540
+ args = ap.parse_args()
1541
+ args.func(args)
1542
+
1543
+
1544
+ if __name__ == "__main__":
1545
+ main()