File size: 32,450 Bytes
32030e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
"""Reward, data and evaluation helpers for GRPO runs on the EJBench training set
(notebooks/dummy_grpo_qwen9b.ipynb).

Training-only: nothing here is used by the benchmark build or by run_model.py, and the rewarder refuses
any task that is not from ``training_v01`` (splits ``train`` and ``train_val``).

Reward
------
The benchmark scores the three single-turn families all or nothing, which gives GRPO almost no signal
where the base model rarely succeeds (Qwen 9B solved 0/16 campaign tasks in the dev pilot). The default
reward follows Surge AI's rubric-rewarded RL on Kimi-K2.7 (September 2026): a dense reward equal to the
fraction of atomic criteria satisfied. Our criteria are checked by the benchmark's own scorer, not an LLM
grader. One criterion per item:

| family | criteria |
|---|---|
| campaign_reconstruction | each link, the misfiled sheet, each sign-off verdict |
| duty_signoff, evidence_signoff | each temperature verdict, each pressure verdict |
| operating_envelope | the ranking (exact), each regime label |

``mode="weighted"`` is the alternative tried first: chance-corrected parts weighted by how hard each item
is to guess (items x log2(1 / chance)), plus ``full_weight`` x the benchmark score. Uniform guessing earns
about 0 under it. It is kept for comparison runs.

A reply with no final answer (cut off at the length limit, still inside its thinking, or with no JSON
object) earns ``no_answer`` (default 0, the same as every criterion missed). Cut-off replies are also
masked out of the loss by the trainer (``mask_truncated_completions``), as Surge drop truncated samples.

With thinking on, Qwen writes ``<think> ... </think>`` and then the answer; only the text after the last
``</think>`` is scored, as the vLLM reasoning parser does when the benchmark is run.

Numeric estimates (optional, off by default)
--------------------------------------------
A pass/fail verdict is right half the time by guessing, so within a group of replies a lucky guess earns
the same as a reasoned answer. Every training task also stores the numbers its verdicts come from, so a
training prompt can ask for them as well (``estimate_messages``; ``prompt_rows(..., estimate_share=0.5)``
asks in about half the rows and leaves the rest as the benchmark prompt). The reply then carries an
``"estimates"`` object, scored item by item by how close each number is:

| family | estimates per duty |
|---|---|
| campaign_reconstruction | ``rise_K`` |
| duty_signoff | ``rise_K``, ``dP_kPa`` |
| operating_envelope | ``rise_K``, ``ambient_ratio`` |

``rise_K`` is the peak cell rise above that duty's coolant inlet, the quantity the prompts quote. An item
scores 1 within its tolerance and falls linearly to 0 at five tolerances: rise ``max(0.5 K, 10%)`` (the
benchmark's ``dT_scale``), pressure drop 10% of the true value, ambient ratio ``max(0.1, 10%)``. So a rise
or pressure drop 50% out scores 0. With ``numeric_weight`` w the reward becomes ``(1 - w) x criteria reward
+ w x estimate score`` on rows that asked; other rows are unchanged. ``estimate_alignment`` checks, on base
model replies, whether better numbers go with better verdicts before the weight is turned on.
"""

from __future__ import annotations

import csv
import hashlib
import json
import math
import random
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any, Iterable

from ejbench_eval.parsing import extract_json
from ejbench_eval.prompting import single_turn_messages
from ejbench_eval.scoring import dT_scale, score_task

TRAINING_SPLITS = frozenset({"train", "train_val"})
SINGLE_TURN = ("campaign_reconstruction", "duty_signoff", "operating_envelope")
MODES = ("criteria", "weighted")
REGIME_CHOICES = 3
THINK_END = "</think>"

ESTIMATES = {"campaign_reconstruction": ("rise_K",),
             "duty_signoff": ("rise_K", "dP_kPa"),
             "operating_envelope": ("rise_K", "ambient_ratio")}
