KlondikeDev commited on
Commit
be48828
·
verified ·
1 Parent(s): 73da6c1

Publish corrected MESA dataset, documentation, and evaluation tools

Browse files
README.md CHANGED
@@ -35,31 +35,87 @@ configs:
35
  # MESA
36
 
37
  **M**ath, **E**nglish, **S**cience, **A**rt. A four-domain, three-tier multiple
38
- choice benchmark built to have usable resolution at the 50M-500M parameter
39
- scale, where most standard suites sit close to their chance floor.
 
40
 
41
- MESA reports four domain scores rather than one number. That is the point of it:
42
- a pretraining mixture change usually helps one domain while hurting another, and
43
- a single aggregate score hides exactly the signal you need.
 
44
 
45
- ## Grid
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
- | Domain | MESA-1 | MESA-2 | MESA-3 | Total |
48
- |---|---|---|---|---|
49
- | Math | 250 | 250 | 250 | 750 |
50
- | English | 250 | 250 | 250 | 750 |
51
- | Science | 250 | 250 | 250 | 750 |
52
- | Art | 118 | 250 | 250 | 618 |
53
- | **Total** | **868** | **1000** | **1000** | **2868** |
54
 
55
- Tiers are ordered by reasoning depth, holding fact obscurity, distractor
56
- construction, and stem complexity fixed. MESA-1 is single-step, MESA-2 is
57
- two-step, MESA-3 chains three or more.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
  ## Format
60
 
61
  4-way multiple choice, scored by **continuation loglikelihood**: each option is
62
- appended to the stem and ranked by its logprob. Chance is 25%.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
  Two other scoring modes are deliberately not used:
65
 
@@ -77,16 +133,16 @@ higher-variance measurements at this scale, and MESA exists to reduce variance.
77
 
78
  ```json
79
  {
80
- "id": "mesa-ar3-00042",
81
  "domain": "Art",
82
  "subdomain": "music_theory",
83
  "skill": "secondary_dominant",
84
  "tier": 3,
85
- "stem": "In F# major, what is the root of the V/vi chord ...",
86
- "choices": ["C#", "G#", "D#", "A#"],
87
- "answer_idx": 3,
88
- "error_modes": ["primary_dominant_returned", "subdominant_of_target",
89
- "target_root_returned", "correct"],
90
  "provenance": "procedural"
91
  }
92
  ```
@@ -94,25 +150,51 @@ higher-variance measurements at this scale, and MESA exists to reduce variance.
94
  Every distractor is labelled with the specific error that produces it, so a
95
  wrong answer localises the failure rather than just costing a point.
96
 
 
 
 
 
 
 
 
 
 
 
97
  ## Usage
98
 
99
  ```python
100
  from datasets import load_dataset
101
 
102
- mesa = load_dataset("OpenCerebral/MESA", "all", split="test")
103
- hard = load_dataset("OpenCerebral/MESA", "mesa-3", split="test")
 
 
104
  ```
105
 
106
- With lm-evaluation-harness, copy `harness/` into your tasks directory:
 
 
 
 
 
 
107
 
108
  ```bash
109
  lm_eval --model hf --model_args pretrained=OpenCerebral/Boris-2-Preview-75M \
110
- --tasks mesa --include_path ./harness --batch_size 16
111
  ```
112
 
113
- `--tasks mesa` reports all sixteen numbers in one pass: twelve cells, four
114
- domain rollups, three tier rollups, one headline score. Domain and tier rollups
115
- are size-weighted.
 
 
 
 
 
 
 
 
116
 
117
  ## Construction
118
 
@@ -120,31 +202,172 @@ Items are procedurally generated. Distractors are drawn from named error modes
120
  rather than random perturbation, so a model that half-knows a procedure lands on
121
  a specific wrong option.
122
 
123
- Two tools ship with the dataset and should be re-run after any change:
124
 
125
  - `tools/mesa_verify.py` re-derives every key from the stem text using
126
  deliberately different methods -- algebra by substitution back into the parsed
127
  equation, chemistry by mass balance, music by scales built from stacked
128
  perfect fifths rather than chromatic offsets.
129
- - `tools/mesa_baselines.py` runs five meaning-blind solvers (longest, shortest,
130
- stem overlap, position, odd-one-out). Any solver above 35% in a cell means the
131
- distractors leak and that cell must be rebuilt.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
133
- Current state: 2097 items machine-verified with 0 key errors; 771 items
134
- (English grammar, plus SI units, molar masses, and Mendelian ratios) are not
135
- machine-checkable and were reviewed by hand. No baseline solver exceeds 35% in
136
- any cell.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
 
138
  ## Regenerating
139
 
140
  ```bash
141
- python generators/mesa_gen.py --n 250 --seed 20260809 --out procedural.jsonl
142
- python generators/mesa_scieng.py --n 250 --seed 20260809 --out scieng.jsonl
 
 
143
  ```
144
 
145
- Seed `20260809` reproduces the released set. If you suspect a model has trained
146
- on MESA, regenerate with a different seed and compare -- a large gap between the
147
- public set and a fresh one indicates contamination.
 
 
 
 
 
 
 
 
148
 
149
  ## Contamination
150
 
@@ -156,20 +379,41 @@ file. If that string is in a model's training corpus, that model has seen MESA.
156
  - **Art-1 is undersized** (118 items). Easy music theory has bounded
157
  combinatorics -- 15 major keys, 7 degrees, a handful of meters. Reaching 250
158
  requires non-music Art content, which cannot be generated.
 
 
 
 
 
 
 
 
 
 
 
159
  - **Three English families are prescriptive.** Object-position `whom`,
160
  neither/nor proximity agreement, and embedded relative case encode codified
161
  rules that fluent speakers routinely violate. Models trained on web text have
162
  seen the "wrong" forms constantly, so these items partly measure exposure to
163
  edited prose.
164
- - **Tiers are calibrated for small models.** MESA-3 is not hard for models above
165
- roughly 3B parameters.
166
- - **Coverage is uneven by subdomain.** Science leans on physics and chemistry;
167
- descriptive biology and earth science are absent. English is entirely grammar;
168
- vocabulary, comprehension, and figurative language are absent. Both gaps
169
- require hand authoring.
170
- - **`data/seed-authored-unreviewed.jsonl`** contains 15 model-drafted items
171
- demonstrating the format for the non-generatable subdomains. They are marked
172
- `reviewed: false` and are **not** part of the benchmark.
 
 
 
 
 
 
 
 
 
 
173
 
174
  ## License
175
 
 
35
  # MESA
36
 
37
  **M**ath, **E**nglish, **S**cience, **A**rt. A four-domain, three-tier multiple
38
+ choice benchmark for evaluating small language models. The measured baselines
39
+ below are two base models at roughly 125M parameters; performance across the
40
+ broader 50M-500M range has not been established.
41
 
42
+ MESA reports four domain scores rather than one number. A pretraining mixture
43
+ change can help one domain while hurting another, and a single aggregate can
44
+ hide that signal. The measured baselines below illustrate the effect: the two
45
+ models are four points apart overall but 24 points apart on English.
46
 
47
+ ## Quickstart
48
+
49
+ ```bash
50
+ git clone https://huggingface.co/datasets/opencerebral/MESA mesa
51
+ cd mesa
52
+ lm_eval --model hf --model_args pretrained=<your-model> \
53
+ --tasks mesa --include_path ./harness --batch_size 16
54
+ ```
55
+
56
+ Report the four **domain** scores and the headline, using **`acc`**. Chance is
57
+ 25%. Two 124-125M results on this revision appear under Measured baselines.
58
+ The repository is currently private, so cloning or loading it requires an
59
+ account with access and a Hugging Face login.
60
 
61
+ ## Grid
 
 
 
 
 
 
62
 
63
+ MESA scores four domains. That is the headline structure:
64
+
65
+ | Domain | Items |
66
+ |---|---|
67
+ | Math | 750 |
68
+ | English | 727 |
69
+ | Science | 750 |
70
+ | Art | 618 |
71
+ | **Total** | **2845** |
72
+
73
+ Each item also carries a `tier` (1-3), assigned by its generator template.
74
+ The tiers group item families by intended complexity; they are **not verified
75
+ per-item step counts**. For example, tier 2 includes direct density and Ohm's
76
+ law substitutions, and tier 3 includes direct displacement-formula questions.
77
+ All four domains have items in all three tiers. The data ships one file per
78
+ tier, and the harness can break scores out that way. Tier has no guarantee of
79
+ increasing empirical difficulty; see Known limitations.
80
+
81
+ | Domain | tier 1 | tier 2 | tier 3 |
82
+ |---|---|---|---|
83
+ | Math | 250 | 250 | 250 |
84
+ | English | 250 | 250 | 227 |
85
+ | Science | 250 | 250 | 250 |
86
+ | Art | 118 | 250 | 250 |
87
 
88
  ## Format
89
 
90
  4-way multiple choice, scored by **continuation loglikelihood**: each option is
91
+ rendered into the stem and ranked by its logprob. Chance is 25%.
92
+
93
+ Report **`acc`**, not `acc_norm`. Option length inside an item is already
94
+ balanced during construction (see Construction below), so byte-length
95
+ normalisation is a second correction on top of one that has been made, and it
96
+ over-corrects hardest where the options are shortest. On this revision, gpt2
97
+ (124M) averages 0.262 with `acc_norm` against 0.339 with `acc` across the twelve
98
+ cells; seven cells fall below the 0.25 chance floor under `acc_norm`. Both metrics
99
+ are reported by the harness; `acc` is the headline.
100
+
101
+ Stems come in two shapes, and they are rendered differently:
102
+
103
+ - **Question stems** are complete questions (`What is 71 + 26?`). The context is
104
+ the stem plus an `Answer:` cue and the option is appended.
105
+ - **Cloze stems** carry a `___` blank mid-sentence (567 of the 727 English
106
+ items). The option is substituted **into** the blank, not appended after the
107
+ stem: context is the text before the blank, continuation is the option plus
108
+ the text after it. Appending would leave the blank unfilled and make every
109
+ option -- the key included -- ungrammatical.
110
+
111
+ ```
112
+ cloze stem Choose the correct verb form: The crate of old letters ___ on the windowsill.
113
+ ctx Choose the correct verb form: The crate of old letters
114
+ cont " rests on the windowsill." vs " rest on the windowsill."
115
+ ```
116
+
117
+ `harness/utils.py` implements both branches. All four options of an item always
118
+ render through the same branch, so a ranking never compares two formats.
119
 
120
  Two other scoring modes are deliberately not used:
121
 
 
133
 
134
  ```json
135
  {
136
+ "id": "mesa-ar3-01123",
137
  "domain": "Art",
138
  "subdomain": "music_theory",
139
  "skill": "secondary_dominant",
140
  "tier": 3,
141
+ "stem": "In E major, what is the root of the V/vi chord (the secondary dominant of vi)?",
142
+ "choices": ["G#", "C#", "F#", "B"],
143
+ "answer_idx": 0,
144
+ "error_modes": ["correct", "target_root_returned",
145
+ "subdominant_of_target", "primary_dominant_returned"],
146
  "provenance": "procedural"
147
  }
148
  ```
 
150
  Every distractor is labelled with the specific error that produces it, so a
151
  wrong answer localises the failure rather than just costing a point.
152
 
153
+ ## Layout
154
+
155
+ ```
156
+ data/ mesa-1.jsonl, mesa-2.jsonl, mesa-3.jsonl (one file per tier)
157
+ generators/ mesa_gen.py, mesa_scieng.py (item generation)
158
+ tools/ mesa_verify.py, mesa_baselines.py, mesa_mutate.py, mesa_build.py
159
+ harness/ lm-evaluation-harness task tree
160
+ canary.txt contamination canary
161
+ ```
162
+
163
  ## Usage
164
 
165
  ```python
166
  from datasets import load_dataset
167
 
168
+ mesa = load_dataset("opencerebral/MESA", "all", split="test")
169
+ tier_3 = load_dataset("opencerebral/MESA", "mesa-3", split="test")
170
+ mesa = mesa.filter(lambda d: d["stem"] is not None)
171
+ tier_3 = tier_3.filter(lambda d: d["stem"] is not None)
172
  ```
173
 
174
+ The first record of each data file is the contamination canary and has no
175
+ `stem`; exclude it before scoring or analysis. Loading the `all` config returns
176
+ 2,848 rows, including three canary records; 2,845 are benchmark items.
177
+
178
+ For lm-evaluation-harness, clone the repository as `mesa` and run from its root
179
+ as in Quickstart. The harness's local dataset path resolves from that directory.
180
+ Run the tier group separately when needed:
181
 
182
  ```bash
183
  lm_eval --model hf --model_args pretrained=OpenCerebral/Boris-2-Preview-75M \
184
+ --tasks mesa_by_tier --include_path ./harness --batch_size 16
185
  ```
186
 
187
+ `--tasks mesa` reports seventeen numbers: the twelve cells, four domain rollups,
188
+ and one headline score. **Domain is the primary axis**: it separates the two
189
+ measured models and can reveal changes that a headline score hides.
190
+
191
+ `mesa_by_tier` is a secondary slice that aggregates the same twelve cells by
192
+ template-assigned tier. Tier does not order difficulty in the current 125M
193
+ runs; do not interpret it as a measured step count. All rollups are size-weighted.
194
+
195
+ **Run the two groups as separate invocations.** They share their twelve leaf
196
+ tasks, and lm-evaluation-harness rejects a task list in which the same leaf is
197
+ reachable from two selected groups (`ValueError: Duplicate task 'mesa_math_1'`).
198
 
199
  ## Construction
200
 
 
202
  rather than random perturbation, so a model that half-knows a procedure lands on
203
  a specific wrong option.
204
 
205
+ Three tools ship with the dataset and should be re-run after any change:
206
 
207
  - `tools/mesa_verify.py` re-derives every key from the stem text using
208
  deliberately different methods -- algebra by substitution back into the parsed
209
  equation, chemistry by mass balance, music by scales built from stacked
210
  perfect fifths rather than chromatic offsets.
211
+ - `tools/mesa_mutate.py` tests the verifier itself: it points each item's
212
+ `answer_idx` at a distractor and requires the checker to reject it. A checker
213
+ that accepts everything passes `mesa_verify.py` while guaranteeing nothing,
214
+ so this is what makes a clean verify run mean something. It exits non-zero if
215
+ any distractor is accepted.
216
+ - `tools/mesa_baselines.py` runs six meaning-blind solvers (longest, shortest,
217
+ stem overlap, position, odd-one-out, majority-key). Any solver at or above 35%
218
+ in a cell means the distractors leak and that cell must be rebuilt.
219
+
220
+ All three default to `data/*.jsonl` and skip the canary; run them from `tools/`, or
221
+ pass paths explicitly.
222
+
223
+ Current state: **2713 of 2845 items machine-verified with 0 key errors** (95.4%).
224
+ The remaining 132 are the families with no mechanical rule -- `only_placement`,
225
+ `irregular_past_participle`, `past_perfect_sequence`, and the 21 hand-authored
226
+ science facts (SI units, molar masses, Mendelian ratios).
227
+
228
+ Earlier versions marked all 700-odd English items UNVERIFIED and relied on a
229
+ one-time human read. That guarantee does not survive a regeneration: changing a
230
+ generator produces sentences nobody has looked at, while the README goes on
231
+ claiming they were reviewed. The English families are now checked from the
232
+ stem's syntax instead -- a plural head requires a base-form verb, "belonging to
233
+ the geese" requires `geese's`, `Of the two` requires a comparative -- so the
234
+ guarantee is a property of the build rather than of one afternoon's proofreading.
235
+
236
+ The checkers are themselves tested by mutation: point each item's `answer_idx`
237
+ at a distractor and confirm the checker rejects it. **All 8139 deliberately
238
+ wrong keys are rejected**. That test originally found the bug below.
239
+
240
+ No solver reaches 35% in any cell.
241
+
242
+ ### What mutation testing caught
243
+
244
+ A checker that accepts everything verifies nothing, so each one is scored on how
245
+ many wrong keys it rejects. Running that found a real defect in the pronoun-case
246
+ families: the distractors included the *right case in a different person*.
247
 