ESTIMATE_MEANING = {
    "rise_K": "peak cell rise above that duty's own coolant inlet, in K",
    "dP_kPa": "coolant pressure drop, in kPa",
    "ambient_ratio": ("net heat gained from the surroundings as a fraction of the pack's own heat generation "
                      "(negative when the pack loses heat to the surroundings)"),
}
ESTIMATE_ZERO_AT = 5.0   # an estimate scores 0 at this many tolerances out


# ── Reward ───────────────────────────────────────────────────────────────────────────────────

def part_chances(task: dict) -> dict[str, tuple[float, int]]:
    """Chance of guessing one item right, and the number of items (criteria), for each scored part."""
    family, answer = task["family"], task["answer"]
    if family == "campaign_reconstruction":
        sheets = len(answer["links"]) + 1
        return {"links": (1 / sheets, len(answer["links"])), "misfiled": (1 / sheets, 1),
                "signoff": (0.5, len(answer["signoff"]))}
    if family in ("duty_signoff", "evidence_signoff"):
        return {"temperature": (0.5, len(answer["temperature"])), "pressure": (0.5, len(answer["pressure"]))}
    if family == "operating_envelope":
        return {"ranking": (1 / math.factorial(len(answer["ranking"])), 1),
                "regimes": (1 / REGIME_CHOICES, len(answer["regimes"]))}
    raise ValueError(f"no training reward for family {family}")


def criteria_fraction(task: dict, parts: dict[str, float]) -> float:
    """Fraction of atomic criteria satisfied (each part's score is the fraction of its items right)."""
    items = {name: n for name, (_, n) in part_chances(task).items()}
    return sum(n * parts.get(name, 0.0) for name, n in items.items()) / sum(items.values())


def weighted_partial(task: dict, parts: dict[str, float]) -> float:
    """Information-weighted mean of chance-corrected parts: about 0 for guessing, 1 when all right."""
    total = weights = 0.0
    for name, (chance, items) in part_chances(task).items():
        weight = items * math.log2(1 / chance)
        total += weight * (parts.get(name, 0.0) - chance) / (1 - chance)
        weights += weight
    return total / weights


def final_answer_text(text: str, thinking: bool = True) -> str | None:
    """The text after the reasoning, or None if the reply never left it.

    With thinking on, the chat template opens ``<think>`` in the prompt, so a completion holds only
    the closing tag. No closing tag means the reply was cut off inside its reasoning. If the decoder
    dropped the tags altogether (``thinking`` False), the whole text is used and the last JSON object
    in it is taken as the answer.
    """
    if THINK_END in text:
        return text.rsplit(THINK_END, 1)[1]
    return None if thinking else text


def final_answer(text: str, thinking: bool = True, truncated: bool = False) -> dict | None:
    """The reply's final JSON answer, or None when it was cut off or never gave one."""
    answer_text = None if truncated else final_answer_text(text, thinking)
    return extract_json(answer_text) if answer_text else None


def reward_parts(task: dict, text: str, *, thinking: bool = True, truncated: bool = False,
                 mode: str = "criteria", full_weight: float = 0.0, no_answer: float = 0.0,
                 estimates: bool = False, numeric_weight: float = 0.0) -> dict:
    """Reward of one completion, with the pieces it was built from (for logging).

    ``estimates`` says the prompt asked for numeric estimates; only then does ``numeric_weight`` apply.
    """
    if mode not in MODES:
        raise ValueError(f"mode must be one of {MODES}")
    answer = final_answer(text, thinking, truncated)
    if answer is None:
        return {"reward": no_answer, "score": 0.0, "criteria": 0.0, "answered": False, "estimates": None}
    result = score_task(task, answer)
    criteria = criteria_fraction(task, result["parts"])
    dense = criteria if mode == "criteria" else weighted_partial(task, result["parts"])
    reward = (1 - full_weight) * dense + full_weight * result["score"]
    numbers = estimate_score(task, answer) if estimates else None
    if numbers is not None and numeric_weight:
        reward = (1 - numeric_weight) * reward + numeric_weight * numbers
    return {"reward": reward, "score": result["score"], "criteria": criteria, "answered": True,
            "estimates": numbers}


# ── Numeric estimates ────────────────────────────────────────────────────────────────────────

def estimate_fields(task: dict) -> dict[str, list[str]]:
    """Estimated quantities for a task and the duty labels each one is asked for."""
    return {field: sorted(task["answer"][field]) for field in ESTIMATES.get(task["family"], ())}


def estimate_instruction(task: dict) -> str:
    fields = estimate_fields(task)
    shape = {field: {label: "number" for label in labels} for field, labels in fields.items()}
    meaning = "; ".join(f"{field} is the {ESTIMATE_MEANING[field]}" for field in fields)
    return ('Also add an "estimates" field to that JSON object, shaped ' + json.dumps(shape)
            + f", with your best single-number estimate for each duty: {meaning}.")


def estimate_messages(task: dict) -> list[dict]:
    """The benchmark's single-turn messages with a request for numeric estimates added at the end."""
    messages = single_turn_messages(task)
    last = messages[-1]
    return messages[:-1] + [{**last, "content": last["content"] + "\n\n" + estimate_instruction(task)}]


def _number(value) -> float | None:
    if isinstance(value, bool):
        return None
    try:
        number = float(value)
    except (TypeError, ValueError):
        return None
    return number if math.isfinite(number) else None


def estimate_tolerance(field: str, truth: float) -> float:
    if field == "rise_K":
        return dT_scale(truth)                    # max(0.5 K, 10%), the benchmark's own temperature scale
    if field == "dP_kPa":
        return 0.10 * abs(truth)
    return max(0.10, 0.10 * abs(truth))


def estimate_closeness(field: str, predicted, truth: float) -> float:
    """1 within the tolerance, falling linearly to 0 at ``ESTIMATE_ZERO_AT`` tolerances out."""
    value = _number(predicted)
    if value is None or (field == "dP_kPa" and value <= 0):
        return 0.0
    tolerance = estimate_tolerance(field, truth)
    error = abs(value - truth)
    if error <= tolerance:
        return 1.0
    return max(0.0, 1.0 - (error - tolerance) / ((ESTIMATE_ZERO_AT - 1) * tolerance))


def _estimates_block(answer: dict | None) -> dict:
    block = answer.get("estimates") if isinstance(answer, dict) else None
    return block if isinstance(block, dict) else {}


def estimate_parts(task: dict, answer: dict | None) -> dict[str, float]:
    """Mean closeness per estimated quantity; a missing number counts as 0."""
    block, truth = _estimates_block(answer), task["answer"]
    parts = {}
    for field, labels in estimate_fields(task).items():
        given = block.get(field) if isinstance(block.get(field), dict) else {}
        parts[field] = sum(estimate_closeness(field, given.get(k), truth[field][k]) for k in labels) / len(labels)
    return parts


def estimate_score(task: dict, answer: dict | None) -> float | None:
    """Item-weighted mean closeness of all estimates, or None for a family without estimates."""
    fields = estimate_fields(task)
    if not fields:
        return None
    parts = estimate_parts(task, answer)
    items = {field: len(labels) for field, labels in fields.items()}
    return sum(items[f] * parts[f] for f in items) / sum(items.values())


def regime_from_ratio(ratio: float) -> str:
    """The prompts' heat-balance regimes from the net ambient gain / own heat generation ratio."""
    if ratio > 1.0:
        return "ambient_gain"
    if ratio > 0.25:
        return "mixed"
    return "own_heat" if ratio >= -0.25 else "ambient_loss"