248
+ ```
249
+ Neither Daniel nor ___ was told about the change. key: "he"
250
+ distractor "I", labelled wrong_person
251
+ ```
252
+
253
+ "Neither Daniel nor I was told about the change" is correct English. The item had
254
+ two right answers, and so did its object-case counterpart ("Between Jonas and
255
+ her"). Every meaning-blind solver passed those items, the key verifier passed
256
+ them, and a human skim passes them too -- the sentence looks fine, and you have
257
+ to hold the key beside it to see the clash. Distractors in those families now
258
+ vary case or reflexivity, never person alone.
259
+
260
+ ### Why majority-key exists
261
+
262
+ The first five solvers all look at surface form: option length, word overlap,
263
+ position. They can all pass while a cell is still most of the way solvable,
264
+ because they cannot see the leak that matters most at this scale -- **a family
265
+ whose answer is a fixed string**.
266
+
267
+ If the answer to every subject-verb agreement item is the third-person singular
268
+ verb, and every distractor is a form that is never the answer anywhere, then the
269
+ option set alone identifies the key. A solver that scores each option by how
270
+ often it is the key *elsewhere in the same cell* (leave-one-out, so no item
271
+ votes for itself) reads nothing and still wins. Earlier drafts of MESA scored
272
+ **74.8% on English-1 and 78.2% on English-2** under exactly that solver while
273
+ passing all five surface checks.
274
+
275
+ Two things fix it, and both are enforced in `ItemBuilder.add`:
276
+
277
+ - **Every family generates both polarities.** Singular *and* plural frames, past
278
+ *and* present, `who` *and* `whom` *and* `whose`, participle *and* simple past.
279
+ Tense-varying frames carry a time adverbial ("last term", "at present") so
280
+ exactly one form is correct.
281
+ - **Agreement options normally share a key pool.** If the options are
282
+ `{is, are, having, has been}` then only two are ever answerable and the item is
283
+ really 2-way. The present-time possession and number-of frames now use a
284
+ nonfinite distractor in place of `had`, because both present and past perfect
285
+ could otherwise be grammatical. The meaning-blind baseline check guards
286
+ against option-identity leakage from that exception.
287
+
288
+ `LENGTH_BUDGET` and `KEY_BUDGET` in `generators/mesa_gen.py` then cap the *rate*
289
+ at which the key is the uniquely shortest option, or the option most often keyed
290
+ elsewhere. Budgeting the rate rather than rejecting item by item matters: a
291
+ per-item rule looks stricter but silently deletes whichever polarity has the
292
+ short key, which puts the constant-key leak straight back.
293
+
294
+ The generator also curates repeated stems without changing item IDs: a neutral
295
+ surname or institution name distinguishes a repeated frame. Past-time agreement
296
+ stems now identify a completed period, present-perfect stems identify the
297
+ present reference point, and the `only_placement` distractor uses a distinct
298
+ temporal meaning. The builder rejects duplicate stems and malformed choice sets.
299
+
300
+ ## Measured baselines
301
+
302
+ Two 124-125M models, `acc`, on this revision: the local
303
+ `boris-1-125M-first-run/export/boris-1-125M` base-model export and `gpt2`.
304
+ Both were run with `--tasks mesa_by_tier` and the local harness on 2026-10-03.
305
+ Chance is 25%.
306
+
307
+ | domain | Boris-1 125M | gpt2 |
308
+ |---|---|---|
309
+ | Math | 0.251 | 0.215 |
310
+ | English | 0.429 | 0.667 |
311
+ | Science | 0.288 | 0.235 |
312
+ | Art | 0.233 | 0.248 |
313
+ | **headline** | **0.302** | **0.343** |
314
+
315
+ The domain spread is what MESA is for: these two models are about four points
316
+ apart on the headline and farther apart underneath it. gpt2 is 24
317
+ points ahead on English and behind on Math and Science. A single aggregate would
318
+ have called them equivalent.
319
+
320
+ Per cell, for error analysis:
321
+
322
+ | cell | Boris | gpt2 | | cell | Boris | gpt2 |
323
+ |---|---|---|---|---|---|---|
324
+ | Math-1 | 0.184 | 0.200 | | Science-1 | 0.216 | 0.204 |
325
+ | Math-2 | 0.292 | 0.264 | | Science-2 | 0.256 | 0.180 |
326
+ | Math-3 | 0.276 | 0.180 | | Science-3 | 0.392 | 0.320 |
327
+ | English-1 | 0.428 | 0.680 | | Art-1 | 0.153 | 0.186 |
328
+ | English-2 | 0.384 | 0.616 | | Art-2 | 0.256 | 0.272 |
329
+ | English-3 | 0.480 | 0.709 | | Art-3 | 0.248 | 0.252 |
330
+
331
+ By tier (`--tasks mesa_by_tier`), which is where the inversion shows:
332
+
333
+ | tier | Boris | gpt2 |
334
+ |---|---|---|
335
+ | MESA-1 | 0.259 | 0.338 |
336
+ | MESA-2 | 0.297 | 0.333 |
337
+ | MESA-3 | 0.346 | 0.357 |
338
+
339
+ ### Reading a below-chance score
340
+
341
+ Distractors are named error modes, not random wrong answers, so a model that
342
+ half-executes a procedure is actively pulled toward one. Cells therefore go
343
+ **below** the 25% floor for weak models, and that is signal rather than a
344
+ defect: gpt2 scores 0.200 / 0.264 / 0.180 on the three Math cells. A model at
345
+ chance is guessing; a model below chance is reliably making a particular
346
+ mistake, and `error_modes` names which one.
347
+
348
+ Do not treat sub-chance as a broken cell without checking the baselines --
349
+ `tools/mesa_baselines.py` is what distinguishes a leaking cell from a hard one.
350
 
351
  ## Regenerating
352
 
353
  ```bash
354
+ python3 generators/mesa_gen.py --n 250 --seed 20260809 --out procedural.jsonl
355
+ python3 generators/mesa_scieng.py --n 250 --seed 20260809 --out scieng.jsonl
356
+ python3 tools/mesa_build.py procedural.jsonl scieng.jsonl --out-dir data \
357
+ --combined-out ../mesa_all.jsonl # optional local export, without canaries
358
  ```
359
 
360
+ Seed `20260809` reproduces the current set exactly, IDs included. The optional
361
+ combined export contains the same 2845 items as the three tier files, without
362
+ their canary records; use the three tier files as the source of truth. If you
363
+ suspect a model has trained on MESA, regenerate with a different seed and
364
+ compare -- a large gap between the public set and a fresh one indicates
365
+ contamination.
366
+
367
+ The generators emit items for `EXCLUDED_SKILLS` and drop them at write time
368
+ rather than never generating them. That is deliberate: it keeps every surviving
369
+ item bit-identical to an unfiltered run, so excluding a family does not
370
+ renumber or perturb the rest of the release.
371
 
372
  ## Contamination
373
 
 
379
  - **Art-1 is undersized** (118 items). Easy music theory has bounded
380
  combinatorics -- 15 major keys, 7 degrees, a handful of meters. Reaching 250
381
  requires non-music Art content, which cannot be generated.
382
+ - **English-3 is undersized** (227 items). The `dangling_modifier` family was
383
+ cut before release: its stem asks which sentence *contains* the error, so the
384
+ key is the least fluent option, and under continuation loglikelihood a better
385
+ model assigns it lower probability than the distractors. The family inverts
386
+ the metric and cannot be reframed in the fluent direction, because three of
387
+ its four options are grammatical. It is excluded in the generators rather than
388
+ stripped from the data, so a fresh run reproduces the released set.
389
+ - **Template reuse remains.** Repeated generated frames now receive distinct
390
+ neutral names, and no complete stem is repeated. Items from the same template
391
+ still share structure, so do not treat all 727 English questions as independent
392
+ evidence about broad language ability.
393
  - **Three English families are prescriptive.** Object-position `whom`,
394
  neither/nor proximity agreement, and embedded relative case encode codified
395
  rules that fluent speakers routinely violate. Models trained on web text have
396
  seen the "wrong" forms constantly, so these items partly measure exposure to
397
  edited prose.
398
+ - **Tier is not a step-count guarantee or difficulty ranking.** On this
399
+ revision, both measured models scored *higher* on MESA-3 than MESA-1:
400
+ Boris-1 125M scored 0.259 / 0.297 / 0.346, and gpt2 scored
401
+ 0.338 / 0.333 / 0.357. Tier groups differ in subject matter and distractors,
402
+ so these scores do not isolate the effect of procedural depth. Report domains;
403
+ treat tier as a template-family slice. Use `--log_samples` grouped by
404
+ `error_modes` for detailed error analysis. Larger models have not been
405
+ calibrated against the tier labels.
406
+ - **Some skill families are small.** MESA reports twelve cells, not sixty
407
+ skills; the `skill` field is for error analysis, not for scoring. Eight
408
+ families have fewer than fifteen items, and all of them are bounded by real
409
+ combinatorics rather than by effort: seven diatonic degrees, fifteen major
410
+ keys, nine SI base units, nine common molar masses, three monohybrid crosses.
411
+ Do not quote a per-skill accuracy off a family that size.
412
+ - **Coverage is uneven by subdomain.** Science is 489 physics, 258 chemistry and
413
+ 3 biology; earth science is absent. Math is 453 algebra, 250 arithmetic and 47
414
+ geometry. English is entirely grammar; vocabulary, comprehension, and
415
+ figurative language are absent. Art is entirely music theory. Closing these
416
+ gaps requires hand authoring.
417
 
418
  ## License
419
 
mesa-1.jsonl → data/mesa-1.jsonl RENAMED
The diff for this file is too large to render. See raw diff
 
mesa-2.jsonl → data/mesa-2.jsonl RENAMED
The diff for this file is too large to render. See raw diff
 
mesa-3.jsonl → data/mesa-3.jsonl RENAMED
The diff for this file is too large to render. See raw diff
 
mesa_gen.py → generators/mesa_gen.py RENAMED
@@ -14,19 +14,41 @@ Output: JSONL, one item per line.
14
  """
15
 
16
  import argparse
 
17
  import json
18
  import random
 
19
  from fractions import Fraction
20
 
21
  # --------------------------------------------------------------------------
22
  # item plumbing
23
  # --------------------------------------------------------------------------
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  class ItemBuilder:
26
  def __init__(self, rng):
27
  self.rng = rng
28
  self.seen = set()
29
  self.items = []
 
 
 
30
 
31
  def add(self, domain, subdomain, tier, stem, correct, distractors, skill):
32
  """distractors: list of (value, error_mode). Deduped, needs >=3 survivors."""
@@ -44,21 +66,58 @@ class ItemBuilder:
44
  return False
45
 
46
  # Length balancing. Error modes skew toward inflated wrong answers, which
47
- # lets a pick-shortest solver beat chance. Force at least one distractor
48
- # shorter than the key and one longer, so option length carries no signal.
 
49
  shorter = [x for x in cands if len(x[0]) < len(c)]
50
  longer = [x for x in cands if len(x[0]) > len(c)]
 
51
  chosen = []
52
  if shorter:
53
  chosen.append(self.rng.choice(shorter))
 
 
54
  if longer:
55
- chosen.append(self.rng.choice(longer))
 
 
 
 
 
56
  rest = [x for x in cands if x not in chosen]
57
  self.rng.shuffle(rest)
58
  chosen += rest[:3 - len(chosen)]
59
  if len(chosen) < 3:
60
  return False
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  opts = [c] + [x[0] for x in chosen]
63
  modes = ["correct"] + [x[1] for x in chosen]
64
 
@@ -67,6 +126,12 @@ class ItemBuilder:
67
  return False
68
  self.seen.add(key)
69
 
 
 
 
 
 
 
70
  order = list(range(4))
71
  self.rng.shuffle(order)
72
  choices = [opts[i] for i in order]
@@ -89,7 +154,85 @@ class ItemBuilder:
89
 
90
 
91
  # --------------------------------------------------------------------------
92
- # MATH - tier 1 (single step)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  # --------------------------------------------------------------------------
94
 
95
  def math_t1(b, n):
@@ -127,7 +270,8 @@ def math_t1(b, n):
127
  base = rng.choice([40, 60, 80, 120, 160, 200, 240])
128
  ans = base * p // 100
129
  d = [(base * p, "no_division_by_100"), (ans * 10, "decimal_place_error"),
130
- (base - ans, "complement_taken"), (round(base / p, 2), "inverted_operation")]
 
131
  ok = b.add("Math", "arithmetic", 1,
132
  f"What is {p}% of {base}?", ans, d, "percent_of_number")
133
 
@@ -141,7 +285,9 @@ def math_t1(b, n):
141
  d = [(f"{num}/{den}", "not_reduced"),
142
  (f"{f.denominator}/{f.numerator}", "inverted"),
143
  (f"{num - 1}/{den - 1}", "subtracted_from_both"),
144
- (f"{f.numerator + 1}/{f.denominator}", "off_by_one")]
 
 
145
  ok = b.add("Math", "arithmetic", 1,
146
  f"Reduce the fraction {num}/{den} to lowest terms.",
147
  ans, d, "fraction_reduction")
@@ -150,7 +296,7 @@ def math_t1(b, n):
150
 
151
 
152
  # --------------------------------------------------------------------------
153
- # MATH - tier 2 (two steps)
154
  # --------------------------------------------------------------------------
155
 
156
  def math_t2(b, n):
@@ -204,7 +350,9 @@ def math_t2(b, n):
204
  ans = 2 * (w + h)
205
  dd = [(w + h, "half_perimeter"), (2 * w + h, "one_side_dropped"),
206
  (w * h, "area_for_perimeter"), (2 * w * h, "doubled_area"),
207
- (4 * w, "assumed_square")]
 
 
208
  ok = b.add("Math", "geometry", 2,
209
  f"A rectangle measures {w} cm by {h} cm. What is its perimeter?",
210
  f"{ans} cm",
@@ -230,7 +378,7 @@ def math_t2(b, n):
230
 
231
 
232
  # --------------------------------------------------------------------------
233
- # MATH - tier 3 (three or more chained steps)
234
  # --------------------------------------------------------------------------
235
 
236
  def math_t3(b, n):
@@ -616,7 +764,7 @@ def main():
616
  ap = argparse.ArgumentParser()
617
  ap.add_argument("--n", type=int, default=40, help="items per cell")
618
  ap.add_argument("--seed", type=int, default=20260809)
619
- ap.add_argument("--out", default="mesa_procedural.jsonl")
620
  a = ap.parse_args()
621
 
622
  b = ItemBuilder(random.Random(a.seed))
@@ -628,10 +776,11 @@ def main():
628
  print(f" ! {fn.__name__}: template space exhausted at {got}/{a.n} "
629
  f"unique items -- add templates to reach target")
630
 
631
- with open(a.out, "w") as f:
632
- for it in b.items:
633
- f.write(json.dumps(it) + "\n")
634
- print(f"wrote {len(b.items)} items to {a.out}")
 
635
 
636
 
637
  if __name__ == "__main__":
 
14
  """
15
 
16
  import argparse
17
+ import collections
18
  import json
19
  import random
20
+ import re
21
  from fractions import Fraction
22
 
23
  # --------------------------------------------------------------------------
24
  # item plumbing
25
  # --------------------------------------------------------------------------
26
 
27
+ # Share of items in a cell whose key may be the uniquely shortest (or uniquely
28
+ # longest) option. Chance is 0.25; holding the rate a little under it leaves
29
+ # room for the partial credit a solver collects from ties and still lands the
30
+ # cell near 25%. WARMUP lets a cell fill before the ratio means anything.
31
+ LENGTH_BUDGET = 0.25
32
+ LENGTH_WARMUP = 20
33
+
34
+ # Share of items in a cell whose key is, on its own, the option most often used
35
+ # as a key elsewhere in that cell. This is what the majority_key solver in
36
+ # tools/mesa_baselines.py measures: if a family's answer is always the same
37
+ # string, or a string that never turns up as a distractor, the option set alone
38
+ # identifies the key and the stem is decorative. Budgeting the rate forces
39
+ # generators to retry until keys and distractors are drawn from the same pool.
40
+ KEY_BUDGET = 0.15
41
+ KEY_WARMUP = 25
42
+
43
+
44
  class ItemBuilder:
45
  def __init__(self, rng):
46
  self.rng = rng
47
  self.seen = set()
48
  self.items = []
49
+ self.cell_stats = collections.defaultdict(
50
+ lambda: {"n": 0, "short": 0, "long": 0, "key_wins": 0,
51
+ "key_count": collections.Counter()})
52
 
53
  def add(self, domain, subdomain, tier, stem, correct, distractors, skill):
54
  """distractors: list of (value, error_mode). Deduped, needs >=3 survivors."""
 
66
  return False
67
 
68
  # Length balancing. Error modes skew toward inflated wrong answers, which
69
+ # lets a pick-shortest solver beat chance. Prefer a distractor strictly
70
+ # shorter than the key and one strictly longer; fall back to equal
71
+ # length, which at least denies the solver a clean win.
72
  shorter = [x for x in cands if len(x[0]) < len(c)]
73
  longer = [x for x in cands if len(x[0]) > len(c)]
74
+ equal = [x for x in cands if len(x[0]) == len(c)]
75
  chosen = []
76
  if shorter:
77
  chosen.append(self.rng.choice(shorter))
78
+ elif equal:
79
+ chosen.append(self.rng.choice(equal))
80
  if longer:
81
+ chosen.append(self.rng.choice([x for x in longer if x not in chosen])
82
+ if [x for x in longer if x not in chosen] else
83
+ self.rng.choice(longer))
84
+ elif [x for x in equal if x not in chosen]:
85
+ chosen.append(self.rng.choice([x for x in equal if x not in chosen]))
86
+ chosen = list(dict.fromkeys(chosen))
87
  rest = [x for x in cands if x not in chosen]
88
  self.rng.shuffle(rest)
89
  chosen += rest[:3 - len(chosen)]
90
  if len(chosen) < 3:
91
  return False
92
 
93
+ # Length gate, enforced as a DISTRIBUTION over the cell rather than
94
+ # per item.
95
+ #
96
+ # What a pick-shortest solver exploits is the RATE at which the key is
97
+ # the shortest option, so that rate is what has to be held near chance.
98
+ # Rejecting every item whose key is uniquely shortest looks stricter but
99
+ # is much worse: for any family with two polarities it silently deletes
100
+ # the short-key one (the "belong"/"belongs", "who"/"whom", "is"/"are"
101
+ # branches), leaving the key a constant string -- which is a far bigger
102
+ # leak, and one the length solvers cannot see. Budget the rate instead
103
+ # and both polarities survive.
104
+ lens = [len(c)] + [len(x[0]) for x in chosen]
105
+ uniq_short = len(c) == min(lens) and lens.count(min(lens)) == 1
106
+ uniq_long = len(c) == max(lens) and lens.count(max(lens)) == 1
107
+ st = self.cell_stats[(domain, tier)]
108
+ if st["n"] >= LENGTH_WARMUP:
109
+ if uniq_short and (st["short"] + 1) / (st["n"] + 1) > LENGTH_BUDGET:
110
+ return False
111
+ if uniq_long and (st["long"] + 1) / (st["n"] + 1) > LENGTH_BUDGET:
112
+ return False
113
+
114
+ # Key-identity gate, same budgeted-rate shape as the length gate.
115
+ kk = st["key_count"]
116
+ key_wins = kk.get(c, 0) > max((kk.get(x[0], 0) for x in chosen), default=0)
117
+ if st["n"] >= KEY_WARMUP:
118
+ if key_wins and (st["key_wins"] + 1) / (st["n"] + 1) > KEY_BUDGET:
119
+ return False
120
+
121
  opts = [c] + [x[0] for x in chosen]
122
  modes = ["correct"] + [x[1] for x in chosen]
123
 
 
126
  return False
127
  self.seen.add(key)
128
 
129
+ st["n"] += 1
130
+ st["short"] += uniq_short
131
+ st["long"] += uniq_long
132
+ st["key_wins"] += key_wins
133
+ st["key_count"][c] += 1
134
+
135
  order = list(range(4))
136
  self.rng.shuffle(order)
137
  choices = [opts[i] for i in order]
 
154
 
155
 
156
  # --------------------------------------------------------------------------
157
+ # Excluded families
158
+ # --------------------------------------------------------------------------
159
+ #
160
+ # Items are still GENERATED for these skills and still consume the RNG stream,
161
+ # then dropped at write time. Generating-then-dropping (rather than never
162
+ # generating) is deliberate: it keeps every other item in the release
163
+ # bit-identical to what an unfiltered run produces, so the published seed still
164
+ # reproduces the published set.
165
+ #
166
+ # dangling_modifier -- the stem asks which sentence CONTAINS the error, so
167
+ # the key is the least fluent option. Under continuation loglikelihood a
168
+ # better language model assigns it LOWER probability than the distractors,
169
+ # which inverts the metric. The family cannot be reframed in the fluent
170
+ # direction because three of its four options are grammatical.
171
+
172
+ EXCLUDED_SKILLS = frozenset({"dangling_modifier"})
173
+
174
+
175
+ def write_items(items, path):
176
+ """Write curated JSONL, dropping excluded families and repeated stems."""
177
+ kept = [dict(it) for it in items if it["skill"] not in EXCLUDED_SKILLS]
178
+ seen_stems = set()
179
+ names = ("Maria", "Thomas", "Priya", "Daniel", "Ingrid", "Samuel",
180
+ "Hannah", "Lukas", "Elena", "Marcus", "Aisha", "Jonas",
181
+ "Clara", "Viktor", "Noor", "Anton", "Beatrix", "Rafael",
182
+ "Sofia", "Werner")
183
+ surnames = ("Vale", "Shaw", "Mora", "Khan", "Reed", "Park")
184
+ groups = ("board", "committee", "council", "panel", "faculty")
185
+ for it in kept:
186
+ # A past-perfect distractor is grammatical without an explicit past
187
+ # reference. Replace it with a nonfinite form in present-time frames.
188
+ key = it["choices"][it["answer_idx"]]
189
+ if (it["skill"] in ("number_of_agreement",
190
+ "indefinite_pronoun_agreement")
191
+ and key in ("has", "have") and "had" in it["choices"]):
192
+ it["choices"] = list(it["choices"])
193
+ it["error_modes"] = list(it["error_modes"])
194
+ idx = it["choices"].index("had")
195
+ it["choices"][idx] = "having"
196
+ it["error_modes"][idx] = "nonfinite_form"
197
+
198
+ # "X only read Y" can itself mean X read nothing except Y. Use an
199
+ # explicitly temporal placement instead of a second defensible key.
200
+ if it["skill"] == "only_placement" and "only_modifies_verb" in it["error_modes"]:
201
+ it["choices"] = list(it["choices"])
202
+ it["error_modes"] = list(it["error_modes"])
203
+ idx = it["error_modes"].index("only_modifies_verb")
204
+ m = re.fullmatch(r"(.+?) only (read|reviewed|copied|annotated) (.+)\.",
205
+ it["choices"][idx])
206
+ if not m:
207
+ raise ValueError(f"unexpected only-placement option: {it['id']}")
208
+ who, action, obj = m.groups()
209
+ it["choices"][idx] = f"{who} {action} {obj} only yesterday."
210
+ it["error_modes"][idx] = "only_modifies_time"
211
+
212
+ stem = it["stem"]
213
+ if stem in seen_stems:
214
+ m = re.search(r"\b(" + "|".join(names) + r")\b", stem)
215
+ candidates = ([stem[:m.end()] + " " + surname + stem[m.end():]
216
+ for surname in surnames] if m else [])
217
+ for group in groups:
218
+ if f"The {group} " in stem:
219
+ candidates += [stem.replace(f"The {group} ",
220
+ f"The {group} of trustees ", 1),
221
+ stem.replace(f"The {group} ",
222
+ f"The {group} of editors ", 1)]
223
+ replacement = next((s for s in candidates if s not in seen_stems), None)
224
+ if replacement is None:
225
+ raise ValueError(f"cannot make repeated stem unique: {it['id']}")
226
+ it["stem"] = replacement
227
+ seen_stems.add(it["stem"])
228
+
229
+ with open(path, "w") as f:
230
+ for it in kept:
231
+ f.write(json.dumps(it) + "\n")
232
+ return len(kept), len(items) - len(kept)
233
+
234
+ # --------------------------------------------------------------------------
235
+ # MATH - tier 1 template group
236
  # --------------------------------------------------------------------------
237
 
238
  def math_t1(b, n):
 
270
  base = rng.choice([40, 60, 80, 120, 160, 200, 240])
271
  ans = base * p // 100
272
  d = [(base * p, "no_division_by_100"), (ans * 10, "decimal_place_error"),
273
+ (base - ans, "complement_taken"), (round(base / p, 2), "inverted_operation"),
274
+ (p, "percent_copied_from_stem"), (base, "base_copied_from_stem")]
275
  ok = b.add("Math", "arithmetic", 1,
276
  f"What is {p}% of {base}?", ans, d, "percent_of_number")
277
 
 
285
  d = [(f"{num}/{den}", "not_reduced"),
286
  (f"{f.denominator}/{f.numerator}", "inverted"),
287
  (f"{num - 1}/{den - 1}", "subtracted_from_both"),
288
+ (f"{f.numerator + 1}/{f.denominator}", "off_by_one"),
289
+ (f"{f.numerator}/{f.denominator + 1}", "denominator_off_by_one"),
290
+ (f"{max(1, f.numerator - 1)}/{f.denominator}", "off_by_one_low")]
291
  ok = b.add("Math", "arithmetic", 1,
292
  f"Reduce the fraction {num}/{den} to lowest terms.",
293
  ans, d, "fraction_reduction")
 
296
 
297
 
298
  # --------------------------------------------------------------------------
299
+ # MATH - tier 2 template group
300
  # --------------------------------------------------------------------------
301
 
302
  def math_t2(b, n):
 
350
  ans = 2 * (w + h)
351
  dd = [(w + h, "half_perimeter"), (2 * w + h, "one_side_dropped"),
352
  (w * h, "area_for_perimeter"), (2 * w * h, "doubled_area"),
353
+ (4 * w, "assumed_square"),
354
+ (2 * (w + h + 1), "side_misread_by_one"),
355
+ (2 * (w + h - 1), "side_misread_by_one_low")]
356
  ok = b.add("Math", "geometry", 2,
357
  f"A rectangle measures {w} cm by {h} cm. What is its perimeter?",
358
  f"{ans} cm",
 
378
 
379
 
380
  # --------------------------------------------------------------------------
381
+ # MATH - tier 3 template group
382
  # --------------------------------------------------------------------------
383
 
384
  def math_t3(b, n):
 
764
  ap = argparse.ArgumentParser()
765
  ap.add_argument("--n", type=int, default=40, help="items per cell")
766
  ap.add_argument("--seed", type=int, default=20260809)
767
+ ap.add_argument("--out", default="procedural.jsonl")
768
  a = ap.parse_args()
769
 
770
  b = ItemBuilder(random.Random(a.seed))
 
776
  print(f" ! {fn.__name__}: template space exhausted at {got}/{a.n} "
777
  f"unique items -- add templates to reach target")
778
 
779
+ kept, dropped = write_items(b.items, a.out)
780
+ if dropped:
781
+ print(f" ! dropped {dropped} items from excluded families: "
782
+ f"{', '.join(sorted(EXCLUDED_SKILLS))}")
783
+ print(f"wrote {kept} items to {a.out}")
784
 
785
 
786
  if __name__ == "__main__":
mesa_scieng.py → generators/mesa_scieng.py RENAMED
@@ -25,7 +25,7 @@ import json
25
  import random
26
  from fractions import Fraction
27
 
28
- from mesa_gen import ItemBuilder
29
 
30
 
31
  # ==========================================================================
@@ -82,7 +82,9 @@ def sci_t1(b, n):
82
  dd = [(k * fac // 10, "prefix_off_by_one_power"),
83
  (k * fac * 10, "prefix_off_by_one_power"),
84
  (Fraction(k, fac), "conversion_inverted"),
85
- (k + fac, "operation_wrong")]
 
 
86
  made += b.add("Science", "physics", 1,
87
  f"How many {to} are in {k} {frm}?", ans, dd,
88
  "unit_conversion")
@@ -94,7 +96,10 @@ def sci_t1(b, n):
94
  d = v * t
95
  dd = [(d * t, "multiplied_instead_of_divided"),
96
  (Fraction(t, d), "ratio_inverted"),
97
- (d - t, "subtracted"), (d + t, "added")]
 
 
 
98
  made += b.add("Science", "physics", 1,
99
  f"An object travels {d} meters in {t} seconds at a constant "
100
  f"rate. What is its speed?",
@@ -131,7 +136,9 @@ def sci_t2(b, n):
131
  if kind == "force":
132
  m, a = rng.randint(2, 25), rng.randint(2, 12)
133
  ans = m * a
134
- dd = [(m + a, "operands_added"), (Fraction(m, a), "operands_divided"),
 
 
135
  (Fraction(a, m), "operands_divided_inverted"), (m - a, "subtracted")]
136
  made += b.add("Science", "physics", 2,
137
  f"A net force accelerates a {m} kg object at {a} m/s\u00b2. "
@@ -143,7 +150,9 @@ def sci_t2(b, n):
143
  if kind == "ohm":
144
  i, r = rng.randint(2, 9), rng.choice([3, 4, 5, 6, 8, 10, 12, 20])
145
  ans = i * r
146
- dd = [(i + r, "operands_added"), (Fraction(r, i), "operands_divided"),
 
 
147
  (Fraction(i, r), "operands_divided_inverted"), (r - i, "subtracted")]
148
  made += b.add("Science", "physics", 2,
149
  f"A current of {i} A flows through a {r} \u03a9 resistor. "
@@ -157,7 +166,10 @@ def sci_t2(b, n):
157
  m = d * v
158
  dd = [(m * v, "multiplied_instead_of_divided"),
159
  (Fraction(v, m), "ratio_inverted"), (m - v, "subtracted"),
160
- (m + v, "added")]
 
 
 
161
  made += b.add("Science", "chemistry", 2,
162
  f"A block has a mass of {m} g and a volume of {v} cm\u00b3. "
163
  f"What is its density?",
@@ -236,7 +248,8 @@ def sci_t3(b, n):
236
  v = rng.choice([10, 20, 30, 40])
237
  h = v * v // 20 # g = 10 m/s^2, v = sqrt(2gh)
238
  m = rng.randint(2, 9)
239
- dd = [(v // 2, "halved"), (h, "height_reported"),
 
240
  (2 * 10 * h, "square_root_omitted"), (m * v, "mass_multiplied_in"),
241
  (10 * h, "gravity_times_height_only")]
242
  made += b.add("Science", "physics", 3,
@@ -308,16 +321,25 @@ SV_VERBS = [("sit", "sits", "sitting", "sat"), ("rest", "rests", "resting", "res
308
  ("belong", "belongs", "belonging", "belonged"),
309
  ("wait", "waits", "waiting", "waited")]
310
 
311
- SV_HEADS = ["box", "crate", "bundle", "stack", "folder", "basket", "tray", "carton"]
 
 
312
  SV_MODS = ["old letters", "rusted tools", "blank forms", "glass marbles",
313
- "dried herbs", "spare keys", "cracked tiles", "faded photographs"]
314
- SV_PLACES = ["shelf", "counter", "table", "windowsill", "workbench", "porch"]
 
 
 
 
315
 
316
  REG_PLURALS = ["dogs", "students", "teachers", "farmers", "sailors", "neighbors",
317
- "artists", "engineers"]
 
318
  IRR_PLURALS = [("children", "child"), ("men", "man"), ("women", "woman"),
319
- ("mice", "mouse"), ("geese", "goose"), ("people", "person")]
320
- POSSESSED = ["toys", "coats", "bicycles", "notebooks", "lunches", "umbrellas"]
 
 
321
 
322
  # each verb carries its own object -- "has given the report" is semantically odd
323
  IRR_VERBS = [("write", "wrote", "written", "the report"),
@@ -339,12 +361,34 @@ IRR_VERBS = [("write", "wrote", "written", "the report"),
339
  ("tear", "tore", "torn", "the receipt"),
340
  ("forget", "forgot", "forgotten", "the appointment")]
341
 
 
 
 
 
 
 
 
 
342
  ADJS = [("tall", "taller", "tallest"), ("bright", "brighter", "brightest"),
343
  ("quiet", "quieter", "quietest"), ("strong", "stronger", "strongest"),
344
- ("narrow", "narrower", "narrowest"), ("clever", "cleverer", "cleverest"),
345
- ("swift", "swifter", "swiftest"), ("calm", "calmer", "calmest"),
346
- ("harsh", "harsher", "harshest"), ("bold", "bolder", "boldest"),
347
- ("sharp", "sharper", "sharpest"), ("humble", "humbler", "humblest")]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
348
 
349
  NAMES = ["Maria", "Thomas", "Priya", "Daniel", "Ingrid", "Samuel", "Hannah", "Lukas",
350
  "Elena", "Marcus", "Aisha", "Jonas", "Clara", "Viktor", "Noor", "Anton",
@@ -362,6 +406,74 @@ DANG_ACTS = [("Walking to school", "the wallet", "found", "find"),
362
  ("Turning the corner", "the shop", "spotted", "spot")]
363
 
364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
365
  def eng_t1(b, n):
366
  rng, made, tries = b.rng, 0, 0
367
  while made < n and tries < n * 200:
@@ -372,15 +484,37 @@ def eng_t1(b, n):
372
  head = rng.choice(SV_HEADS)
373
  mod = rng.choice(SV_MODS)
374
  place = rng.choice(SV_PLACES)
375
- base, s, ing, pp = rng.choice(SV_VERBS)
376
- dd = [(base, "agrees_with_object_of_preposition"),
377
- (f"are {ing}", "plural_progressive"),
378
- (f"have {pp}", "plural_perfect"),
379
- (f"were {ing}", "plural_past_progressive")]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
380
  made += b.add("English", "grammar", 1,
381
- f"Choose the correct verb form: The {head} of {mod} ___ "
382
- f"on the {place}.",
383
- s, dd, "subject_verb_agreement")
384
  continue
385
 
386
  if kind == "poss_reg":
@@ -417,25 +551,38 @@ def eng_t2(b, n):
417
 
418
  if kind == "pronoun_subj":
419
  nm = rng.choice(NAMES)
420
- dd = [("me", "object_case_in_subject_position"),
421
- ("myself", "reflexive_misused"),
422
- ("us", "wrong_number"), ("him", "wrong_person_and_case")]
 
 
 
 
 
 
 
 
423
  frame = rng.choice([
424
  f"{nm} and ___ finished the project before the deadline.",
425
  f"{nm} and ___ were asked to present first.",
426
- f"Neither {nm} nor ___ knew about the change.",
427
  f"{nm} and ___ have volunteered for the early shift.",
428
  ])
429
  made += b.add("English", "grammar", 2,
430
  f"Choose the correct pronoun: {frame}",
431
- "I", dd, "pronoun_case_subject")
432
  continue
433
 
434
  if kind == "pronoun_obj":
435
  nm = rng.choice(NAMES)
436
- dd = [("I", "subject_case_in_object_position"),
437
- ("myself", "reflexive_misused"),
438
- ("we", "wrong_number_and_case"), ("he", "wrong_person_and_case")]
 
 
 
 
 
439
  frame = rng.choice([
440
  f"The librarian handed the forms to {nm} and ___.",
441
  f"Between {nm} and ___, the work was finished early.",
@@ -444,7 +591,7 @@ def eng_t2(b, n):
444
  ])
445
  made += b.add("English", "grammar", 2,
446
  f"Choose the correct pronoun: {frame}",
447
- "me", dd, "pronoun_case_object")
448
  continue
449
 
450
  if kind == "irr_verb":
@@ -462,46 +609,109 @@ def eng_t2(b, n):
462
  made += b.add("English", "grammar", 2,
463
  f"Choose the correct form: {frame}",
464
  pp, dd, "irregular_past_participle")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465
  continue
466
 
467
  if kind == "compsup":
468
  adj, comp, sup = rng.choice(ADJS)
469
  nm = rng.choice(NAMES)
470
- if rng.random() < 0.5:
471
- dd = [(comp, "comparative_for_superlative"),
 
 
 
 
 
472
  (f"most {sup}", "double_superlative"),
473
  (f"more {comp}", "double_comparative"),
474
  (f"most {adj}", "periphrastic_form_misused"),
475
  (adj, "positive_form_used")]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
476
  made += b.add("English", "grammar", 2,
477
- f"Choose the correct form: Of the three finalists, "
478
- f"{nm} is the ___.",
479
- sup, dd, "superlative_form")
480
- else:
481
- dd = [(sup, "superlative_for_comparative"),
482
- (f"more {comp}", "double_comparative"),
483
- (f"most {sup}", "double_superlative"),
484
- (f"more {adj}", "periphrastic_comparative"),
485
- (adj, "positive_form_used")]
486
- made += b.add("English", "grammar", 2,
487
- f"Choose the correct form: Of the two candidates, "
488
- f"{nm} is the ___ speaker.",
489
- comp, dd, "comparative_form")
490
  continue
491
 
492
  nm = rng.choice(NAMES)
493
  thing = rng.choice(["the tickets", "the keys", "the proofs", "the invitation"])
494
- frame = rng.choice([
495
- f"___ did {nm} give {thing} to?",
496
- f"To ___ did {nm} address {thing}?",
497
- f"{nm} could not recall ___ {pron(nm)} had shown {thing} to.",
498
- ])
499
- dd = [("Who" if frame.startswith("___") else "who",
500
- "subject_form_in_object_position"),
501
- ("Whose" if frame.startswith("___") else "whose",
502
- "possessive_form_used"),
503
- ("Whom's", "nonexistent_form"), ("Who's", "contraction_confused")]
504
- ans = "Whom" if frame.startswith("___") else "whom"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505
  made += b.add("English", "grammar", 2,
506
  f"Choose the correct form: {frame}", ans, dd,
507
  "relative_pronoun_case")
@@ -538,132 +748,192 @@ def eng_t3(b, n):
538
  sg, pl = rng.choice(SINGS), rng.choice(PLURALS)
539
  pred = rng.choice(["satisfied with the outcome", "aware of the change",
540
  "present at the hearing", "eligible for the bonus"])
541
- if rng.random() < 0.5:
542
- stem = (f"Choose the correct verb: Neither the {sg} nor the {pl} "
543
- f"___ {pred}.")
544
- ans = "were"
545
- dd = [("was", "agreed_with_distant_singular_subject"),
546
- ("has been", "singular_perfect"), ("is", "singular_present"),
547
- ("been", "nonfinite_form")]
548
- else:
549
- stem = (f"Choose the correct verb: Neither the {pl} nor the {sg} "
550
- f"___ {pred}.")
551
- ans = "was"
552
- dd = [("were", "agreed_with_distant_plural_subject"),
553
- ("have been", "plural_perfect"), ("are", "plural_present"),
554
- ("been", "nonfinite_form")]
555
- made += b.add("English", "grammar", 3, stem, ans, dd,
556
  "proximity_agreement")
557
  continue
558
 
559
  if kind == "each":
560
  pl = rng.choice(PLURALS)
561
- th = rng.choice(["a locker", "a number", "a folder", "a seat",
562
- "a mentor", "a badge"])
563
- quant = rng.choice(["Each", "Every one", "Neither"])
564
- dd = [("have", "agreed_with_object_of_preposition"),
565
- ("are having", "progressive_and_plural"),
566
- ("were having", "past_progressive_and_plural"),
567
- ("having", "nonfinite_form")]
 
 
 
 
 
 
 
 
 
 
568
  made += b.add("English", "grammar", 3,
569
- f"Choose the correct verb: {quant} of the {pl} ___ {th} "
570
- f"assigned at registration.",
571
- "has", dd, "indefinite_pronoun_agreement")
572
  continue
573
 
574
  if kind == "expletive":
575
- pl = rng.choice(["several reasons", "many objections", "three exceptions",
576
- "two explanations", "four candidates", "some doubts"])
577
  cause = rng.choice(["for the delay", "for the revision",
578
  "behind the decision", "for the shortfall"])
579
- dd = [("is", "agreed_with_expletive_there"),
580
- ("has been", "singular_perfect"), ("was", "singular_past"),
581
- ("being", "nonfinite_form")]
 
 
 
 
 
 
 
 
 
 
582
  made += b.add("English", "grammar", 3,
583
- f"Choose the correct verb: There ___ {pl} {cause}.",
584
- "are", dd, "expletive_construction_agreement")
 
 
585
  continue
586
 
587
  if kind == "number_of":
588
  pl = rng.choice(PLURALS)
589
- pred = rng.choice(["risen sharply this term", "declined since April",
590
- "remained steady", "grown every year"])
 
591
  if rng.random() < 0.5:
592
- # "A number of X" takes a plural verb
593
- dd = [("has", "treated_as_singular_head"),
594
- ("is", "singular_present"), ("was", "singular_past"),
595
- ("having", "nonfinite_form")]
596
- made += b.add("English", "grammar", 3,
597
- f"Choose the correct verb: A number of {pl} ___ "
598
- f"{pred}.",
599
- "have", dd, "number_of_agreement")
600
  else:
601
- # "The number of X" takes a singular verb
602
- dd = [("have", "agreed_with_object_of_preposition"),
603
- ("are", "plural_present"), ("were", "plural_past"),
604
- ("having", "nonfinite_form")]
605
- made += b.add("English", "grammar", 3,
606
- f"Choose the correct verb: The number of {pl} ___ "
607
- f"{pred}.",
608
- "has", dd, "number_of_agreement")
 
 
 
 
 
 
 
 
 
609
  continue
610
 
611
  if kind == "subjunctive":
612
  body = rng.choice(["committee", "board", "council", "panel", "faculty"])
613
- verb = rng.choice(["recommends", "insists", "requires", "asks", "demands"])
614
  subj = rng.choice(["the proposal", "the schedule", "the clause",
615
  "the budget", "the report"])
616
  comp = rng.choice(["revised", "postponed", "withdrawn", "reconsidered"])
617
- dd = [("is", "indicative_present"), ("was", "indicative_past"),
618
- ("will be", "future_indicative"), ("being", "nonfinite_form")]
619
- made += b.add("English", "grammar", 3,
620
- f"Choose the correct verb: The {body} {verb} that "
621
- f"{subj} ___ {comp}.",
622
- "be", dd, "subjunctive_mood")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
623
  continue
624
 
625
  if kind == "inversion":
626
- place = rng.choice(["Among the finalists", "Behind the old barn",
627
- "Beneath the floorboards", "Across the valley",
628
- "Inside the sealed crate"])
629
- pl = rng.choice(["two former champions", "three rusted plows",
630
- "several loose wires", "four abandoned huts",
631
- "dozens of yellowed letters"])
632
- dd = [("is", "agreed_with_fronted_phrase"), ("was", "singular_past"),
633
- ("has been", "singular_perfect"), ("being", "nonfinite_form")]
 
 
 
 
 
 
 
 
 
 
634
  made += b.add("English", "grammar", 3,
635
- f"Choose the correct verb: {place} ___ {pl}.",
636
- "are", dd, "inverted_subject_agreement")
 
637
  continue
638
 
639
  if kind == "embedded_case":
640
  nm = rng.choice(NAMES)
641
  role = rng.choice(["candidate", "applicant", "witness", "trainee",
642
  "delegate"])
643
- if rng.random() < 0.5:
644
- # relative pronoun is the SUBJECT of the embedded clause -> "who"
645
- pred = rng.choice(["will win", "should lead the team",
646
- "deserves the grant", "can finish the audit"])
647
- dd = [("whom", "object_form_in_subject_position"),
648
- ("whose", "possessive_form_used"),
649
- ("which", "nonhuman_relative_used"),
650
- ("what", "free_relative_used")]
651
- made += b.add("English", "grammar", 3,
652
- f"Choose the correct form: {nm} is the {role} ___ "
653
- f"we believe {pred}.",
654
- "who", dd, "embedded_relative_case")
655
- else:
656
- # relative pronoun is the OBJECT of the embedded clause -> "whom"
657
- pred = rng.choice(["we recommended", "the panel selected",
658
  "the director interviewed", "everyone praised"])
659
- dd = [("who", "subject_form_in_object_position"),
660
- ("whose", "possessive_form_used"),
661
- ("which", "nonhuman_relative_used"),
662
- ("what", "free_relative_used")]
663
- made += b.add("English", "grammar", 3,
664
- f"Choose the correct form: {nm} is the {role} ___ "
665
- f"{pred}.",
666
- "whom", dd, "embedded_relative_case")
 
667
  continue
668
 
669
  if kind == "past_perfect":
@@ -676,14 +946,37 @@ def eng_t3(b, n):
676
  ("file", "filed", "filing", "the paperwork"),
677
  ("repair", "repaired", "repairing", "the fence")])
678
  base, past, ing, obj = act
679
- dd = [(past, "simple_past_for_prior_event"),
680
- (f"has {past}", "present_perfect_used"),
681
- (f"was {ing}", "past_progressive_used"),
682
- (f"would {base}", "conditional_used")]
683
- made += b.add("English", "grammar", 3,
684
- f"Choose the correct verb: By the time {trig}, {nm} ___ "
685
- f"{obj}.",
686
- f"had {past}", dd, "past_perfect_sequence")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
687
  continue
688
 
689
  nm = rng.choice(NAMES)
@@ -706,7 +999,7 @@ def main():
706
  ap = argparse.ArgumentParser()
707
  ap.add_argument("--n", type=int, default=250)
708
  ap.add_argument("--seed", type=int, default=20260809)
709
- ap.add_argument("--out", default="mesa_scieng.jsonl")
710
  a = ap.parse_args()
711
 
712
  b = ItemBuilder(random.Random(a.seed))
@@ -717,10 +1010,11 @@ def main():
717
  if got < a.n:
718
  print(f" ! {fn.__name__}: template space exhausted at {got}/{a.n}")
719
 
720
- with open(a.out, "w") as f:
721
- for it in b.items:
722
- f.write(json.dumps(it) + "\n")
723
- print(f"wrote {len(b.items)} items to {a.out}")
 
724
 
725
 
726
  if __name__ == "__main__":
 
25
  import random
26
  from fractions import Fraction
27
 
28
+ from mesa_gen import EXCLUDED_SKILLS, ItemBuilder, write_items
29
 
30
 
31
  # ==========================================================================
 
82
  dd = [(k * fac // 10, "prefix_off_by_one_power"),
83
  (k * fac * 10, "prefix_off_by_one_power"),
84
  (Fraction(k, fac), "conversion_inverted"),
85
+ (k + fac, "operation_wrong"),
86
+ ((k + 1) * fac, "quantity_misread_by_one"),
87
+ ((k - 1) * fac, "quantity_misread_by_one_low")]
88
  made += b.add("Science", "physics", 1,
89
  f"How many {to} are in {k} {frm}?", ans, dd,
90
  "unit_conversion")
 
96
  d = v * t
97
  dd = [(d * t, "multiplied_instead_of_divided"),
98
  (Fraction(t, d), "ratio_inverted"),
99
+ (d - t, "subtracted"), (d + t, "added"),
100
+ (t, "time_copied_from_stem"),
101
+ (d, "distance_copied_from_stem"),
102
+ (v + 1, "quotient_off_by_one"), (max(1, v - 1), "quotient_off_by_one_low")]
103
  made += b.add("Science", "physics", 1,
104
  f"An object travels {d} meters in {t} seconds at a constant "
105
  f"rate. What is its speed?",
 
136
  if kind == "force":
137
  m, a = rng.randint(2, 25), rng.randint(2, 12)
138
  ans = m * a
139
+ dd = [((m + 1) * a, "mass_misread_by_one"),
140
+ (m * (a + 1), "acceleration_misread_by_one"),
141
+ (m + a, "operands_added"), (Fraction(m, a), "operands_divided"),
142
  (Fraction(a, m), "operands_divided_inverted"), (m - a, "subtracted")]
143
  made += b.add("Science", "physics", 2,
144
  f"A net force accelerates a {m} kg object at {a} m/s\u00b2. "
 
150
  if kind == "ohm":
151
  i, r = rng.randint(2, 9), rng.choice([3, 4, 5, 6, 8, 10, 12, 20])
152
  ans = i * r
153
+ dd = [((i + 1) * r, "current_misread_by_one"),
154
+ (i * (r + 1), "resistance_misread_by_one"),
155
+ (i + r, "operands_added"), (Fraction(r, i), "operands_divided"),
156
  (Fraction(i, r), "operands_divided_inverted"), (r - i, "subtracted")]
157
  made += b.add("Science", "physics", 2,
158
  f"A current of {i} A flows through a {r} \u03a9 resistor. "
 
166
  m = d * v
167
  dd = [(m * v, "multiplied_instead_of_divided"),
168
  (Fraction(v, m), "ratio_inverted"), (m - v, "subtracted"),
169
+ (m + v, "added"),
170
+ (v, "volume_copied_from_stem"),
171
+ (m, "mass_copied_from_stem"),
172
+ (d + 1, "quotient_off_by_one"), (max(1, d - 1), "quotient_off_by_one_low")]
173
  made += b.add("Science", "chemistry", 2,
174
  f"A block has a mass of {m} g and a volume of {v} cm\u00b3. "
175
  f"What is its density?",
 
248
  v = rng.choice([10, 20, 30, 40])
249
  h = v * v // 20 # g = 10 m/s^2, v = sqrt(2gh)
250
  m = rng.randint(2, 9)
251
+ dd = [(v + 10, "speed_off_by_step"), (max(5, v - 10), "speed_off_by_step_low"),
252
+ (v // 2, "halved"), (h, "height_reported"),
253
  (2 * 10 * h, "square_root_omitted"), (m * v, "mass_multiplied_in"),
254
  (10 * h, "gravity_times_height_only")]
255
  made += b.add("Science", "physics", 3,
 
321
  ("belong", "belongs", "belonging", "belonged"),
322
  ("wait", "waits", "waiting", "waited")]
323
 
324
+ SV_HEADS = ["box", "crate", "bundle", "stack", "folder", "basket", "tray",
325
+ "carton", "binder", "packet", "canister", "drawer", "sack",
326
+ "parcel", "jar", "pouch"]
327
  SV_MODS = ["old letters", "rusted tools", "blank forms", "glass marbles",
328
+ "dried herbs", "spare keys", "cracked tiles", "faded photographs",
329
+ "loose screws", "brittle rubber bands", "unsorted receipts",
330
+ "chipped buttons", "tangled cables", "yellowed clippings",
331
+ "worn playing cards", "mismatched socks"]
332
+ SV_PLACES = ["shelf", "counter", "table", "windowsill", "workbench", "porch",
333
+ "landing", "sideboard", "radiator", "bench", "mantel", "stoop"]
334
 
335
  REG_PLURALS = ["dogs", "students", "teachers", "farmers", "sailors", "neighbors",
336
+ "artists", "engineers", "painters", "gardeners", "bakers",
337
+ "climbers", "welders", "tailors"]
338
  IRR_PLURALS = [("children", "child"), ("men", "man"), ("women", "woman"),
339
+ ("mice", "mouse"), ("geese", "goose"), ("people", "person"),
340
+ ("oxen", "ox"), ("feet", "foot"), ("teeth", "tooth")]
341
+ POSSESSED = ["toys", "coats", "bicycles", "notebooks", "lunches", "umbrellas",
342
+ "boots", "helmets", "satchels", "mittens", "lanterns", "kites"]
343
 
344
  # each verb carries its own object -- "has given the report" is semantically odd
345
  IRR_VERBS = [("write", "wrote", "written", "the report"),
 
361
  ("tear", "tore", "torn", "the receipt"),
362
  ("forget", "forgot", "forgotten", "the appointment")]
363
 
364
+ # Adjectives that take the -er/-est inflection and can describe a person, so
365
+ # "Of the three finalists, X is the ___" stays sensible. A wider pool also
366
+ # spreads the key counts, which keeps the key-balance gate from thinning the
367
+ # superlative family.
368
+ # Adjectives that take the -er/-est inflection and can describe a person, so
369
+ # "Of the three finalists, X is the ___" stays sensible. The pool is wide on
370
+ # purpose: each adjective is one distinct key, and the key-balance gate thins a
371
+ # family whose keys repeat, so a narrow pool caps how many items survive.
372
  ADJS = [("tall", "taller", "tallest"), ("bright", "brighter", "brightest"),
373
  ("quiet", "quieter", "quietest"), ("strong", "stronger", "strongest"),
374
+ ("clever", "cleverer", "cleverest"), ("swift", "swifter", "swiftest"),
375
+ ("calm", "calmer", "calmest"), ("harsh", "harsher", "harshest"),
376
+ ("bold", "bolder", "boldest"), ("sharp", "sharper", "sharpest"),
377
+ ("humble", "humbler", "humblest"), ("brave", "braver", "bravest"),
378
+ ("fierce", "fiercer", "fiercest"), ("gentle", "gentler", "gentlest"),
379
+ ("keen", "keener", "keenest"), ("proud", "prouder", "proudest"),
380
+ ("shrewd", "shrewder", "shrewdest"), ("stern", "sterner", "sternest"),
381
+ ("nimble", "nimbler", "nimblest"), ("frank", "franker", "frankest"),
382
+ ("wise", "wiser", "wisest"), ("young", "younger", "youngest"),
383
+ ("kind", "kinder", "kindest"), ("quick", "quicker", "quickest"),
384
+ ("slow", "slower", "slowest"), ("neat", "neater", "neatest"),
385
+ ("tough", "tougher", "toughest"), ("plain", "plainer", "plainest"),
386
+ ("smart", "smarter", "smartest"), ("warm", "warmer", "warmest"),
387
+ ("polite", "politer", "politest"), ("subtle", "subtler", "subtlest"),
388
+ ("crafty", "craftier", "craftiest"), ("steady", "steadier", "steadiest"),
389
+ ("hardy", "hardier", "hardiest"), ("lively", "livelier", "liveliest"),
390
+ ("wary", "warier", "wariest"), ("worthy", "worthier", "worthiest"),
391
+ ("lucky", "luckier", "luckiest"), ("busy", "busier", "busiest")]
392
 
393
  NAMES = ["Maria", "Thomas", "Priya", "Daniel", "Ingrid", "Samuel", "Hannah", "Lukas",
394
  "Elena", "Marcus", "Aisha", "Jonas", "Clara", "Viktor", "Noor", "Anton",
 
406
  ("Turning the corner", "the shop", "spotted", "spot")]
407
 
408
 
409
+ # Person-rotated pronoun forms. Fixing the key to a single string ("I") makes
410
+ # the family solvable by option identity alone: a solver that never reads the
411
+ # stem learns that "I" is always the answer. Rotating person spreads the key
412
+ # across five strings, each of which also appears as a distractor in the
413
+ # counterpart case family.
414
+ PRONOUNS = [
415
+ # subject, object, reflexive, agrees_plural
416
+ ("I", "me", "myself", False),
417
+ ("he", "him", "himself", False),
418
+ ("she", "her", "herself", False),
419
+ ("we", "us", "ourselves", True),
420
+ ("they", "them", "themselves", True),
421
+ ]
422
+
423
+
424
+ def other_pronoun(rng, subj):
425
+ """A different person's forms, for wrong-person distractors."""
426
+ return rng.choice([p for p in PRONOUNS if p[0] != subj])
427
+
428
+
429
+ # Agreement families share one option pool.
430
+ #
431
+ # The failure this fixes: if the options are {is, are, having, has been}, only
432
+ # two of them are ever the answer, so the item is really 2-way and a solver that
433
+ # knows which strings are ever keys scores ~50% without reading anything.
434
+ # Drawing every option from the same pool of forms that ARE keys somewhere in
435
+ # the family restores a genuine 4-way choice.
436
+ COPULAR = ["is", "are", "was", "were"]
437
+ POSSESSIVE = ["has", "have", "had"]
438
+
439
+
440
+ PAST_WHEN = ["last term", "at the time", "back then", "that year"]
441
+ PRES_WHEN = ["at present", "this term", "right now", "these days"]
442
+
443
+
444
+ def when_phrase(rng, past):
445
+ """Time adverbial that fixes the tense, so only one form is correct."""
446
+ return rng.choice(PAST_WHEN if past else PRES_WHEN)
447
+
448
+
449
+ def agreement_distractors(rng, key):
450
+ """Three distractors for an agreement item, all drawn from attested keys."""
451
+ if key in COPULAR:
452
+ sing = key in ("is", "was")
453
+ pres = key in ("is", "are")
454
+ out = []
455
+ for f in COPULAR:
456
+ if f == key:
457
+ continue
458
+ f_sing, f_pres = f in ("is", "was"), f in ("is", "are")
459
+ if f_sing != sing and f_pres == pres:
460
+ mode = "number_error"
461
+ elif f_sing == sing and f_pres != pres:
462
+ mode = "tense_error"
463
+ else:
464
+ mode = "number_and_tense_error"
465
+ out.append((f, mode))
466
+ return out
467
+ out = []
468
+ for f in POSSESSIVE:
469
+ if f == key:
470
+ continue
471
+ mode = "tense_error" if f == "had" else "number_error"
472
+ out.append((f, mode))
473
+ out.append((rng.choice(["is", "are"]), "copula_for_possession"))
474
+ return out
475
+
476
+
477
  def eng_t1(b, n):
478
  rng, made, tries = b.rng, 0, 0
479
  while made < n and tries < n * 200:
 
484
  head = rng.choice(SV_HEADS)
485
  mod = rng.choice(SV_MODS)
486
  place = rng.choice(SV_PLACES)
487
+ base, sing, ing, pp = rng.choice(SV_VERBS)
488
+
489
+ # Number AND tense both vary, and every option is drawn from the
490
+ # same pool of forms that are the answer somewhere in the family.
491
+ # A present-tense-only family makes the third-person singular the
492
+ # key every time, which the option set alone gives away.
493
+ plural = rng.random() < 0.5
494
+ subject = f"The {head}s of {mod}" if plural else f"The {head} of {mod}"
495
+ mode = rng.choice(["present", "past", "perfect"])
496
+ if mode == "present":
497
+ ans, tail = (base if plural else sing), f"on the {place}"
498
+ elif mode == "past":
499
+ ans = pp
500
+ tail = (f"on the {place} "
501
+ + rng.choice(["last winter", "that summer",
502
+ "until the move last winter",
503
+ "for years before last winter"]))
504
+ else:
505
+ ans = f"have {pp}" if plural else f"has {pp}"
506
+ tail = (f"on the {place} "
507
+ + rng.choice(["since Tuesday", "ever since the move",
508
+ "since the shop reopened"]))
509
+
510
+ pool = [(base, "number_error"), (sing, "number_error"),
511
+ (pp, "tense_error"), (f"has {pp}", "aspect_and_number_error"),
512
+ (f"have {pp}", "aspect_and_number_error"),
513
+ (f"is {ing}", "aspect_error"), (f"are {ing}", "aspect_error")]
514
+ dd = [(f, m) for f, m in pool if f != ans]
515
  made += b.add("English", "grammar", 1,
516
+ f"Choose the correct verb form: {subject} ___ {tail}.",
517
+ ans, dd, "subject_verb_agreement")
 
518
  continue
519
 
520
  if kind == "poss_reg":
 
551
 
552
  if kind == "pronoun_subj":
553
  nm = rng.choice(NAMES)
554
+ subj, obj, refl, plural = rng.choice(PRONOUNS)
555
+ o_subj, o_obj, o_refl, _ = other_pronoun(rng, subj)
556
+ # Every distractor must be wrong in CASE. A different person in the
557
+ # correct case ("Neither Daniel nor I was told" against a key of
558
+ # "he") is perfectly grammatical, and would give the item two right
559
+ # answers.
560
+ dd = [(obj, "object_case_in_subject_position"),
561
+ (refl, "reflexive_misused"),
562
+ (o_obj, "wrong_person_and_case"),
563
+ (o_refl, "wrong_person_reflexive")]
564
+ verb_pl = "were" if plural else "was"
565
  frame = rng.choice([
566
  f"{nm} and ___ finished the project before the deadline.",
567
  f"{nm} and ___ were asked to present first.",
568
+ f"Neither {nm} nor ___ {verb_pl} told about the change.",
569
  f"{nm} and ___ have volunteered for the early shift.",
570
  ])
571
  made += b.add("English", "grammar", 2,
572
  f"Choose the correct pronoun: {frame}",
573
+ subj, dd, "pronoun_case_subject")
574
  continue
575
 
576
  if kind == "pronoun_obj":
577
  nm = rng.choice(NAMES)
578
+ subj, obj, refl, _ = rng.choice(PRONOUNS)
579
+ o_subj, o_obj, o_refl, _ = other_pronoun(rng, subj)
580
+ # As above: a different person in the object case is grammatical
581
+ # here, so distractors vary case, never person alone.
582
+ dd = [(subj, "subject_case_in_object_position"),
583
+ (refl, "reflexive_misused"),
584
+ (o_subj, "wrong_person_and_case"),
585
+ (o_refl, "wrong_person_reflexive")]
586
  frame = rng.choice([
587
  f"The librarian handed the forms to {nm} and ___.",
588
  f"Between {nm} and ___, the work was finished early.",
 
591
  ])
592
  made += b.add("English", "grammar", 2,
593
  f"Choose the correct pronoun: {frame}",
594
+ obj, dd, "pronoun_case_object")
595
  continue
596
 
597
  if kind == "irr_verb":
 
609
  made += b.add("English", "grammar", 2,
610
  f"Choose the correct form: {frame}",
611
  pp, dd, "irregular_past_participle")
612
+ # Simple-past frames, where the participle is the error instead of
613
+ # the answer. Without this the participle is the key every time and
614
+ # the option set alone gives it away.
615
+ past_frame = rng.choice([
616
+ f"Yesterday {nm} ___ {obj}.",
617
+ f"Last week {nm} ___ {obj}.",
618
+ f"{nm} ___ {obj} before anyone noticed.",
619
+ ])
620
+ dd2 = [(pp, "participle_for_simple_past"), (base, "base_form_used"),
621
+ (base + "ed", "regularized_form"),
622
+ (f"has {pp}", "present_perfect_for_simple_past")]
623
+ made += b.add("English", "grammar", 2,
624
+ f"Choose the correct form: {past_frame}",
625
+ past, dd2, "irregular_past_participle")
626
  continue
627
 
628
  if kind == "compsup":
629
  adj, comp, sup = rng.choice(ADJS)
630
  nm = rng.choice(NAMES)
631
+ other = rng.choice([x for x in NAMES if x != nm])
632
+
633
+ # Emit the superlative AND the comparative from one draw. Emitting
634
+ # only one per iteration leaves each family at roughly half the
635
+ # volume it needs once the key-balance gate starts rejecting, and
636
+ # the superlative family in particular ends up too small to read.
637
+ dd_sup = [(comp, "comparative_for_superlative"),
638
  (f"most {sup}", "double_superlative"),
639
  (f"more {comp}", "double_comparative"),
640
  (f"most {adj}", "periphrastic_form_misused"),
641
  (adj, "positive_form_used")]
642
+ made += b.add("English", "grammar", 2,
643
+ "Choose the correct form: " + rng.choice([
644
+ f"Of the three finalists, {nm} is the ___.",
645
+ f"Of the four applicants, {nm} is the ___.",
646
+ f"Among the five nominees, {nm} is the ___.",
647
+ f"{nm} is the ___ of all the candidates.",
648
+ ]), sup, dd_sup, "superlative_form")
649
+
650
+ dd_comp = [(sup, "superlative_for_comparative"),
651
+ (f"more {comp}", "double_comparative"),
652
+ (f"most {sup}", "double_superlative"),
653
+ (f"more {adj}", "periphrastic_comparative"),
654
+ (adj, "positive_form_used")]
655
+ made += b.add("English", "grammar", 2,
656
+ "Choose the correct form: " + rng.choice([
657
+ f"Of the two candidates, {nm} is the ___ speaker.",
658
+ f"Between the two finalists, {nm} is the ___.",
659
+ f"{nm} is the ___ of the two.",
660
+ f"Compared with {other}, {nm} is the ___.",
661
+ ]), comp, dd_comp, "comparative_form")
662
+
663
+ if rng.random() < 0.4:
664
+ # equative frame: only the positive form is grammatical, so the
665
+ # bare adjective is an attested key rather than a permanent
666
+ # distractor
667
+ dd_eq = [(comp, "comparative_in_equative"),
668
+ (sup, "superlative_in_equative"),
669
+ (f"more {adj}", "periphrastic_comparative"),
670
+ (f"most {adj}", "periphrastic_superlative")]
671
  made += b.add("English", "grammar", 2,
672
+ f"Choose the correct form: {nm} is as ___ as "
673
+ f"{other}.", adj, dd_eq, "comparative_form")
 
 
 
 
 
 
 
 
 
 
 
674
  continue
675
 
676
  nm = rng.choice(NAMES)
677
  thing = rng.choice(["the tickets", "the keys", "the proofs", "the invitation"])
678
+ # Both cases. An object-only family makes "whom" the answer every time.
679
+ if rng.random() < 0.5:
680
+ frame = rng.choice([
681
+ f"___ did {nm} give {thing} to?",
682
+ f"To ___ did {nm} address {thing}?",
683
+ f"{nm} could not recall ___ {pron(nm)} had shown {thing} to.",
684
+ ])
685
+ cap = frame.startswith("___")
686
+ dd = [("Who" if cap else "who", "subject_form_in_object_position"),
687
+ ("Whose" if cap else "whose", "possessive_form_used"),
688
+ ("Whom's" if cap else "whom's", "nonexistent_form"),
689
+ ("Who's" if cap else "who's", "contraction_confused")]
690
+ ans = "Whom" if cap else "whom"
691
+ elif rng.random() < 0.5:
692
+ frame = rng.choice([
693
+ f"___ gave {thing} to {nm}?",
694
+ f"___ signed for {thing} yesterday?",
695
+ f"{nm} could not recall ___ had sent {thing}.",
696
+ ])
697
+ cap = frame.startswith("___")
698
+ dd = [("Whom" if cap else "whom", "object_form_in_subject_position"),
699
+ ("Whose" if cap else "whose", "possessive_form_used"),
700
+ ("Whom's" if cap else "whom's", "nonexistent_form"),
701
+ ("Who's" if cap else "who's", "contraction_confused")]
702
+ ans = "Who" if cap else "who"
703
+ else:
704
+ poss = rng.choice(["coat", "notes", "signature", "car"])
705
+ frame = rng.choice([
706
+ f"___ {poss} was left with {nm}?",
707
+ f"{nm} could not recall ___ {poss} had been left behind.",
708
+ ])
709
+ cap = frame.startswith("___")
710
+ dd = [("Who" if cap else "who", "subject_form_for_possessive"),
711
+ ("Whom" if cap else "whom", "object_form_for_possessive"),
712
+ ("Who's" if cap else "who's", "contraction_confused"),
713
+ ("Whom's" if cap else "whom's", "nonexistent_form")]
714
+ ans = "Whose" if cap else "whose"
715
  made += b.add("English", "grammar", 2,
716
  f"Choose the correct form: {frame}", ans, dd,
717
  "relative_pronoun_case")
 
748
  sg, pl = rng.choice(SINGS), rng.choice(PLURALS)
749
  pred = rng.choice(["satisfied with the outcome", "aware of the change",
750
  "present at the hearing", "eligible for the bonus"])
751
+ # The verb agrees with the NEARER conjunct.
752
+ near_plural = rng.random() < 0.5
753
+ past = rng.random() < 0.5
754
+ first, second = (sg, pl) if near_plural else (pl, sg)
755
+ ans = ("were" if near_plural else "was") if past else \
756
+ ("are" if near_plural else "is")
757
+ when = when_phrase(rng, past)
758
+ made += b.add("English", "grammar", 3,
759
+ f"Choose the correct verb: Neither the {first} nor the "
760
+ f"{second} ___ {pred} {when}.",
761
+ ans, agreement_distractors(rng, ans),
 
 
 
 
762
  "proximity_agreement")
763
  continue
764
 
765
  if kind == "each":
766
  pl = rng.choice(PLURALS)
767
+ plural = rng.random() < 0.5
768
+ quant = (rng.choice(["Both", "All", "Several", "Many"]) if plural
769
+ else rng.choice(["Each", "Every one", "Neither"]))
770
+ if rng.random() < 0.5:
771
+ th = rng.choice(["a locker", "a number", "a folder", "a seat",
772
+ "a mentor", "a badge"])
773
+ past = rng.random() < 0.5
774
+ ans = "had" if past else ("have" if plural else "has")
775
+ tail = (f"{th} assigned at registration "
776
+ f"{when_phrase(rng, past)}.")
777
+ else:
778
+ adj = rng.choice(["eligible for the bonus", "aware of the change",
779
+ "present at the hearing", "late for the briefing"])
780
+ past = rng.random() < 0.5
781
+ ans = ("were" if plural else "was") if past else \
782
+ ("are" if plural else "is")
783
+ tail = f"{adj} {when_phrase(rng, past)}."
784
  made += b.add("English", "grammar", 3,
785
+ f"Choose the correct verb: {quant} of the {pl} ___ {tail}",
786
+ ans, agreement_distractors(rng, ans),
787
+ "indefinite_pronoun_agreement")
788
  continue
789
 
790
  if kind == "expletive":
 
 
791
  cause = rng.choice(["for the delay", "for the revision",
792
  "behind the decision", "for the shortfall"])
793
+ plural = rng.random() < 0.5
794
+ past = rng.random() < 0.5
795
+ if plural:
796
+ subj = rng.choice(["several reasons", "many objections",
797
+ "three exceptions", "two explanations",
798
+ "four candidates", "some doubts"])
799
+ ans = "were" if past else "are"
800
+ else:
801
+ subj = rng.choice(["one reason", "a single objection",
802
+ "one exception", "another explanation",
803
+ "one candidate", "little doubt"])
804
+ ans = "was" if past else "is"
805
+ when = " " + when_phrase(rng, past)
806
  made += b.add("English", "grammar", 3,
807
+ f"Choose the correct verb: There ___ {subj} {cause}"
808
+ f"{when}.",
809
+ ans, agreement_distractors(rng, ans),
810
+ "expletive_construction_agreement")
811
  continue
812
 
813
  if kind == "number_of":
814
  pl = rng.choice(PLURALS)
815
+ # "A number of X" takes a plural verb; "The number of X" singular.
816
+ plural = rng.random() < 0.5
817
+ det = "A" if plural else "The"
818
  if rng.random() < 0.5:
819
+ people_pred, count_pred = rng.choice([
820
+ ("arrived at the meeting today", "risen sharply so far this year"),
821
+ ("responded to the notice today", "declined since April this year"),
822
+ ("finished the assignment today", "remained steady up to today"),
823
+ ("volunteered for the event today", "grown every year through today"),
824
+ ])
825
+ ans = "have" if plural else "has"
826
+ tail = people_pred if plural else count_pred
827
  else:
828
+ # "A number of X" predicates describe the PEOPLE; "The number of
829
+ # X" predicates describe the NUMBER. Swapping them produces
830
+ # sentences like "A number of employees were unusually high".
831
+ adj = (rng.choice(["eligible for the bonus", "aware of the change",
832
+ "present at the hearing", "still waiting"])
833
+ if plural else
834
+ rng.choice(["unusually high", "hard to explain",
835
+ "under review", "still provisional"]))
836
+ past = rng.random() < 0.5
837
+ ans = ("were" if plural else "was") if past else \
838
+ ("are" if plural else "is")
839
+ tail = f"{adj} {when_phrase(rng, past)}"
840
+ made += b.add("English", "grammar", 3,
841
+ f"Choose the correct verb: {det} number of {pl} ___ "
842
+ f"{tail}.",
843
+ ans, agreement_distractors(rng, ans),
844
+ "number_of_agreement")
845
  continue
846
 
847
  if kind == "subjunctive":
848
  body = rng.choice(["committee", "board", "council", "panel", "faculty"])
849
+ verb = rng.choice(["recommends", "requests", "requires", "asks", "demands"])
850
  subj = rng.choice(["the proposal", "the schedule", "the clause",
851
  "the budget", "the report"])
852
  comp = rng.choice(["revised", "postponed", "withdrawn", "reconsidered"])
853
+ # Passive frames make "be" the answer every time. Active frames put
854
+ # a lexical verb in the subjunctive slot instead, so the key varies.
855
+ if rng.random() < 0.5:
856
+ dd = [("is", "indicative_present"), ("was", "indicative_past"),
857
+ ("will be", "future_indicative"),
858
+ ("being", "nonfinite_form")]
859
+ made += b.add("English", "grammar", 3,
860
+ f"Choose the correct verb: The {body} {verb} that "
861
+ f"{subj} ___ {comp}.",
862
+ "be", dd, "subjunctive_mood")
863
+ else:
864
+ role = rng.choice(["chair", "registrar", "treasurer", "clerk",
865
+ "auditor"])
866
+ base, third, past = rng.choice([
867
+ ("submit", "submits", "submitted"),
868
+ ("revise", "revises", "revised"),
869
+ ("postpone", "postpones", "postponed"),
870
+ ("review", "reviews", "reviewed"),
871
+ ("withdraw", "withdraws", "withdrew"),
872
+ ])
873
+ dd = [(third, "indicative_present"), (past, "indicative_past"),
874
+ (f"will {base}", "future_indicative"),
875
+ (f"{base[:-1] if base.endswith('e') else base}ing",
876
+ "nonfinite_form")]
877
+ made += b.add("English", "grammar", 3,
878
+ f"Choose the correct verb: The {body} {verb} that "
879
+ f"the {role} ___ {subj}.",
880
+ base, dd, "subjunctive_mood")
881
  continue
882
 
883
  if kind == "inversion":
884
+ place, pl, sg = rng.choice([
885
+ ("Among the finalists",
886
+ "two former champions", "a former champion"),
887
+ ("Behind the old barn",
888
+ "three rusted plows", "a rusted plow"),
889
+ ("Beneath the floorboards",
890
+ "several loose wires", "one loose wire"),
891
+ ("Across the valley",
892
+ "four abandoned huts", "an abandoned hut"),
893
+ ("Inside the sealed crate",
894
+ "dozens of yellowed letters", "a yellowed letter"),
895
+ ])
896
+ plural = rng.random() < 0.5
897
+ past = rng.random() < 0.5
898
+ subj = pl if plural else sg
899
+ ans = ("were" if plural else "was") if past else \
900
+ ("are" if plural else "is")
901
+ when = " " + when_phrase(rng, past)
902
  made += b.add("English", "grammar", 3,
903
+ f"Choose the correct verb: {place} ___ {subj}{when}.",
904
+ ans, agreement_distractors(rng, ans),
905
+ "inverted_subject_agreement")
906
  continue
907
 
908
  if kind == "embedded_case":
909
  nm = rng.choice(NAMES)
910
  role = rng.choice(["candidate", "applicant", "witness", "trainee",
911
  "delegate"])
912
+ # Both cases from one draw, for the same reason as compsup above.
913
+ # relative pronoun is the SUBJECT of the embedded clause -> "who"
914
+ subj_pred = rng.choice(["will win", "should lead the team",
915
+ "deserves the grant", "can finish the audit"])
916
+ made += b.add("English", "grammar", 3,
917
+ f"Choose the correct form: {nm} is the {role} ___ "
918
+ f"we believe {subj_pred}.",
919
+ "who",
920
+ [("whom", "object_form_in_subject_position"),
921
+ ("whose", "possessive_form_used"),
922
+ ("which", "nonhuman_relative_used"),
923
+ ("what", "free_relative_used")],
924
+ "embedded_relative_case")
925
+ # relative pronoun is the OBJECT of the embedded clause -> "whom"
926
+ obj_pred = rng.choice(["we recommended", "the panel selected",
927
  "the director interviewed", "everyone praised"])
928
+ made += b.add("English", "grammar", 3,
929
+ f"Choose the correct form: {nm} is the {role} ___ "
930
+ f"{obj_pred}.",
931
+ "whom",
932
+ [("who", "subject_form_in_object_position"),
933
+ ("whose", "possessive_form_used"),
934
+ ("which", "nonhuman_relative_used"),
935
+ ("what", "free_relative_used")],
936
+ "embedded_relative_case")
937
  continue
938
 
939
  if kind == "past_perfect":
 
946
  ("file", "filed", "filing", "the paperwork"),
947
  ("repair", "repaired", "repairing", "the fence")])
948
  base, past, ing, obj = act
949
+ pp = past # these verbs are regular; participle == simple past
950
+ forms = [f"had {pp}", past, f"has {pp}", f"was {ing}"]
951
+
952
+ def others(keep):
953
+ return [(f, m) for f, m in zip(
954
+ forms, ["past_perfect_used", "simple_past_used",
955
+ "present_perfect_used", "past_progressive_used"])
956
+ if f != keep]
957
+
958
+ roll = rng.random()
959
+ if roll < 0.4:
960
+ # prior-event context requires the past perfect
961
+ made += b.add("English", "grammar", 3,
962
+ f"Choose the correct verb: By the time {trig}, {nm} "
963
+ f"___ {obj}.",
964
+ f"had {pp}", others(f"had {pp}"),
965
+ "past_perfect_sequence")
966
+ elif roll < 0.7:
967
+ # definite past time adverbial requires the simple past
968
+ when = rng.choice(["last Tuesday", "at noon yesterday",
969
+ "on Friday morning", "two weeks ago"])
970
+ made += b.add("English", "grammar", 3,
971
+ f"Choose the correct verb: {nm} ___ {obj} {when}.",
972
+ past, others(past), "past_perfect_sequence")
973
+ else:
974
+ # "already", with present relevance, requires present perfect
975
+ made += b.add("English", "grammar", 3,
976
+ f"Choose the correct verb: {nm} ___ {obj} already, "
977
+ f"so there is nothing left to do.",
978
+ f"has {pp}", others(f"has {pp}"),
979
+ "past_perfect_sequence")
980
  continue
981
 
982
  nm = rng.choice(NAMES)
 
999
  ap = argparse.ArgumentParser()
1000
  ap.add_argument("--n", type=int, default=250)
1001
  ap.add_argument("--seed", type=int, default=20260809)
1002
+ ap.add_argument("--out", default="scieng.jsonl")
1003
  a = ap.parse_args()
1004
 
1005
  b = ItemBuilder(random.Random(a.seed))
 
1010
  if got < a.n:
1011
  print(f" ! {fn.__name__}: template space exhausted at {got}/{a.n}")
1012
 
1013
+ kept, dropped = write_items(b.items, a.out)
1014
+ if dropped:
1015
+ print(f" ! dropped {dropped} items from excluded families: "
1016
+ f"{', '.join(sorted(EXCLUDED_SKILLS))}")
1017
+ print(f"wrote {kept} items to {a.out}")
1018
 
1019
 
1020
  if __name__ == "__main__":
harness/README.md ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MESA task tree for lm-evaluation-harness
2
+
3
+ Run from the MESA directory and point `--include_path` at `./harness`. The
4
+ shared template loads the local dataset through `dataset_path: ../mesa`.
5
+
6
+ ```bash
7
+ lm_eval --model hf --model_args pretrained=<model> \
8
+ --tasks mesa --include_path ./harness --batch_size 16
9
+
10
+ lm_eval --model hf --model_args pretrained=<model> \
11
+ --tasks mesa_by_tier --include_path ./harness --batch_size 16
12
+ ```
13
+
14
+ Two invocations, not one: both groups reach the same twelve leaves, and
15
+ lm-evaluation-harness refuses a selection where a leaf is reachable twice
16
+ (`ValueError: Duplicate task 'mesa_math_1'`). Verified against lm_eval 0.4.12.
17
+
18
+ ## What is here
19
+
20
+ | File | Role |
21
+ |---|---|
22
+ | `_mesa_template.yaml` | shared leaf config: dataset, scoring mode, metrics |
23
+ | `mesa_<domain>_<tier>.yaml` | the twelve leaf tasks |
24
+ | `mesa_1/2/3.yaml` | tier rollups |
25
+ | `mesa_<domain>.yaml` | domain rollups |
26
+ | `mesa.yaml` | headline group over the four domain rollups (primary) |
27
+ | `mesa_by_tier.yaml` | secondary group over the three tier rollups |
28
+ | `utils.py` | domain filters and item rendering |
29
+
30
+ `--tasks mesa` gives seventeen numbers: twelve cells, four domain rollups, one
31
+ headline. Domain is the primary axis. `mesa_by_tier` adds the three tier
32
+ rollups; it is secondary because tier is a template-assigned group, not a
33
+ verified step count or difficulty rank (see the top-level README). It re-scores the same twelve
34
+ leaves along the domain axis, so running both evaluates each item twice; that
35
+ costs a second pass but keeps every rollup size-weighted over exactly the cells
36
+ it covers.
37
+
38
+ A `--model dummy` run should land every cell near 0.25. That is the cheapest
39
+ check that the tree, the filters and the rendering are wired correctly.
40
+
41
+ ## Scoring
42
+
43
+ `output_type: multiple_choice`, ranked by continuation loglikelihood.
44
+ **Report `acc`, not `acc_norm`.** `ItemBuilder` already balances option length
45
+ inside every item, so byte-length normalisation corrects for a bias the
46
+ construction has already removed, and it over-corrects worst on the cells with
47
+ the shortest options. The following gpt2 (124M) results were measured on this
48
+ revision:
49
+
50
+ | cell | acc | acc_norm |
51
+ |---|---|---|
52
+ | mesa_english_3 | 0.709 | 0.520 |
53
+ | mesa_english_2 | 0.616 | 0.328 |
54
+ | mesa_science_3 | 0.320 | 0.096 |
55
+ | mesa_math_2 | 0.264 | 0.168 |
56
+ | **mean over all twelve cells** | **0.339** | **0.262** |
57
+
58
+ `acc_norm` puts seven of the twelve cells below the 0.25 chance floor. It is still
59
+ reported, but `acc` is the headline.
60
+
61
+ `utils.doc_to_text` / `doc_to_choice` handle the two stem shapes:
62
+
63
+ - **cloze** (`___` in the stem, 567 English items) -- context is the text before
64
+ the blank, continuation is `option + text after the blank`. Substituting into
65
+ the blank is the whole point: appending after the stem leaves the blank
66
+ unfilled and makes every option ungrammatical, key included.
67
+ - **question** (everything else) -- context is the stem plus `\nAnswer:`,
68
+ continuation is the option.
69
+
70
+ Both branches are per-item, so an item's four options always render the same
71
+ way as each other.
72
+
73
+ ## Canary
74
+
75
+ The first record of every data file is the contamination canary and has no
76
+ `domain`. The `filter_*` functions in `utils.py` compare `d.get("domain")`
77
+ against a domain name, so the canary drops out of all twelve leaves. Any new
78
+ task added here must filter it out too.
harness/_mesa_template.yaml ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Shared configuration for the twelve MESA leaf tasks.
2
+ #
3
+ # Scoring is continuation loglikelihood: each option is rendered into the stem
4
+ # by utils.doc_to_choice and ranked by its logprob. Chance is 25%.
5
+ #
6
+ # Report acc, NOT acc_norm. ItemBuilder already balances option length inside
7
+ # every item (see LENGTH_BUDGET in generators/mesa_gen.py), so byte-length
8
+ # normalisation is a second correction applied on top of one the construction
9
+ # has already made, and it over-corrects hardest where options are shortest.
10
+ # On this revision, gpt2 averaged 0.262 with acc_norm against 0.339 with acc
11
+ # across the twelve cells; seven acc_norm cells fell below chance.
12
+ # acc_norm is still reported as a secondary number.
13
+ # Run lm_eval from the MESA repository root. The explicit directory name avoids
14
+ # a datasets path-resolution bug for `.` with multiple local configs.
15
+ dataset_path: ../mesa
16
+ dataset_name: all
17
+ test_split: test
18
+ output_type: multiple_choice
19
+ doc_to_text: !function utils.doc_to_text
20
+ doc_to_choice: !function utils.doc_to_choice
21
+ doc_to_target: answer_idx
22
+ metric_list:
23
+ - metric: acc
24
+ aggregation: mean
25
+ higher_is_better: true
26
+ - metric: acc_norm
27
+ aggregation: mean
28
+ higher_is_better: true
29
+ metadata:
30
+ version: 1.0
harness/mesa.yaml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Headline group, aggregated by DOMAIN.
2
+ #
3
+ # Domain is the primary axis: a pretraining mixture change moves one domain and
4
+ # not another, and that is the signal MESA exists to show. `--tasks mesa`
5
+ # reports seventeen numbers in one pass -- the twelve cells, the four domain
6
+ # rollups, and this aggregate.
7
+ #
8
+ # The TIER axis is available as `mesa_by_tier` but is NOT the headline. Both
9
+ # models measured on this revision scored higher on MESA-3 than MESA-1. Tier
10
+ # identifies a template group, not a measured step count or difficulty rank.
11
+ # See "Measured baselines" in the README. Run it as a separate invocation;
12
+ # lm-evaluation-harness refuses a selection in which the same leaf is reachable
13
+ # from two chosen groups.
14
+ group: mesa
15
+ task:
16
+ - mesa_math
17
+ - mesa_english
18
+ - mesa_science
19
+ - mesa_art
20
+ aggregate_metric_list:
21
+ - metric: acc
22
+ aggregation: mean
23
+ weight_by_size: true
24
+ metadata:
25
+ version: 1.0
harness/mesa_1.yaml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ group: mesa_1
2
+ task:
3
+ - mesa_math_1
4
+ - mesa_english_1
5
+ - mesa_science_1
6
+ - mesa_art_1
7
+ aggregate_metric_list:
8
+ - metric: acc
9
+ aggregation: mean
10
+ weight_by_size: true
11
+ metadata:
12
+ version: 1.0
harness/mesa_2.yaml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ group: mesa_2
2
+ task:
3
+ - mesa_math_2
4
+ - mesa_english_2
5
+ - mesa_science_2
6
+ - mesa_art_2
7
+ aggregate_metric_list:
8
+ - metric: acc
9
+ aggregation: mean
10
+ weight_by_size: true
11
+ metadata:
12
+ version: 1.0
harness/mesa_3.yaml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ group: mesa_3
2
+ task:
3
+ - mesa_math_3
4
+ - mesa_english_3
5
+ - mesa_science_3
6
+ - mesa_art_3
7
+ aggregate_metric_list:
8
+ - metric: acc
9
+ aggregation: mean
10
+ weight_by_size: true
11
+ metadata:
12
+ version: 1.0
mesa.yaml → harness/mesa_art.yaml RENAMED
@@ -1,10 +1,10 @@
1
- group: mesa
2
  task:
3
- - mesa_1
4
- - mesa_2
5
- - mesa_3
6
  aggregate_metric_list:
7
- - metric: acc_norm
8
  aggregation: mean
9
  weight_by_size: true
10
  metadata:
 
1
+ group: mesa_art
2
  task:
3
+ - mesa_art_1
4
+ - mesa_art_2
5
+ - mesa_art_3
6
  aggregate_metric_list:
7
+ - metric: acc
8
  aggregation: mean
9
  weight_by_size: true
10
  metadata:
harness/mesa_art_1.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ include: _mesa_template.yaml
2
+ task: mesa_art_1
3
+ dataset_name: mesa-1
4
+ process_docs: !function utils.filter_art
harness/mesa_art_2.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ include: _mesa_template.yaml
2
+ task: mesa_art_2
3
+ dataset_name: mesa-2
4
+ process_docs: !function utils.filter_art
harness/mesa_art_3.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ include: _mesa_template.yaml
2
+ task: mesa_art_3
3
+ dataset_name: mesa-3
4
+ process_docs: !function utils.filter_art
harness/mesa_by_tier.yaml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tier rollups: the same twelve leaves aggregated by template-assigned tier.
2
+ #
3
+ # Secondary, and deliberately not the headline. Both models measured on this
4
+ # revision scored HIGHER on MESA-3 than MESA-1, so this axis did not order
5
+ # difficulty at the 125M scale -- see "Measured baselines" in the README.
6
+ # It is kept as a useful template-group breakdown.
7
+ #
8
+ # Separate invocation from `mesa`; the two groups share their leaves.
9
+ group: mesa_by_tier
10
+ task:
11
+ - mesa_1
12
+ - mesa_2
13
+ - mesa_3
14
+ aggregate_metric_list:
15
+ - metric: acc
16
+ aggregation: mean
17
+ weight_by_size: true
18
+ metadata:
19
+ version: 1.0
harness/mesa_english.yaml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ group: mesa_english
2
+ task:
3
+ - mesa_english_1
4
+ - mesa_english_2
5
+ - mesa_english_3
6
+ aggregate_metric_list:
7
+ - metric: acc
8
+ aggregation: mean
9
+ weight_by_size: true
10
+ metadata:
11
+ version: 1.0
harness/mesa_english_1.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ include: _mesa_template.yaml
2
+ task: mesa_english_1
3
+ dataset_name: mesa-1
4
+ process_docs: !function utils.filter_english
harness/mesa_english_2.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ include: _mesa_template.yaml
2
+ task: mesa_english_2
3
+ dataset_name: mesa-2
4
+ process_docs: !function utils.filter_english
harness/mesa_english_3.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ include: _mesa_template.yaml
2
+ task: mesa_english_3
3
+ dataset_name: mesa-3
4
+ process_docs: !function utils.filter_english
harness/mesa_math.yaml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ group: mesa_math
2
+ task:
3
+ - mesa_math_1
4
+ - mesa_math_2
5
+ - mesa_math_3
6
+ aggregate_metric_list:
7
+ - metric: acc
8
+ aggregation: mean
9
+ weight_by_size: true
10
+ metadata:
11
+ version: 1.0
harness/mesa_math_1.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ include: _mesa_template.yaml
2
+ task: mesa_math_1
3
+ dataset_name: mesa-1
4
+ process_docs: !function utils.filter_math
harness/mesa_math_2.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ include: _mesa_template.yaml
2
+ task: mesa_math_2
3
+ dataset_name: mesa-2
4
+ process_docs: !function utils.filter_math
harness/mesa_math_3.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ include: _mesa_template.yaml
2
+ task: mesa_math_3
3
+ dataset_name: mesa-3
4
+ process_docs: !function utils.filter_math
harness/mesa_science.yaml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ group: mesa_science
2
+ task:
3
+ - mesa_science_1
4
+ - mesa_science_2
5
+ - mesa_science_3
6
+ aggregate_metric_list:
7
+ - metric: acc
8
+ aggregation: mean
9
+ weight_by_size: true
10
+ metadata:
11
+ version: 1.0
harness/mesa_science_1.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ include: _mesa_template.yaml
2
+ task: mesa_science_1
3
+ dataset_name: mesa-1
4
+ process_docs: !function utils.filter_science
harness/mesa_science_2.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ include: _mesa_template.yaml
2
+ task: mesa_science_2
3
+ dataset_name: mesa-2
4
+ process_docs: !function utils.filter_science
harness/mesa_science_3.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ include: _mesa_template.yaml
2
+ task: mesa_science_3
3
+ dataset_name: mesa-3
4
+ process_docs: !function utils.filter_science
harness/utils.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Document processing for the MESA task tree.
2
+
3
+ Two jobs:
4
+
5
+ 1. Tier/domain routing. Each tier lives in its own dataset config, so a leaf
6
+ task loads only its tier and filters by domain here. The filters also drop
7
+ the contamination canary, which is the first record of every data file and
8
+ has no ``domain`` field.
9
+
10
+ 2. Item rendering for continuation loglikelihood. MESA has two stem shapes and
11
+ they must not be rendered the same way:
12
+
13
+ * **Cloze** stems carry a ``___`` blank mid-sentence (567 of the 727 English
14
+ items). The option belongs IN the blank, not after the stem. Appending
15
+ instead of substituting leaves the blank unfilled and makes every option
16
+ -- the key included -- ungrammatical, which is not a measurement of
17
+ anything. The context is the text before the blank and the continuation is
18
+ ``option + text after the blank``.
19
+
20
+ * **Question** stems are complete questions. These get an ``Answer:`` cue
21
+ and the option is appended.
22
+
23
+ The four options of a single item always render through the same branch, so
24
+ the ranking within an item is never comparing two different formats.
25
+ """
26
+
27
+ import datasets
28
+
29
+ BLANK = "___"
30
+
31
+
32
+ # ---------------------------------------------------------------- rendering
33
+
34
+ def _split_stem(stem):
35
+ """Return (before_blank, after_blank), or (None, None) for a question."""
36
+ if BLANK not in stem:
37
+ return None, None
38
+ head, _, tail = stem.partition(BLANK)
39
+ return head.rstrip(), tail
40
+
41
+
42
+ def doc_to_text(doc):
43
+ head, _ = _split_stem(doc["stem"])
44
+ if head is not None:
45
+ return head
46
+ return doc["stem"].rstrip() + "\nAnswer:"
47
+
48
+
49
+ def doc_to_choice(doc):
50
+ _, tail = _split_stem(doc["stem"])
51
+ if tail is not None:
52
+ return [" " + c + tail for c in doc["choices"]]
53
+ return [" " + c for c in doc["choices"]]
54
+
55
+
56
+ # ---------------------------------------------------------------- routing
57
+
58
+ def _by_domain(domain):
59
+ def fn(dataset: datasets.Dataset) -> datasets.Dataset:
60
+ return dataset.filter(lambda d: d.get("domain") == domain)
61
+ return fn
62
+
63
+
64
+ filter_math = _by_domain("Math")
65
+ filter_english = _by_domain("English")
66
+ filter_science = _by_domain("Science")
67
+ filter_art = _by_domain("Art")
mesa_baselines.py → tools/mesa_baselines.py RENAMED
@@ -11,6 +11,14 @@ cell must be rebuilt. Run this BEFORE any model ever sees the benchmark.
11
  overlap - pick the option sharing the most word types with the stem
12
  position - always pick option A (checks answer-position balance)
13
  odd_one_out - pick the option least similar to the other three
 
 
 
 
 
 
 
 
14
  """
15
 
16
  import json
@@ -19,6 +27,8 @@ import sys
19
  import collections
20
 
21
  CHANCE = 25.0
 
 
22
 
23
 
24
  def toks(s):
@@ -57,6 +67,20 @@ def solve_odd(it):
57
  return _score(sims, it["answer_idx"], min)
58
 
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  SOLVERS = {
61
  "longest": solve_longest,
62
  "shortest": solve_shortest,
@@ -65,41 +89,91 @@ SOLVERS = {
65
  "odd_one_out": solve_odd,
66
  }
67
 
68
-
69
- def main(path):
70
- items = [json.loads(l) for l in open(path)]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  cells = collections.defaultdict(list)
72
  for it in items:
73
  cells[(it["domain"], it["tier"])].append(it)
74
 
75
- print(f"{'cell':<12}{'n':>5} " + "".join(f"{k:>13}" for k in SOLVERS) + f"{'ANY':>8}")
76
- print("-" * (17 + 13 * len(SOLVERS) + 8))
 
77
 
78
- flagged = []
79
  for cell in sorted(cells):
80
  its = cells[cell]
 
 
 
 
 
 
 
 
81
  row, any_hits = [], 0
82
  per_solver = {}
83
- for name, fn in SOLVERS.items():
84
- per_solver[name] = 100.0 * sum(fn(it) for it in its) / len(its)
85
  row.append(per_solver[name])
86
  for it in its:
87
- any_hits += max(fn(it) for fn in SOLVERS.values())
88
  anyv = 100.0 * any_hits / len(its)
89
  label = f"{cell[0]}-{cell[1]}"
90
  print(f"{label:<12}{len(its):>5} " + "".join(f"{v:>12.1f}%" for v in row)
91
  + f"{anyv:>7.1f}%")
92
  for name, v in per_solver.items():
93
- if v >= 35.0:
94
  flagged.append((label, name, v))
 
 
95
 
96
  print()
97
  if flagged:
98
- print("FLAGGED (solver >= 35%, rebuild these distractor families):")
99
- for label, name, v in flagged:
 
100
  print(f" {label}: {name} = {v:.1f}%")
101
  else:
102
- print("No solver exceeded 35% in any cell. Distractors are holding.")
 
 
 
 
 
 
 
 
103
 
104
  # answer position balance
105
  pos = collections.Counter(it["answer_idx"] for it in items)
@@ -107,5 +181,8 @@ def main(path):
107
  " ".join(f"{'ABCD'[k]}={100.0*pos[k]/len(items):.1f}%" for k in range(4)))
108
 
109
 
 
 
 
110
  if __name__ == "__main__":
111
- main(sys.argv[1] if len(sys.argv) > 1 else "mesa_procedural.jsonl")
 
11
  overlap - pick the option sharing the most word types with the stem
12
  position - always pick option A (checks answer-position balance)
13
  odd_one_out - pick the option least similar to the other three
14
+ majority_key - pick whichever option is most often the KEY elsewhere in
15
+ the same cell, scored leave-one-out
16
+
17
+ majority_key is the one that catches a family whose answer is a fixed string.
18
+ If "has" is the key every time it appears and is rarely a distractor, then the
19
+ option set alone identifies the answer and the item measures nothing. Length and
20
+ overlap solvers do not see this at all; a cell can pass all four of them and
21
+ still be most of the way solvable without the stem.
22
  """
23
 
24
  import json
 
27
  import collections
28
 
29
  CHANCE = 25.0
30
+ REBUILD = 35.0 # at or above this, the cell leaks and must be rebuilt
31
+ WARN = 30.0 # at or above this, the margin is thin -- report it explicitly
32
 
33
 
34
  def toks(s):
 
67
  return _score(sims, it["answer_idx"], min)
68
 
69
 
70
+ def solve_majority_key(it, key_counts):
71
+ """Leave-one-out: how often is each option the key ELSEWHERE in this cell?
72
+
73
+ Excluding the item itself is what keeps this honest -- otherwise every item
74
+ trivially votes for its own key.
75
+ """
76
+ key = it["choices"][it["answer_idx"]]
77
+ scores = []
78
+ for c in it["choices"]:
79
+ n = key_counts.get(c, 0)
80
+ scores.append(n - 1 if c == key else n)
81
+ return _score(scores, it["answer_idx"], max)
82
+
83
+
84
  SOLVERS = {
85
  "longest": solve_longest,
86
  "shortest": solve_shortest,
 
89
  "odd_one_out": solve_odd,
90
  }
91
 
92
+ # Solvers needing cell-level context rather than just the item.
93
+ CONTEXTUAL = {"majority_key": solve_majority_key}
94
+ ALL_SOLVERS = list(SOLVERS) + list(CONTEXTUAL)
95
+
96
+
97
+ def load_items(paths):
98
+ """Read one or more MESA JSONL files, skipping contamination canary rows.
99
+
100
+ The canary is the first record of every shipped data file and carries no
101
+ domain or tier, so it must be dropped before anything indexes those fields.
102
+ """
103
+ if isinstance(paths, str):
104
+ paths = [paths]
105
+ items, canaries = [], 0
106
+ for path in paths:
107
+ with open(path) as f:
108
+ for line in f:
109
+ if not line.strip():
110
+ continue
111
+ rec = json.loads(line)
112
+ if "canary" in rec or "stem" not in rec:
113
+ canaries += 1
114
+ continue
115
+ items.append(rec)
116
+ if canaries:
117
+ print(f"(skipped {canaries} canary record(s))\n")
118
+ return items
119
+
120
+
121
+ def main(paths):
122
+ items = load_items(paths)
123
+ if not items:
124
+ sys.exit("no items found -- check the path(s) given")
125
  cells = collections.defaultdict(list)
126
  for it in items:
127
  cells[(it["domain"], it["tier"])].append(it)
128
 
129
+ print(f"{'cell':<12}{'n':>5} " + "".join(f"{k:>13}" for k in ALL_SOLVERS)
130
+ + f"{'ANY':>8}")
131
+ print("-" * (17 + 13 * len(ALL_SOLVERS) + 8))
132
 
133
+ flagged, warned = [], []
134
  for cell in sorted(cells):
135
  its = cells[cell]
136
+ key_counts = collections.Counter(
137
+ it["choices"][it["answer_idx"]] for it in its)
138
+
139
+ def run(name, it):
140
+ if name in CONTEXTUAL:
141
+ return CONTEXTUAL[name](it, key_counts)
142
+ return SOLVERS[name](it)
143
+
144
  row, any_hits = [], 0
145
  per_solver = {}
146
+ for name in ALL_SOLVERS:
147
+ per_solver[name] = 100.0 * sum(run(name, it) for it in its) / len(its)
148
  row.append(per_solver[name])
149
  for it in its:
150
+ any_hits += max(run(name, it) for name in ALL_SOLVERS)
151
  anyv = 100.0 * any_hits / len(its)
152
  label = f"{cell[0]}-{cell[1]}"
153
  print(f"{label:<12}{len(its):>5} " + "".join(f"{v:>12.1f}%" for v in row)
154
  + f"{anyv:>7.1f}%")
155
  for name, v in per_solver.items():
156
+ if v >= REBUILD:
157
  flagged.append((label, name, v))
158
+ elif v >= WARN:
159
+ warned.append((label, name, v))
160
 
161
  print()
162
  if flagged:
163
+ print(f"FLAGGED (solver >= {REBUILD:.0f}%, rebuild these distractor "
164
+ f"families):")
165
+ for label, name, v in sorted(flagged, key=lambda x: -x[2]):
166
  print(f" {label}: {name} = {v:.1f}%")
167
  else:
168
+ print(f"No solver reached {REBUILD:.0f}% in any cell.")
169
+
170
+ if warned:
171
+ print(f"\nTHIN MARGIN ({WARN:.0f}% <= solver < {REBUILD:.0f}%). Not a "
172
+ f"rebuild trigger, but do not\nreport these cells as clean "
173
+ f"without the number:")
174
+ for label, name, v in sorted(warned, key=lambda x: -x[2]):
175
+ print(f" {label}: {name} = {v:.1f}% "
176
+ f"(+{v - CHANCE:.1f}pp over chance)")
177
 
178
  # answer position balance
179
  pos = collections.Counter(it["answer_idx"] for it in items)
 
181
  " ".join(f"{'ABCD'[k]}={100.0*pos[k]/len(items):.1f}%" for k in range(4)))
182
 
183
 
184
+ DEFAULT_PATHS = ["../data/mesa-1.jsonl", "../data/mesa-2.jsonl",
185
+ "../data/mesa-3.jsonl"]
186
+
187
  if __name__ == "__main__":
188
+ main(sys.argv[1:] if len(sys.argv) > 1 else DEFAULT_PATHS)
tools/mesa_build.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ MESA shard builder.
4
+
5
+ Takes the raw generator outputs and writes the released per-tier data files,
6
+ prepending the contamination canary to each one.
7
+
8
+ python3 generators/mesa_gen.py --n 250 --seed 20260809 --out procedural.jsonl
9
+ python3 generators/mesa_scieng.py --n 250 --seed 20260809 --out scieng.jsonl
10
+ python3 tools/mesa_build.py procedural.jsonl scieng.jsonl --out-dir data
11
+
12
+ Items keep the ids assigned at generation time, so rebuilding does not
13
+ renumber the released set.
14
+ """
15
+
16
+ import argparse
17
+ import collections
18
+ import json
19
+ import os
20
+ import sys
21
+
22
+ CANARY_FILE = os.path.join(os.path.dirname(__file__), "..", "canary.txt")
23
+ TIERS = (1, 2, 3)
24
+
25
+
26
+ def read_canary(path):
27
+ """First line of canary.txt is 'MESA-CANARY-GUID <guid>'."""
28
+ with open(path) as f:
29
+ line = f.readline().strip()
30
+ if not line.startswith("MESA-CANARY-GUID "):
31
+ sys.exit(f"{path}: first line is not a MESA-CANARY-GUID line")
32
+ return line
33
+
34
+
35
+ def main():
36
+ ap = argparse.ArgumentParser()
37
+ ap.add_argument("inputs", nargs="+", help="generator JSONL outputs")
38
+ ap.add_argument("--out-dir", default="data")
39
+ ap.add_argument("--combined-out", help="optional canary-free combined JSONL export")
40
+ ap.add_argument("--canary", default=CANARY_FILE)
41
+ a = ap.parse_args()
42
+
43
+ canary = read_canary(a.canary)
44
+
45
+ items = []
46
+ for path in a.inputs:
47
+ with open(path) as f:
48
+ items += [json.loads(l) for l in f if l.strip()]
49
+
50
+ ids = collections.Counter(it["id"] for it in items)
51
+ dupes = [i for i, n in ids.items() if n > 1]
52
+ if dupes:
53
+ sys.exit(f"duplicate ids across inputs: {dupes[:5]}")
54
+
55
+ stems = collections.Counter(it["stem"] for it in items)
56
+ repeated = [s for s, n in stems.items() if n > 1]
57
+ if repeated:
58
+ sys.exit(f"repeated stems across inputs: {repeated[:3]}")
59
+ for it in items:
60
+ choices = it["choices"]
61
+ if (len(choices) != 4 or len(set(choices)) != 4
62
+ or len(it["error_modes"]) != 4
63
+ or not isinstance(it["answer_idx"], int)
64
+ or not 0 <= it["answer_idx"] < 4
65
+ or it["error_modes"][it["answer_idx"]] != "correct"):
66
+ sys.exit(f"invalid choice set: {it['id']}")
67
+
68
+ os.makedirs(a.out_dir, exist_ok=True)
69
+ grid = collections.Counter()
70
+ for tier in TIERS:
71
+ rows = [it for it in items if it["tier"] == tier]
72
+ if not rows:
73
+ sys.exit(f"no items found for tier {tier}")
74
+ out = os.path.join(a.out_dir, f"mesa-{tier}.jsonl")
75
+ with open(out, "w") as f:
76
+ f.write(json.dumps({"id": f"canary-mesa-{tier}",
77
+ "canary": canary}) + "\n")
78
+ for it in rows:
79
+ f.write(json.dumps(it) + "\n")
80
+ print(f"wrote {len(rows):>5} items (+1 canary) to {out}")
81
+ for it in rows:
82
+ grid[(it["domain"], tier)] += 1
83
+
84
+ domains = sorted({d for d, _ in grid})
85
+ print(f"\n{'domain':<10}" + "".join(f"{'MESA-' + str(t):>9}" for t in TIERS)
86
+ + f"{'total':>9}")
87
+ for d in domains:
88
+ row = [grid[(d, t)] for t in TIERS]
89
+ print(f"{d:<10}" + "".join(f"{v:>9}" for v in row) + f"{sum(row):>9}")
90
+ col = [sum(grid[(d, t)] for d in domains) for t in TIERS]
91
+ print(f"{'TOTAL':<10}" + "".join(f"{v:>9}" for v in col) + f"{sum(col):>9}")
92
+
93
+ if a.combined_out:
94
+ with open(a.combined_out, "w") as f:
95
+ for it in items:
96
+ f.write(json.dumps(it) + "\n")
97
+ print(f"wrote {len(items)} canary-free items to {a.combined_out}")
98
+
99
+
100
+ if __name__ == "__main__":
101
+ main()
tools/mesa_mutate.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ MESA checker test.
4
+
5
+ mesa_verify.py confirms that each key is right. This confirms that mesa_verify
6
+ is actually looking: a checker that returns True for everything reports a clean
7
+ run and guarantees nothing.
8
+
9
+ For every verifiable item, point answer_idx at each distractor in turn and
10
+ require the checker to reject it. A family that scores well below 100% has a
11
+ checker too loose to trust -- and sometimes a real defect, because a distractor
12
+ the checker accepts may be a second correct answer. That is how the
13
+ wrong_person bug in the pronoun-case families was found.
14
+
15
+ python3 tools/mesa_mutate.py # defaults to ../data/*.jsonl
16
+ """
17
+
18
+ import collections
19
+ import importlib.util
20
+ import json
21
+ import os
22
+ import sys
23
+
24
+ HERE = os.path.dirname(os.path.abspath(__file__))
25
+ DEFAULT_PATHS = [os.path.join(HERE, "..", "data", f"mesa-{t}.jsonl")
26
+ for t in (1, 2, 3)]
27
+ FLOOR = 100.0 # every distractor must be rejected
28
+
29
+
30
+ def load_verifier():
31
+ spec = importlib.util.spec_from_file_location(
32
+ "mesa_verify", os.path.join(HERE, "mesa_verify.py"))
33
+ mod = importlib.util.module_from_spec(spec)
34
+ sys.modules["mesa_verify"] = mod
35
+ spec.loader.exec_module(mod)
36
+ return mod
37
+
38
+
39
+ def main(paths):
40
+ v = load_verifier()
41
+ items = v.load_items(paths)
42
+ caught = collections.Counter()
43
+ total = collections.Counter()
44
+
45
+ for it in items:
46
+ if v.check(it) is not True:
47
+ continue # unverifiable, or already failing
48
+ for j in range(len(it["choices"])):
49
+ if j == it["answer_idx"]:
50
+ continue
51
+ total[it["skill"]] += 1
52
+ try:
53
+ if v.check(dict(it, answer_idx=j)) is False:
54
+ caught[it["skill"]] += 1
55
+ except Exception:
56
+ caught[it["skill"]] += 1 # raising is a rejection
57
+
58
+ print(f"{'skill':<34}{'caught':>9}{'of':>7}{'rate':>8}")
59
+ print("-" * 58)
60
+ weak = []
61
+ for sk in sorted(total, key=lambda x: caught[x] / total[x]):
62
+ c, t = caught[sk], total[sk]
63
+ rate = 100.0 * c / t
64
+ flag = " <<<" if rate < FLOOR else ""
65
+ print(f"{sk:<34}{c:>9}{t:>7}{rate:>7.1f}%{flag}")
66
+ if rate < FLOOR:
67
+ weak.append((sk, rate))
68
+ tc, ta = sum(caught.values()), sum(total.values())
69
+ print("-" * 58)
70
+ print(f"{'TOTAL':<34}{tc:>9}{ta:>7}{100.0 * tc / ta:>7.1f}%")
71
+
72
+ if weak:
73
+ print(f"\nBELOW {FLOOR:.0f}% -- these checkers are too loose to trust, and a\n"
74
+ f"distractor they accept may be a second correct answer:")
75
+ for sk, rate in weak:
76
+ print(f" {sk}: {rate:.1f}%")
77
+ return 1
78
+ print(f"\nEvery checker rejects at least {FLOOR:.0f}% of wrong keys.")
79
+ return 0
80
+
81
+
82
+ if __name__ == "__main__":
83
+ sys.exit(main(sys.argv[1:] if len(sys.argv) > 1 else DEFAULT_PATHS))
mesa_verify.py → tools/mesa_verify.py RENAMED
@@ -54,9 +54,6 @@ def scale_by_fifths(tonic):
54
  """Major scale as the seven notes from IV up through vii on the circle
55
  of fifths -- an independent construction from chromatic offsets."""
56
  chain = [down_fifth(tonic)]
57
- for _ in range(6):
58
- chain.append(up_fifth(chain[-1]) if len(chain) == 1 else up_fifth(chain[-1]))
59
- chain = [down_fifth(tonic)]
60
  cur = tonic
61
  for _ in range(6):
62
  chain.append(cur)
@@ -82,6 +79,212 @@ def key_from(text, pat):
82
  return m.group(1) if m else None
83
 
84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  # ---------------------------------------------------------------- checkers
86
 
87
  def ck(cond):
@@ -90,6 +293,8 @@ def ck(cond):
90
 
91
  def check(it):
92
  s, k, key = it["stem"], it["skill"], it["choices"][it["answer_idx"]]
 
 
93
  def num(x):
94
  m = re.match(r"^\s*(-?\d+(?:/\d+)?(?:\.\d+)?)", str(x))
95
  return Fraction(m.group(1))
@@ -264,8 +469,34 @@ def check(it):
264
  return None
265
 
266
 
267
- def main(path):
268
- items = [json.loads(l) for l in open(path)]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
  res = collections.defaultdict(lambda: [0, 0, 0]) # ok, bad, unverified
270
  failures = []
271
  for it in items:
@@ -298,7 +529,11 @@ def main(path):
298
  print("\nFAIL", f["id"], f["skill"])
299
  print(" ", f["stem"].replace("\n", " / "))
300
  print(" key =", f["choices"][f["answer_idx"]], f.get("_err", ""))
 
 
301
 
 
 
302
 
303
  if __name__ == "__main__":
304
- main(sys.argv[1] if len(sys.argv) > 1 else "mesa_all.jsonl")
 
54
  """Major scale as the seven notes from IV up through vii on the circle
55
  of fifths -- an independent construction from chromatic offsets."""
56
  chain = [down_fifth(tonic)]
 
 
 
57
  cur = tonic
58
  for _ in range(6):
59
  chain.append(cur)
 
79
  return m.group(1) if m else None
80
 
81
 
82
+
83
+ # ---------------------------------------------------------------- English
84
+ #
85
+ # These families were previously marked UNVERIFIED and signed off by hand. That
86
+ # does not survive a regeneration: rewriting a generator produces new sentences
87
+ # that no one has read. The checks below re-derive each key from the STEM's
88
+ # syntax instead, so the guarantee holds for any future build.
89
+ #
90
+ # They deliberately test the AGREEMENT RELATION rather than consulting the
91
+ # generator's word lists -- a plural head requires a base-form verb whatever the
92
+ # verb is -- so a wrong lexicon in the generator cannot also pass the check.
93
+
94
+ SUBJ_PRON = {"I", "he", "she", "we", "they"}
95
+ OBJ_PRON = {"me", "him", "her", "us", "them"}
96
+ COP_SING = {"is", "was"}
97
+ COP_PLUR = {"are", "were"}
98
+ COP_PRES = {"is", "are"}
99
+ COP_PAST = {"was", "were"}
100
+ PAST_ADV = ("last term", "at the time", "back then", "that year")
101
+
102
+
103
+ def _tensed(stem):
104
+ """True if the stem carries a past-time adverbial."""
105
+ return any(a in stem for a in PAST_ADV)
106
+
107
+
108
+ def check_english(it):
109
+ s, k, key = it["stem"], it["skill"], it["choices"][it["answer_idx"]]
110
+
111
+ # ---- possessives: derivable entirely from the plural's spelling
112
+ if k in ("possessive_apostrophe", "irregular_possessive"):
113
+ m = re.search(r"belonging to the (\w+)\?", s)
114
+ if not m:
115
+ return None
116
+ plural = m.group(1)
117
+ thing = re.search(r"write the (\w+) belonging", s).group(1)
118
+ want = (f"the {plural}' {thing}" if plural.endswith("s")
119
+ else f"the {plural}'s {thing}")
120
+ return key == want
121
+
122
+ # ---- comparative / superlative / equative: the frame fixes the degree
123
+ if k in ("comparative_form", "superlative_form"):
124
+ if re.search(r"\bas ___ as\b", s):
125
+ degree = "positive"
126
+ elif re.search(r"of the two|between the two|compared with", s, re.I):
127
+ degree = "comparative"
128
+ else:
129
+ degree = "superlative"
130
+ if " " in key:
131
+ return False # "more X" / "most X" are never the key
132
+ if degree == "comparative":
133
+ return key.endswith("er")
134
+ if degree == "superlative":
135
+ return key.endswith("est")
136
+ # Positive degree. A suffix test is wrong here -- "clever" and "humble"
137
+ # are base adjectives that already end in -er/-le. Test structurally
138
+ # instead: the equative frame always carries the inflected forms as
139
+ # distractors, so the base form is a proper prefix of one of them.
140
+ stems = {key}
141
+ if key.endswith("y"):
142
+ stems.add(key[:-1] + "i") # lively -> livelier, wary -> warier
143
+ return any(o != key and len(o) > len(key)
144
+ and any(o.startswith(st) for st in stems)
145
+ for o in it["choices"])
146
+
147
+ # ---- subject-verb agreement: number of the HEAD noun, not the modifier
148
+ if k == "subject_verb_agreement":
149
+ m = re.search(r"The (\w+) of ", s)
150
+ if not m:
151
+ return None
152
+ plural_head = m.group(1).endswith("s")
153
+
154
+ # The frame picks the tense; the head picks the number. Both have to
155
+ # hold, so classify the frame first rather than inspecting the key.
156
+ if re.search(r"\bsince\b", s):
157
+ frame = "perfect"
158
+ elif re.search(r"last winter|that summer|until the move|for years", s):
159
+ frame = "past"
160
+ else:
161
+ frame = "present"
162
+
163
+ # The present-tense pair is identifiable without a verb lexicon: two
164
+ # single-word options X and X+"s".
165
+ singles = [o for o in it["choices"] if " " not in o]
166
+ present = {o for o in singles
167
+ if o + "s" in singles or (o.endswith("s") and o[:-1] in singles)}
168
+ part = None
169
+ for o in it["choices"]:
170
+ m2 = re.fullmatch(r"(?:has|have) (\w+)", o)
171
+ if m2:
172
+ part = m2.group(1)
173
+ break
174
+
175
+ if frame == "perfect":
176
+ if " " not in key:
177
+ return False
178
+ aux, rest = key.split(None, 1)
179
+ if aux not in ("has", "have"):
180
+ return False
181
+ return aux == ("have" if plural_head else "has") and \
182
+ (part is None or rest == part)
183
+
184
+ if " " in key:
185
+ return False # only a perfect frame takes an aux
186
+
187
+ if frame == "past":
188
+ if key in present:
189
+ return False # a present form in a past frame
190
+ # When only the base and past are among the selected options,
191
+ # `present` can be empty. Require past morphology explicitly.
192
+ return key.endswith("ed") or key in {"sat", "stood"}
193
+
194
+ # present: must be one of the two present forms, and agree with the head
195
+ if part is not None and key == part:
196
+ return False
197
+ if present and key not in present:
198
+ return False
199
+ return key.endswith("s") != plural_head
200
+
201
+ # ---- expletive "there", inverted locatives: agree with the real subject
202
+ if k in ("expletive_construction_agreement", "inverted_subject_agreement"):
203
+ if key not in COP_SING | COP_PLUR:
204
+ return False
205
+ tail = s.split("___", 1)[1]
206
+ singular = bool(re.search(r"\b(a|an|one|another|little)\b", tail))
207
+ num_ok = (key in COP_SING) == singular
208
+ return num_ok and ((key in COP_PAST) == _tensed(s))
209
+
210
+ # ---- quantifier agreement
211
+ if k == "indefinite_pronoun_agreement":
212
+ plural_q = bool(re.match(r".*\b(Both|All|Several|Many) of\b", s))
213
+ possession = bool(re.search(r"___ (?:a|an) ", s))
214
+ if key in ("has", "have", "had"):
215
+ if not possession:
216
+ return False
217
+ return key == "had" if _tensed(s) else \
218
+ key == ("have" if plural_q else "has")
219
+ if key in COP_SING | COP_PLUR:
220
+ if possession:
221
+ return False
222
+ return ((key in COP_PLUR) == plural_q) and \
223
+ ((key in COP_PAST) == _tensed(s))
224
+ return False
225
+
226
+ if k == "number_of_agreement":
227
+ plural = bool(re.search(r"\bA number of\b", s))
228
+ perfect = bool(re.search(
229
+ r"___ (?:risen|declined|remained|grown|arrived|responded|finished|volunteered)\b",
230
+ s))
231
+ if key in ("has", "have"):
232
+ return perfect and key == ("have" if plural else "has")
233
+ if key in COP_SING | COP_PLUR:
234
+ if perfect:
235
+ return False
236
+ return ((key in COP_PLUR) == plural) and \
237
+ ((key in COP_PAST) == _tensed(s))
238
+ return False
239
+
240
+ # ---- proximity: agrees with the NEARER conjunct
241
+ if k == "proximity_agreement":
242
+ m = re.search(r"nor the (\w+) ___", s)
243
+ if not m or key not in COP_SING | COP_PLUR:
244
+ return None
245
+ near_plural = m.group(1).endswith("s")
246
+ return ((key in COP_PLUR) == near_plural) and \
247
+ ((key in COP_PAST) == _tensed(s))
248
+
249
+ # ---- pronoun case: decided by the slot, not the person
250
+ if k == "pronoun_case_subject":
251
+ return key in SUBJ_PRON
252
+ if k == "pronoun_case_object":
253
+ return key in OBJ_PRON
254
+
255
+ # ---- who / whom / whose
256
+ if k in ("relative_pronoun_case", "embedded_relative_case"):
257
+ low = key.lower()
258
+ if low not in ("who", "whom", "whose"):
259
+ return False
260
+ if re.search(r"___ (coat|notes|signature|car)\b", s):
261
+ return low == "whose"
262
+ # "___ we believe <verb>" is a parenthetical: the relative pronoun is
263
+ # still the SUBJECT of the following verb, so it takes "who". Checking
264
+ # only for a following noun phrase would wrongly demand "whom" here.
265
+ if re.search(r"___ we believe ", s):
266
+ return low == "who"
267
+ # object position: after a preposition, in a fronted question, or with
268
+ # the embedded clause supplying its own subject
269
+ if re.search(r"To ___|___ did |\bto\.$|\bto\b\s*$", s) or \
270
+ re.search(r"___ (we|the panel|the director|everyone) \w+", s):
271
+ return low == "whom"
272
+ return low == "who"
273
+
274
+ # ---- subjunctive: bare base form
275
+ if k == "subjunctive_mood":
276
+ # In passive frames the bare auxiliary is "be". In active frames,
277
+ # identify the bare verb through its inflected or future counterpart;
278
+ # suffix-only checks mistakenly accept irregular past forms like
279
+ # "withdrew".
280
+ if re.search(r"___ (?:revised|postponed|withdrawn|reconsidered)\.", s):
281
+ return key == "be"
282
+ return any(option in (key + "s", "will " + key)
283
+ for option in it["choices"] if option != key)
284
+
285
+ return None
286
+
287
+
288
  # ---------------------------------------------------------------- checkers
289
 
290
  def ck(cond):
 
293
 
294
  def check(it):
295
  s, k, key = it["stem"], it["skill"], it["choices"][it["answer_idx"]]
296
+ if it["domain"] == "English":
297
+ return check_english(it)
298
  def num(x):
299
  m = re.match(r"^\s*(-?\d+(?:/\d+)?(?:\.\d+)?)", str(x))
300
  return Fraction(m.group(1))
 
469
  return None
470
 
471
 
472
+ def load_items(paths):
473
+ """Read one or more MESA JSONL files, skipping contamination canary rows.
474
+
475
+ The canary is the first record of every shipped data file and carries no
476
+ stem or skill, so it must be dropped before anything indexes those fields.
477
+ """
478
+ if isinstance(paths, str):
479
+ paths = [paths]
480
+ items, canaries = [], 0
481
+ for path in paths:
482
+ with open(path) as f:
483
+ for line in f:
484
+ if not line.strip():
485
+ continue
486
+ rec = json.loads(line)
487
+ if "canary" in rec or "stem" not in rec:
488
+ canaries += 1
489
+ continue
490
+ items.append(rec)
491
+ if canaries:
492
+ print(f"(skipped {canaries} canary record(s))\n")
493
+ return items
494
+
495
+
496
+ def main(paths):
497
+ items = load_items(paths)
498
+ if not items:
499
+ sys.exit("no items found -- check the path(s) given")
500
  res = collections.defaultdict(lambda: [0, 0, 0]) # ok, bad, unverified
501
  failures = []
502
  for it in items:
 
529
  print("\nFAIL", f["id"], f["skill"])
530
  print(" ", f["stem"].replace("\n", " / "))
531
  print(" key =", f["choices"][f["answer_idx"]], f.get("_err", ""))
532
+ return 1 if tot_bad else 0
533
+
534
 
535
+ DEFAULT_PATHS = ["../data/mesa-1.jsonl", "../data/mesa-2.jsonl",
536
+ "../data/mesa-3.jsonl"]
537
 
538
  if __name__ == "__main__":
539
+ sys.exit(main(sys.argv[1:] if len(sys.argv) > 1 else DEFAULT_PATHS))
utils.py DELETED
@@ -1,19 +0,0 @@
1
- """Document filters for the MESA task tree.
2
-
3
- Each tier lives in its own dataset config, so a leaf task loads only its tier
4
- and filters by domain here.
5
- """
6
-
7
- import datasets
8
-
9
-
10
- def _by_domain(domain):
11
- def fn(dataset: datasets.Dataset) -> datasets.Dataset:
12
- return dataset.filter(lambda d: d.get("domain") == domain)
13
- return fn
14
-
15
-
16
- filter_math = _by_domain("Math")
17
- filter_english = _by_domain("English")
18
- filter_science = _by_domain("Science")
19
- filter_art = _by_domain("Art")