def implied_answer(task: dict, numbers: dict[str, dict]) -> dict | None:
    """The verdicts, ranking or regimes that follow from a set of estimates, in the benchmark's answer
    shape; None when a number is missing. Inlets are recovered from the stored answer (peak - rise)."""
    truth = task["answer"]
    fields = estimate_fields(task)
    values = {}
    for field, labels in fields.items():
        given = numbers.get(field) if isinstance(numbers.get(field), dict) else {}
        values[field] = {k: _number(given.get(k)) for k in labels}
        if any(v is None for v in values[field].values()):
            return None
    if not fields:
        return None
    family = task["family"]
    peak = lambda k: truth["peak_C"][k] - truth["rise_K"][k] + values["rise_K"][k]  # noqa: E731
    verdict = lambda ok: "pass" if ok else "fail"  # noqa: E731
    if family == "campaign_reconstruction":
        return {"signoff": {k: verdict(peak(k) <= truth["limits_C"][k]) for k in fields["rise_K"]}}
    if family == "duty_signoff":
        return {"temperature": {k: verdict(peak(k) <= truth["limits_C"][k]) for k in fields["rise_K"]},
                "pressure": {k: verdict(values["dP_kPa"][k] <= truth["pressure_limits_kPa"][k])
                             for k in fields["dP_kPa"]}}
    return {"ranking": sorted(fields["rise_K"], key=lambda k: -values["rise_K"][k]),
            "regimes": {k: regime_from_ratio(values["ambient_ratio"][k]) for k in fields["ambient_ratio"]}}


def estimate_alignment(pairs: Iterable[tuple[dict, dict | None]]) -> dict:
    """Do better numbers go with better answers? ``pairs`` are (task, final answer) from replies that
    were asked for estimates. Per family:

    - ``estimate_score``: mean closeness of the numbers;
    - ``criteria_low_half`` / ``criteria_high_half``: criteria fraction of replies with estimate scores
      below / at or above the family median (a clear rise means the numbers track the answers);
    - ``follows_own_numbers``: share of stated verdicts / regimes / rankings that match what its own
      numbers imply;
    - ``criteria_stated`` / ``criteria_from_numbers``: the criteria fraction as answered, and if those
      parts had been taken from its own numbers instead.
    """
    by_family: dict[str, list[dict]] = defaultdict(list)
    for task, answer in pairs:
        if answer is None or task["family"] not in ESTIMATES:
            continue
        stated = score_task(task, answer)["parts"]
        row = {"estimate": estimate_score(task, answer), "criteria": criteria_fraction(task, stated)}
        implied = implied_answer(task, _estimates_block(answer))
        if implied is not None:
            checks = [str(_lookup(answer, part, key)).strip().lower() == str(value).lower()
                      for part, labels in implied.items() if part != "ranking" for key, value in labels.items()]
            if "ranking" in implied:
                shown = answer.get("ranking")
                checks.append(isinstance(shown, list) and [str(x).strip().upper() for x in shown] == implied["ranking"])
            row["follows"] = sum(checks) / len(checks)
            row["criteria_from_numbers"] = criteria_fraction(task, score_task(task, {**answer, **implied})["parts"])
        by_family[task["family"]].append(row)
    out = {}
    for family, rows in sorted(by_family.items()):
        ordered = sorted(rows, key=lambda r: r["estimate"])
        median = ordered[len(ordered) // 2]["estimate"]
        low = [r["criteria"] for r in rows if r["estimate"] < median]
        high = [r["criteria"] for r in rows if r["estimate"] >= median]
        implied_rows = [r for r in rows if "follows" in r]
        mean = lambda xs: round(sum(xs) / len(xs), 3) if xs else None  # noqa: E731
        out[family] = {"replies": len(rows), "estimate_score": mean([r["estimate"] for r in rows]),
                       "criteria_low_half": mean(low), "criteria_high_half": mean(high),
                       "with_every_number": len(implied_rows),
                       "follows_own_numbers": mean([r["follows"] for r in implied_rows]),
                       "criteria_stated": mean([r["criteria"] for r in implied_rows]),
                       "criteria_from_numbers": mean([r["criteria_from_numbers"] for r in implied_rows])}
    return out


def _lookup(answer: dict, part: str, key: str):
    block = answer.get(part)
    return block.get(key) if isinstance(block, dict) else None


def completion_text(completion: Any) -> str:
    """TRL passes strings, or lists of chat messages for conversational datasets."""
    if isinstance(completion, str):
        return completion
    if isinstance(completion, list) and completion and isinstance(completion[-1], dict):
        return str(completion[-1].get("content") or "")
    return str(completion)


class PartialCreditReward:
    """TRL reward function: ``reward_funcs=[PartialCreditReward(tasks, max_completion_length)]``.

    The dataset needs a ``task_id`` column, and an ``estimates`` column (from ``prompt_rows``) when
    ``numeric_weight`` is used. A completion whose token count reaches ``max_completion_length`` counts
    as cut off, whatever its text.
    """

    __name__ = "ejbench_criteria"

    def __init__(self, tasks: Iterable[dict], max_completion_length: int | None = None, thinking: bool = True,
                 mode: str = "criteria", full_weight: float = 0.0, no_answer: float = 0.0,
                 numeric_weight: float = 0.0):
        tasks = list(tasks)
        bad = sorted({task.get("split") for task in tasks} - TRAINING_SPLITS)
        if bad:
            raise ValueError(f"Rewards are for training_v01 tasks only; got splits {bad}")
        self.tasks = {task["task_id"]: task for task in tasks if task["family"] in SINGLE_TURN}
        self.max_completion_length, self.thinking = max_completion_length, thinking
        self.options = {"mode": mode, "full_weight": full_weight, "no_answer": no_answer,
                        "numeric_weight": numeric_weight}
        self.history: list[dict] = []

    def __call__(self, completions: list, task_id: list[str], completion_ids: list | None = None,
                 estimates: list | None = None, **_: Any) -> list[float]:
        rewards = []
        for i, (completion, tid) in enumerate(zip(completions, task_id)):
            truncated = bool(self.max_completion_length and completion_ids is not None
                             and len(completion_ids[i]) >= self.max_completion_length)
            task = self.tasks[tid]
            asked = bool(estimates[i]) if estimates is not None else False
            parts = reward_parts(task, completion_text(completion), thinking=self.thinking, truncated=truncated,
                                 estimates=asked, **self.options)
            self.history.append({"task_id": tid, "family": task["family"], "truncated": truncated,
                                 "asked_estimates": asked,
                                 **{k: parts[k] for k in ("reward", "score", "criteria", "answered", "estimates")}})
            rewards.append(float(parts["reward"]))
        return rewards


# ── Data ─────────────────────────────────────────────────────────────────────────────────────

def training_tasks(tasks: Iterable[dict]) -> list[dict]:
    """Single-turn training tasks with answers; refuses anything outside training_v01."""
    tasks = list(tasks)
    bad = sorted({task.get("split") for task in tasks} - TRAINING_SPLITS)
    if bad:
        raise ValueError(f"Only training_v01 tasks may be trained on; got splits {bad}")
    return [t for t in tasks if t["family"] in SINGLE_TURN and t["interaction"] == "single_turn"
            and t.get("answer") is not None]


def prompt_rows(tasks: Iterable[dict], estimate_share: float = 0.0, seed: int = 0) -> list[dict]:
    """One row per task: the exact chat messages run_model.py sends, plus the ids the reward needs.

    With ``estimate_share`` > 0, about that share of rows (chosen by a stable hash of seed, row and task)
    ask for numeric estimates as well, and carry ``estimates=True`` for the reward.
    """
    rows = []
    for i, task in enumerate(tasks):
        draw = int(hashlib.sha1(f"{seed}:{i}:{task['task_id']}".encode()).hexdigest()[:8], 16) / 16 ** 8
        asked = task["family"] in ESTIMATES and draw < estimate_share
        rows.append({"prompt": estimate_messages(task) if asked else single_turn_messages(task),
                     "task_id": task["task_id"], "family": task["family"],
                     "training_format": task["tags"].get("training_format"),
                     "quick_right": bool(task["tags"].get("quick_right")), "estimates": asked})
    return rows


def stable_order(task_ids: Iterable[str], seed: int) -> list[str]:
    return sorted(task_ids, key=lambda tid: hashlib.sha1(f"{seed}:{tid}".encode()).hexdigest())


# The recommended fine-tuning subset (agreed 2026-11-09): single-turn, no task a quick method also
# solves, and at most this many tasks per design and training format. Near-copies of one design add
# little, and sign-off is a training-only stand-in, so it gets one per design.
RECOMMENDED_CAPS = {"campaign_reconstruction": 3, "operating_envelope": 3, "duty_signoff": 1}
SELECTION_SEED = 20261109


def recommended_subset(tasks: Iterable[dict], caps: dict[str, int] | None = None, *,
                       drop_quick_right: bool = True, seed: int = SELECTION_SEED) -> list[dict]:
    """The recommended training subset of ``training_v01`` tasks, in task-ID order.

    Keeps single-turn tasks of the families in ``caps``; drops ``tags.quick_right`` tasks unless
    ``drop_quick_right`` is False; then keeps at most ``caps[family]`` tasks per design and
    ``tags.training_format``, chosen in a seeded order. Refuses benchmark tasks, like ``training_tasks``.
    """
    caps = RECOMMENDED_CAPS if caps is None else caps
    pool = {t["task_id"]: t for t in training_tasks(tasks) if t["family"] in caps
            and not (drop_quick_right and t["tags"].get("quick_right"))}
    seen: Counter = Counter()
    picked = []
    for tid in stable_order(pool, seed):
        task = pool[tid]
        key = (task["provenance"]["geometry_ids"][0], task["tags"].get("training_format") or task["family"])
        if seen[key] < caps[task["family"]]:
            seen[key] += 1
            picked.append(task)
    return sorted(picked, key=lambda task: task["task_id"])


def scaling_subset(tasks: Iterable[dict], fraction: float, seed: int = SELECTION_SEED) -> list[dict]:
    """A share of ``tasks`` for the data-scaling runs, in task-ID order.

    Stratified by family: each family keeps ``fraction`` of its tasks (rounded half up, at least one),
    so the family mix matches the full set. Nested: within a family, tasks are taken in one seeded
    order, so the 25% subset sits inside the 50% subset, which sits inside the full set.
    """
    if not 0 < fraction <= 1:
        raise ValueError(f"fraction must be in (0, 1], got {fraction}")
    by_family: dict[str, dict[str, dict]] = defaultdict(dict)
    for task in tasks:
        by_family[task["family"]][task["task_id"]] = task
    picked = []
    for family in sorted(by_family):
        pool = by_family[family]
        keep = max(1, math.floor(fraction * len(pool) + 0.5))
        picked.extend(pool[tid] for tid in stable_order(pool, seed)[:keep])
    return sorted(picked, key=lambda task: task["task_id"])


def pick_profile_tasks(tasks: list[dict], n: int, seed: int = 0) -> list[dict]:
    """``n`` tasks for the pass-rate check, spread evenly over training formats where they allow."""
    by_format: dict[str, list[dict]] = defaultdict(list)
    lookup = {task["task_id"]: task for task in tasks}
    for tid in stable_order(lookup, seed):
        by_format[lookup[tid]["tags"].get("training_format") or lookup[tid]["family"]].append(lookup[tid])
    picked: list[dict] = []
    while len(picked) < n and any(by_format.values()):
        for name in sorted(by_format):
            if by_format[name] and len(picked) < n:
                picked.append(by_format[name].pop(0))
    return picked


def select_learnable(profile: list[dict], tasks: list[dict], *, min_spread: float = 1e-6,
                     max_quick_share: float = 0.3, seed: int = 0) -> list[dict]:
    """Tasks worth training on, from a pass-rate profile.

    ``profile`` has one row per sampled completion: ``task_id`` and ``reward``. A task is kept when its
    rewards differ between samples (GRPO learns nothing from a group that all scored the same). Tasks a
    quick method also gets right (``tags.quick_right``) are capped at ``max_quick_share`` of the result,
    so the run does not mostly reward the shortcut.
    """
    rewards: dict[str, list[float]] = defaultdict(list)
    for row in profile:
        rewards[row["task_id"]].append(float(row["reward"]))
    lookup = {task["task_id"]: task for task in tasks}
    varied = [tid for tid in stable_order(rewards, seed)
              if tid in lookup and len(rewards[tid]) > 1 and max(rewards[tid]) - min(rewards[tid]) > min_spread]
    slow = [tid for tid in varied if not lookup[tid]["tags"].get("quick_right")]
    quick = [tid for tid in varied if lookup[tid]["tags"].get("quick_right")]
    cap = int(max_quick_share * len(slow) / (1 - max_quick_share)) if max_quick_share < 1 else len(quick)
    return [lookup[tid] for tid in slow + quick[:cap]]


def family_balanced(tasks: list[dict], seed: int = 0) -> list[dict]:
    """Repeat tasks so each family appears equally often (Surge balance their training tasks by domain).

    Each family is cycled up to the size of the largest one, in a stable random order, so no family's
    tasks are dropped and the smaller families are revisited more often.
    """
    by_family: dict[str, list[dict]] = defaultdict(list)
    for task in tasks:
        by_family[task["family"]].append(task)
    if not by_family:
        return []
    target = max(len(pool) for pool in by_family.values())
    rng = random.Random(seed)
    out = []
    for family in sorted(by_family):
        pool = sorted(by_family[family], key=lambda t: t["task_id"])
        rng.shuffle(pool)
        out.extend(pool[i % len(pool)] for i in range(target))
    return out


def profile_summary(profile: list[dict], tasks: list[dict]) -> dict:
    """Mean reward, criteria fraction, full-score rate and answered rate per training format."""
    lookup = {task["task_id"]: task for task in tasks}
    groups: dict[str, list[dict]] = defaultdict(list)
    for row in profile:
        task = lookup[row["task_id"]]
        groups[task["tags"].get("training_format") or task["family"]].append(row)
    return {name: {"samples": len(rows), "mean_reward": round(sum(r["reward"] for r in rows) / len(rows), 3),
                   "criteria": round(sum(r["criteria"] for r in rows) / len(rows), 3),
                   "full_score_rate": round(sum(r["score"] for r in rows) / len(rows), 3),
                   "answered_rate": round(sum(bool(r["answered"]) for r in rows) / len(rows), 3)}
            for name, rows in sorted(groups.items())}


def write_task_set(tasks: list[dict], path: Path, split: str) -> Path:
    """A task-set CSV that run_model.py --task-set accepts."""
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", newline="") as handle:
        writer = csv.writer(handle)
        writer.writerow(["split", "family", "task_id"])
        writer.writerows([split, task["family"], task["task_id"]] for task in tasks)
    return path


def balanced_sample(tasks: list[dict], per_family: int, seed: int = 0) -> list[dict]:
    """Up to ``per_family`` tasks from each family, in a stable random order."""
    rng = random.Random(seed)
    by_family: dict[str, list[dict]] = defaultdict(list)
    for task in sorted(tasks, key=lambda t: t["task_id"]):
        by_family[task["family"]].append(task)
    picked = []
    for family in sorted(by_family):
        pool = by_family[family]
        rng.shuffle(pool)
        picked.extend(pool[:per_family])
    return picked


def family_counts(tasks: Iterable[dict]) -> dict[str, int]:
    return dict(Counter(task["family"] for task in tasks))


# ── Evaluation (Surge's reporting: pass rate, criteria rate, paired counts and tests) ───────

def record_criteria(task: dict, record: dict) -> float:
    """Criteria fraction of one run_model.py record; a failed or unparsed reply counts as 0."""
    parts = record.get("parts") or {}
    if record.get("score") is None or "format" in parts:
        return 0.0
    return criteria_fraction(task, parts)


def mcnemar_exact(base_only: int, trained_only: int) -> float:
    """Two-sided exact McNemar p-value from the discordant pair counts."""
    n = base_only + trained_only
    if n == 0:
        return 1.0
    k = min(base_only, trained_only)
    tail = sum(math.comb(n, i) for i in range(k + 1)) / 2 ** n
    return min(1.0, 2 * tail)


def compare_runs(tasks: dict[str, dict], base: list[dict], trained: list[dict], seed: int = 0) -> dict:
    """Base against trained, each one or more runs (``sample`` 0..k-1), paired by task.

    Reported as in Surge's Kimi-K2.7 write-up: full-task pass rate (averaged over runs), the mean
    criteria pass rate, tasks improved / regressed / tied on the per-task criteria rate (mean over each
    model's runs), an exact McNemar test on full passes for each trained run (against the base run with
    the same number, or base run 0 when base ran once), a Wilcoxon signed-rank test on the criteria
    rate, and a paired bootstrap 95% interval on the change. Surge ran base once; running it as many
    times as the trained model makes the per-task comparison less noisy.
    """
    def by_run(records):
        runs: dict[int, dict[str, dict]] = defaultdict(dict)
        for r in records:
            runs[int(r.get("sample", 0))][r["task_id"]] = r
        return runs

    base_runs, runs = by_run(base), by_run(trained)
    ids = sorted(tid for tid in tasks if all(tid in run for run in list(base_runs.values()) + list(runs.values())))
    full = lambda r: float((r.get("score") or 0.0) == 1.0)  # noqa: E731
    mean_crit = lambda rs, t: sum(record_criteria(tasks[t], run[t]) for run in rs.values()) / len(rs)  # noqa: E731
    base_crit = [mean_crit(base_runs, t) for t in ids]
    trained_crit = [mean_crit(runs, t) for t in ids]
    diffs = [b - a for a, b in zip(base_crit, trained_crit)]
    base_full_rate = sum(full(run[t]) for run in base_runs.values() for t in ids) / (len(ids) * len(base_runs))
    per_run = {}
    for k, run in sorted(runs.items()):
        paired = base_runs.get(k, base_runs[min(base_runs)])
        base_full = [full(paired[t]) for t in ids]
        tr_full = [full(run[t]) for t in ids]
        b_only = sum(a == 1 and b == 0 for a, b in zip(base_full, tr_full))
        t_only = sum(a == 0 and b == 1 for a, b in zip(base_full, tr_full))
        per_run[k] = {"full_pass": sum(tr_full) / len(ids), "mcnemar_p": round(mcnemar_exact(b_only, t_only), 4)}
    rng = random.Random(seed)
    boots = sorted(sum(rng.choices(diffs, k=len(diffs))) / len(diffs) for _ in range(5000))
    try:
        from scipy.stats import wilcoxon
        wilcoxon_p = float(wilcoxon(diffs).pvalue) if any(diffs) else 1.0
    except ImportError:  # pragma: no cover
        wilcoxon_p = None
    return {"tasks": len(ids), "base_runs": len(base_runs), "trained_runs": len(runs),
            "full_pass": {"base": round(base_full_rate, 3),
                          "trained": round(sum(v["full_pass"] for v in per_run.values()) / len(per_run), 3)},
            "criteria": {"base": round(sum(base_crit) / len(ids), 3), "trained": round(sum(trained_crit) / len(ids), 3)},
            "improved_regressed_tied": [sum(d > 1e-9 for d in diffs), sum(d < -1e-9 for d in diffs),
                                        sum(abs(d) <= 1e-9 for d in diffs)],
            "criteria_change_95ci": [round(boots[125], 3), round(boots[4874], 3)],
            "wilcoxon_p": None if wilcoxon_p is None else round(wilcoxon_p, 4),
            "per_run": per_run}