jgeuter commited on
Commit
47cbcda
·
verified ·
1 Parent(s): 2ee6131

OpenDecisions 1.0: 2,352 decisions (long logs removed), dataset card, scorer and letter readout

Browse files
Files changed (4) hide show
  1. README.md +191 -0
  2. opendecisions.jsonl +0 -0
  3. predict_letters.py +110 -0
  4. score.py +218 -0
README.md ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-sa-4.0
3
+ pretty_name: OpenDecisions
4
+ language:
5
+ - en
6
+ - pl
7
+ - pt
8
+ - es
9
+ - de
10
+ - ja
11
+ - da
12
+ - it
13
+ - fr
14
+ - hi
15
+ - ar
16
+ - zh
17
+ - ko
18
+ - uk
19
+ - el
20
+ - tr
21
+ - nl
22
+ - cs
23
+ - fi
24
+ - 'no'
25
+ - sv
26
+ - id
27
+ task_categories:
28
+ - multiple-choice
29
+ - text-classification
30
+ tags:
31
+ - decision-model
32
+ - jev
33
+ - jevbench
34
+ - calibration
35
+ - evaluation
36
+ size_categories:
37
+ - 1K<n<10K
38
+ configs:
39
+ - config_name: default
40
+ data_files: opendecisions.jsonl
41
+ ---
42
+
43
+ # OpenDecisions
44
+
45
+ OpenDecisions (version 1.0) is a validation set of 2,352 Jev-style decisions: a state, a typed question and its options. A decision
46
+ model returns one probability per option. The set is built to compare decision models such as Jev and its open
47
+ alternatives. Its composition follows JevBench v1.6 (question types, difficulty tiers, item families and languages),
48
+ but it contains no JevBench items.
49
+
50
+ Use it for evaluation only. Do not train on it, fit temperatures on it, or use its items as examples.
51
+
52
+ ## At a glance
53
+
54
+ | | |
55
+ |---|---|
56
+ | Decisions | 2,352 |
57
+ | Question types | choice 1,178, yes/no 586, score (ordered levels) 588 |
58
+ | Difficulty tiers | easy 443, standard 407, judge 581, hard 921 |
59
+ | Languages | English 1,842; 510 items in 21 other languages or mixed-language inputs |
60
+ | Labels | computed by code 599; written by an LLM author and confirmed by a labeler panel 1,443; real user requests labeled by the panel 310 |
61
+
62
+ ## Files
63
+
64
+ | File | Content |
65
+ |---|---|
66
+ | `opendecisions.jsonl` | the 2,352 items |
67
+ | `score.py` | the scorer: Intelligence, Calibration and Capability (Python standard library only) |
68
+ | `predict_letters.py` | predictions from any Hugging Face chat model with a letter readout (one forward pass per item) |
69
+
70
+ ## How to evaluate
71
+
72
+ Write one prediction per item to a JSONL file, `{"id": "<item id>", "probs": {...}}`:
73
+
74
+ - choice: one probability per option id in `labels`
75
+ - yes/no: `{"yes": p, "no": 1 - p}`
76
+ - score: one probability per level `"0"`, `"1"`, ...
77
+
78
+ The probabilities of an item must sum to 1. Items without a prediction count as wrong. Then run:
79
+
80
+ ```
81
+ python score.py predictions.jsonl
82
+ ```
83
+
84
+ To get predictions from a Hugging Face chat model:
85
+
86
+ ```
87
+ pip install torch transformers accelerate
88
+ python predict_letters.py --model google/gemma-4-31B-it --out predictions.jsonl
89
+ python score.py predictions.jsonl
90
+ ```
91
+
92
+ `predict_letters.py` shows each item as a multiple-choice prompt with lettered options, runs the model once and reads
93
+ the probabilities of the option letters. `--temperatures` divides the letter logits by one temperature per question
94
+ type (choice, yes/no, score). Fit temperatures on your own data, never on OpenDecisions.
95
+
96
+ As a check of your setup: google/gemma-4-31B-it scores 72.3 without temperatures and 79.3 with
97
+ `--temperatures 5.96,7.2444,7.2444` (the temperatures we fitted on separate data). Our paper reports 79.6 for the same
98
+ model; there we ran many items per batch, which changes the top answer on 0.6% of items.
99
+
100
+ ## Format
101
+
102
+ One JSON object per line, in JevBench's task format. A short example:
103
+
104
+ ```json
105
+ {"id": "jb16-usecase-842d6d23b1", "family": "usecase", "tier": "easy", "language": "en",
106
+ "state": "CRM note, 2025-03-04, account Hillcrest Bakeries\nCall with Dana (purchasing). They open two new shops in May and asked us to double their weekly flour order from the first week of May onward.",
107
+ "question": {"type": "choice",
108
+ "instructions": "What does this note say about Hillcrest's flour orders from May?",
109
+ "criteria": {"lower_volume": "Hillcrest will order less flour than now.",
110
+ "same_volume": "Hillcrest will keep ordering about the same amount.",
111
+ "higher_volume": "Hillcrest will order more flour than now.",
112
+ "not_mentioned": "The note says nothing about future order volume."}},
113
+ "labels": ["lower_volume", "same_volume", "higher_volume", "not_mentioned"],
114
+ "expected": "higher_volume"}
115
+ ```
116
+
117
+ | Field | Content |
118
+ |---|---|
119
+ | `state` | the input: text or a JSON object |
120
+ | `question` | `type` (`choice`, `noul` = yes/no, `score`), `instructions`, and `criteria`: one description per option (choice), the meaning of `true` and `false` (yes/no), or the ordered levels (score) |
121
+ | `labels`, `expected` | the option ids and the correct one; yes/no items use `no` / `yes`; score items give the correct level as an index from 0 |
122
+ | `family`, `tier`, `language`, `use_case`, `topic` | what kind of item it is |
123
+ | `group` | items that belong together (pairs that differ in one detail, the same item with reordered options); empty otherwise |
124
+ | `label_source` | `programmatic`, `author+panel` or `panel` (see below) |
125
+ | `panel` | the answers of the three labeler models and their mean probability per option |
126
+ | `provenance` | origin and licence of the item, and the reason for its label |
127
+ | `jb16` | build details (generator, batch, prompt source) |
128
+
129
+ Item IDs (`jb16-...`) and the `jb16` field keep the set's working name from when it was built.
130
+
131
+ ## Item families
132
+
133
+ | Family | Items | What it tests |
134
+ |---|---:|---|
135
+ | llm_router | 694 | routing requests: task type, needed capability, model choice, difficulty |
136
+ | multilingual | 422 | decisions on inputs in 21 languages other than English, or mixed |
137
+ | fairness | 236 | variants that change only a protected attribute; the answer must stay the same |
138
+ | usecase | 213 | everyday business decisions (support, compliance, extraction, and similar) |
139
+ | jaggedness | 162 | easy-looking questions where models fail unevenly: counting, decimals vs. version numbers, dates, small sums |
140
+ | negation_pair_gen | 160 | pairs whose answer flips because one fact or the question is negated |
141
+ | option_order | 120 | the same item with its options reordered |
142
+ | perturb_pair | 110 | pairs that change only an irrelevant detail; the answer must stay the same |
143
+ | composite_gen | 106 | policies with 2 to 5 rules that need small computations |
144
+ | calibration_gen, calibration | 129 | the state fixes the answer distribution exactly (rates among past cases, dice, cards, draws) |
145
+
146
+ ## How the labels were made
147
+
148
+ - **Computed (599 items).** Written by seeded generators; the label is computed, so it is exact.
149
+ - **Authored (1,443 items).** Written by LLM agents (Claude Opus) from fixed briefs, with a label and a rationale.
150
+ Kept only if a panel of three open models (Qwen3.8-27B, gpt-oss-120b, GLM-4.7-Flash) agreed with the label: all
151
+ three, or two of three with a mean probability of at least 0.5 on the label.
152
+ - **Real requests (310 items).** User prompts from public datasets (Chatbot Arena 55k 288, Dolly 17, GSM8K 4,
153
+ MATH-500 1), each paired with a routing question. The label is the panel's answer, kept only when all three agree.
154
+ - Items that belong together are kept only if every member passes.
155
+ - Every candidate was compared with our model training data and with the 231 public JevBench items; 43 of 3,297
156
+ candidates were dropped for overlap. About 60 items were also read by hand.
157
+
158
+ ## Scoring
159
+
160
+ `score.py` computes Capability, the mean of Intelligence and Calibration, as JevBench v1.6 defines them, with one
161
+ change for yes/no questions.
162
+
163
+ - Intelligence: accuracy corrected for chance, per question type and difficulty tier (tier weights: easy 0.1,
164
+ standard 0.2, judge 0.3, hard 0.4; the three question types weigh equally).
165
+ - Calibration: an expected-calibration-error score per question type.
166
+ - Yes/no answers: "yes" if P(yes) is at least 0.5, otherwise "no".
167
+
168
+ Note: JevBench v1.6 counts a yes/no answer with P(yes) between 0.2 and 0.8 as an abstention, which is scored as
169
+ wrong. OpenDecisions drops this rule. The exact definitions are in the docstring of `score.py`.
170
+
171
+ We ran 17 public systems the way their authors serve them and scored them with JevBench v1.6's own rule. For the 14
172
+ with an official Capability of 55 or more, OpenDecisions ranks them close to the official JevBench v1.6.1 board
173
+ (Spearman correlation 0.90). For systems not used while the set was built, the official score is predicted to within
174
+ 3.0 points (root mean squared error).
175
+
176
+ ## Limitations
177
+
178
+ - Authored items may differ in style from real requests, and some labels may be wrong. 71 items are answered wrongly by every strong public system we ran; some of them may have wrong labels, others are simply hard.
179
+ - Compared with JevBench v1.6, our easy and standard tiers are easier and our hard tier is harder.
180
+ - Non-English items were written natively by the agents but not checked by native speakers.
181
+ - 78% of the items are English.
182
+ - All inputs are short (at most about 10,000 characters), so the set does not test long inputs. We removed 37 very
183
+ long items (about 80,000 tokens each) before release, because most decision models, ours included, refuse inputs above
184
+ 8,192 tokens.
185
+
186
+ ## Licence
187
+
188
+ CC BY-SA 4.0. Items built from real requests keep the terms of their source (Chatbot Arena 55k: Apache-2.0; Dolly:
189
+ CC BY-SA 3.0; GSM8K and MATH-500: MIT); each item names its source and licence in `provenance`. The code (`score.py`,
190
+ `predict_letters.py`) is under the MIT License. This dataset is not
191
+ affiliated with TypeSafe or Benchmark Heaven.
opendecisions.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
predict_letters.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Zero-shot letter readout of a Hugging Face chat model on OpenDecisions; writes predictions for score.py.
2
+
3
+ pip install torch transformers accelerate
4
+ python predict_letters.py --model google/gemma-4-31B-it --out predictions.jsonl
5
+ python predict_letters.py --model google/gemma-4-31B-it --out predictions.jsonl --temperatures 5.96,7.24,7.24
6
+ python score.py predictions.jsonl
7
+
8
+ Each item becomes a multiple-choice prompt with lettered options (the prompt of SemIf, github.com/TheoLeeCJ/SemIf):
9
+ a fixed system message and a JSON user message {"evidence": state, "criterion": question, "options": [{"letter",
10
+ "description"}]}, rendered with the model's chat template with thinking disabled. One forward pass gives the
11
+ next-token logits of the option letters A, B, C, ...; a softmax over the item's K letters gives the probabilities.
12
+ Option descriptions are "<id>: <text>"; yes/no questions have the options "true" (listed first) and "false"; score
13
+ levels are listed from lowest to highest. This is how JevBench's semif_direct adapter maps a question
14
+ (github.com/fstandhartinger/jevbench, MIT).
15
+
16
+ --temperatures choice,yesno,score divides the letter logits by one temperature per question type (default 1, 1, 1).
17
+ Our paper fits them by NLL on separate data, never below 1 (for example 5.96, 7.24, 7.24 for Gemma 4 31B).
18
+ Items above --max-tokens prompt tokens (default 8192) are skipped and count as wrong in score.py. MIT License.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import json
24
+ from pathlib import Path
25
+
26
+ SYSTEM = ("Apply the supplied criterion to the supplied evidence. Choose exactly one listed option. "
27
+ "Respond with only its uppercase letter, with no explanation or reasoning.")
28
+ LETTERS = "ABCDEFGHIJKLMNOP"
29
+
30
+
31
+ def options(question: dict) -> list[dict]:
32
+ """Option ids and descriptions of one question, in prompt order."""
33
+ qtype, criteria = question["type"], question["criteria"]
34
+ if qtype == "noul":
35
+ opts = [(key, criteria.get(key, f"The proposition is {key}.")) for key in ("true", "false")]
36
+ elif qtype == "choice" and isinstance(criteria, dict):
37
+ opts = [(key, text or key) for key, text in criteria.items()]
38
+ elif qtype == "choice": # a bare list of option ids
39
+ opts = [(str(key), str(key)) for key in criteria]
40
+ else:
41
+ opts = [(str(i), text) for i, text in enumerate(criteria)]
42
+ return [{"id": key, "description": f"{key}: {text}"} for key, text in opts]
43
+
44
+
45
+ def messages(item: dict) -> tuple[list[dict], list[str]]:
46
+ opts = options(item["question"])
47
+ if len(opts) > len(LETTERS):
48
+ raise ValueError(f"{item['id']}: more than {len(LETTERS)} options")
49
+ payload = {"evidence": item["state"], "criterion": item["question"]["instructions"],
50
+ "options": [{"letter": LETTERS[i], "description": o["description"]} for i, o in enumerate(opts)]}
51
+ return ([{"role": "system", "content": SYSTEM}, {"role": "user", "content": json.dumps(payload, ensure_ascii=False)}],
52
+ [o["id"] for o in opts])
53
+
54
+
55
+ def letter_ids(tokenizer) -> list[int]:
56
+ ids = []
57
+ for letter in LETTERS:
58
+ encoded = tokenizer.encode(letter, add_special_tokens=False)
59
+ if len(encoded) != 1 or tokenizer.decode(encoded) != letter:
60
+ raise ValueError(f"the letter {letter!r} is not a single token for this tokenizer")
61
+ ids.append(encoded[0])
62
+ return ids
63
+
64
+
65
+ def main() -> None:
66
+ import torch
67
+ from transformers import AutoModelForCausalLM, AutoTokenizer
68
+
69
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
70
+ parser.add_argument("--model", required=True)
71
+ parser.add_argument("--revision", default=None)
72
+ parser.add_argument("--out", required=True)
73
+ parser.add_argument("--data", default=str(Path(__file__).resolve().parent / "opendecisions.jsonl"))
74
+ parser.add_argument("--temperatures", default="1,1,1", help="choice,yesno,score")
75
+ parser.add_argument("--max-tokens", type=int, default=8192)
76
+ parser.add_argument("--limit", type=int, default=None, help="only the first N items (for a quick test)")
77
+ args = parser.parse_args()
78
+ temps = dict(zip(("choice", "noul", "score"), (float(x) for x in args.temperatures.split(","))))
79
+
80
+ torch.backends.cuda.enable_cudnn_sdp(False) # as in all our evaluations
81
+ tokenizer = AutoTokenizer.from_pretrained(args.model, revision=args.revision)
82
+ model = AutoModelForCausalLM.from_pretrained(args.model, revision=args.revision, dtype=torch.bfloat16,
83
+ device_map="auto").eval()
84
+ letters = letter_ids(tokenizer)
85
+ with open(args.data, encoding="utf-8") as f:
86
+ items = [json.loads(line) for line in f if line.strip()][:args.limit]
87
+ written = skipped = 0
88
+ with open(args.out, "w", encoding="utf-8") as out:
89
+ for item in items:
90
+ msgs, ids = messages(item)
91
+ prompt = tokenizer.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, enable_thinking=False)
92
+ tokens = tokenizer.encode(prompt, add_special_tokens=False)
93
+ if len(tokens) > args.max_tokens:
94
+ skipped += 1
95
+ continue
96
+ with torch.inference_mode():
97
+ logits = model(input_ids=torch.tensor([tokens], device=model.device), use_cache=False,
98
+ logits_to_keep=1).logits[0, -1].float()
99
+ qtype = item["question"]["type"]
100
+ probs = torch.softmax(logits[letters[:len(ids)]] / temps[qtype], dim=-1).tolist()
101
+ by_id = dict(zip(ids, probs))
102
+ if qtype == "noul":
103
+ by_id = {"yes": by_id["true"], "no": by_id["false"]}
104
+ out.write(json.dumps({"id": item["id"], "probs": by_id}) + "\n")
105
+ written += 1
106
+ print(f"wrote {written} predictions to {args.out}; skipped {skipped} items above {args.max_tokens} tokens")
107
+
108
+
109
+ if __name__ == "__main__":
110
+ main()
score.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Score a model's predictions on OpenDecisions: Intelligence, Calibration and Capability.
2
+
3
+ python score.py predictions.jsonl # data file: opendecisions.jsonl next to this script
4
+ python score.py predictions.jsonl --data path/to/opendecisions.jsonl --json
5
+
6
+ predictions.jsonl has one line per item: {"id": "<item id>", "probs": {"<label>": probability, ...}}
7
+ choice one probability per id in the item's "labels"
8
+ yes/no {"yes": p, "no": 1 - p} (or only {"yes": p})
9
+ score one probability per level "0", "1", ... (the item's "labels")
10
+ Probabilities are used as given and must sum to 1 over the item's labels (within 0.01, so rounded outputs are fine).
11
+ An item without a prediction counts as wrong (this is how we count inputs that are too long for a model).
12
+
13
+ The metric is JevBench v1.6's Capability, with one change: a yes/no answer counts as "yes" when P(yes) >= 0.5 and
14
+ as "no" otherwise. JevBench v1.6 instead counts an answer with 0.2 < P(yes) < 0.8 as an abstention (wrong).
15
+
16
+ Capability = (Intelligence + Calibration) / 2
17
+ Intelligence = mean over the three question types of a tier-weighted, chance-corrected competence
18
+ (tier weights easy 0.1, standard 0.2, judge 0.3, hard 0.4; each type's value clipped at 0),
19
+ clipped to [0, 100]
20
+ choice: 100 (acc - c) / (1 - c), c = mean of 1 / (number of options)
21
+ yes/no: 100 (acc - 0.5) / 0.5
22
+ score: 100 (1 - mean nMAE / mean nMAE of the mid-scale guess), nMAE = |E[level] - gold| / (K - 1)
23
+ Calibration = mean over the three types of
24
+ choice: 100 (1 - ECE / 0.5), top-label ECE on hard-tier items
25
+ yes/no: 100 (1 - ECE / 0.5), ECE of P(yes)
26
+ score: mean of 100 (1 - top-level ECE / 0.5) and 100 (1 - mean nRPS)
27
+ (ECE: 10 equal-width bins; each ECE term clipped at 0; only items with a prediction)
28
+
29
+ This file reimplements the JevBench v1.6 scorer from its published method and reproduces the published v1.6.1
30
+ results; JevBench's own v1.6 scorer is not public. MIT License.
31
+ """
32
+ from __future__ import annotations
33
+
34
+ import argparse
35
+ import json
36
+ import math
37
+ from collections import defaultdict
38
+ from pathlib import Path
39
+
40
+ TIER_WEIGHTS = {"easy": 0.1, "standard": 0.2, "judge": 0.3, "hard": 0.4}
41
+ TYPES = ("choice", "noul", "score")
42
+
43
+
44
+ # ------------------------------------------------------------------ per item
45
+
46
+ def ece(pairs: list[tuple[float, float]], bins: int = 10) -> float | None:
47
+ """Expected calibration error of (forecast, outcome) pairs; equal-width bins, empty bins absent."""
48
+ if not pairs:
49
+ return None
50
+ sums = defaultdict(lambda: [0, 0.0, 0.0])
51
+ for p, y in pairs:
52
+ p = min(max(float(p), 0.0), 1.0)
53
+ b = sums[min(int(p * bins), bins - 1)]
54
+ b[0] += 1
55
+ b[1] += p
56
+ b[2] += float(y)
57
+ return sum(n / len(pairs) * abs(o / n - f / n) for n, f, o in sums.values())
58
+
59
+
60
+ def nrps(probs: list[float], gold: int) -> float:
61
+ """Normalized ranked probability score (0 is perfect)."""
62
+ k, cum, total = len(probs), 0.0, 0.0
63
+ for level in range(k - 1):
64
+ cum += probs[level]
65
+ total += (cum - (1.0 if gold <= level else 0.0)) ** 2
66
+ return total / (k - 1)
67
+
68
+
69
+ def item_outcome(task: dict, probs: dict | None) -> dict:
70
+ """Outcome of one item; probs is None for a missing prediction (wrong, no forecast)."""
71
+ qtype, labels = task["question"]["type"], task["labels"]
72
+ out = {"id": task["id"], "type": qtype, "tier": task["tier"], "k": len(labels), "valid": probs is not None}
73
+ if qtype == "choice":
74
+ out["chance"] = 1.0 / len(labels)
75
+ if probs is None:
76
+ out.update(correct=False, conf=None)
77
+ else:
78
+ best = max(sorted(labels), key=lambda lab: probs[lab]) # ties: the smallest label
79
+ out.update(correct=best == task["expected"], conf=probs[best])
80
+ elif qtype == "noul":
81
+ y = 1.0 if task["expected"] == "yes" else 0.0
82
+ if probs is None:
83
+ out.update(correct=False, p_yes=None, y=y)
84
+ else:
85
+ p = probs["yes"]
86
+ out.update(correct=(p >= 0.5) == (y == 1.0), p_yes=p, y=y) # the more likely side; no abstention
87
+ else:
88
+ k, gold = len(labels), int(task["expected"])
89
+ out["nmae_chance"] = sum(abs(level - gold) for level in range(k)) / k / (k - 1) # random level
90
+ out["nmae_chance_mid"] = abs((k - 1) / 2 - gold) / (k - 1) # mid-scale guess
91
+ if probs is None:
92
+ out.update(nmae=max(gold, k - 1 - gold) / (k - 1), conf=None, correct=False) # the worst level
93
+ else:
94
+ vector = [probs[str(level)] for level in range(k)]
95
+ ev = sum(level * p for level, p in enumerate(vector))
96
+ best = max(range(k), key=lambda level: (vector[level], -level))
97
+ out.update(nmae=abs(ev - gold) / (k - 1), conf=vector[best], correct=best == gold, nrps=nrps(vector, gold))
98
+ return out
99
+
100
+
101
+ # ------------------------------------------------------------------ aggregation
102
+
103
+ def _weighted(values: dict, weights: dict) -> float | None:
104
+ present = {k: v for k, v in values.items() if v is not None}
105
+ total = sum(weights[k] for k in present)
106
+ return sum(weights[k] * v for k, v in present.items()) / total if total else None
107
+
108
+
109
+ def _mean(values: list[float]) -> float:
110
+ return sum(values) / len(values)
111
+
112
+
113
+ def competence(outs: list[dict]) -> float | None:
114
+ """Chance-corrected competence of items of one type and tier (0 = chance, 100 = perfect)."""
115
+ if not outs:
116
+ return None
117
+ qtype = outs[0]["type"]
118
+ if qtype == "choice":
119
+ acc, chance = _mean([o["correct"] for o in outs]), _mean([o["chance"] for o in outs])
120
+ return 100 * (acc - chance) / (1 - chance)
121
+ if qtype == "noul":
122
+ return 100 * (_mean([o["correct"] for o in outs]) - 0.5) / 0.5
123
+ chance = _mean([o["nmae_chance_mid"] for o in outs])
124
+ if chance <= 0: # every gold at mid-scale: the random-level baseline
125
+ chance = _mean([o["nmae_chance"] for o in outs])
126
+ return 100 * (1 - _mean([o["nmae"] for o in outs]) / chance)
127
+
128
+
129
+ def intelligence(outs: list[dict]) -> tuple[float | None, dict]:
130
+ per_type = {}
131
+ for qtype in TYPES:
132
+ tiers = {t: competence([o for o in outs if o["type"] == qtype and o["tier"] == t]) for t in TIER_WEIGHTS}
133
+ cc = _weighted(tiers, TIER_WEIGHTS)
134
+ per_type[qtype] = None if cc is None else max(0.0, cc)
135
+ total = _weighted(per_type, {t: 1 / 3 for t in TYPES})
136
+ return (None if total is None else min(100.0, max(0.0, total))), per_type
137
+
138
+
139
+ def _ece_score(e: float | None) -> float | None:
140
+ return None if e is None else max(0.0, 100 * (1 - e / 0.5))
141
+
142
+
143
+ def calibration(outs: list[dict]) -> tuple[float | None, dict]:
144
+ parts = {}
145
+ choice = [o for o in outs if o["type"] == "choice" and o["valid"]]
146
+ if choice:
147
+ parts["choice"] = _ece_score(ece([(o["conf"], float(o["correct"])) for o in choice if o["tier"] == "hard"]))
148
+ noul = [o for o in outs if o["type"] == "noul" and o["valid"]]
149
+ if noul:
150
+ parts["noul"] = _ece_score(ece([(o["p_yes"], o["y"]) for o in noul]))
151
+ score = [o for o in outs if o["type"] == "score" and o["valid"]]
152
+ if score:
153
+ top = _ece_score(ece([(o["conf"], float(o["correct"])) for o in score]))
154
+ parts["score"] = (top + 100 * (1 - _mean([o["nrps"] for o in score]))) / 2
155
+ return _weighted(parts, {t: 1 / 3 for t in TYPES}), parts
156
+
157
+
158
+ def summary(outs: list[dict]) -> dict:
159
+ i, cc = intelligence(outs)
160
+ c, cal = calibration(outs)
161
+ accuracy = {t: _mean([o["correct"] for o in outs if o["type"] == t]) * 100 for t in TYPES
162
+ if any(o["type"] == t for o in outs)}
163
+ return {"capability": None if i is None or c is None else (i + c) / 2, "intelligence": i, "calibration": c,
164
+ "competence_per_type": cc, "calibration_per_type": cal, "accuracy_per_type": accuracy,
165
+ "items": len(outs), "predicted": sum(o["valid"] for o in outs)}
166
+
167
+
168
+ # ------------------------------------------------------------------ input
169
+
170
+ def normalized(task: dict, probs: dict) -> dict:
171
+ labels = task["labels"]
172
+ if task["question"]["type"] == "noul" and "no" not in probs:
173
+ probs = {"yes": probs["yes"], "no": 1.0 - probs["yes"]}
174
+ values = {lab: float(probs.get(lab, 0.0)) for lab in labels}
175
+ if any(not math.isfinite(v) or v < 0 for v in values.values()):
176
+ raise ValueError(f"{task['id']}: probabilities must be finite and non-negative")
177
+ if abs(sum(values.values()) - 1.0) > 0.01:
178
+ raise ValueError(f"{task['id']}: probabilities over the labels {labels} sum to {sum(values.values()):.4f}, not 1")
179
+ return values
180
+
181
+
182
+ def score(tasks: list[dict], predictions: list[dict]) -> dict:
183
+ by_id = {t["id"]: t for t in tasks}
184
+ probs = {}
185
+ for p in predictions:
186
+ if p["id"] not in by_id:
187
+ raise ValueError(f"unknown item id {p['id']!r}")
188
+ if p["id"] in probs:
189
+ raise ValueError(f"item {p['id']!r} predicted twice")
190
+ probs[p["id"]] = normalized(by_id[p["id"]], p["probs"])
191
+ return summary([item_outcome(t, probs.get(t["id"])) for t in tasks])
192
+
193
+
194
+ def read_jsonl(path) -> list[dict]:
195
+ with open(path, encoding="utf-8") as f:
196
+ return [json.loads(line) for line in f if line.strip()]
197
+
198
+
199
+ def main() -> None:
200
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
201
+ parser.add_argument("predictions")
202
+ parser.add_argument("--data", default=str(Path(__file__).resolve().parent / "opendecisions.jsonl"))
203
+ parser.add_argument("--json", action="store_true", help="print the full result as JSON")
204
+ args = parser.parse_args()
205
+ result = score(read_jsonl(args.data), read_jsonl(args.predictions))
206
+ if args.json:
207
+ print(json.dumps(result, indent=1))
208
+ return
209
+ print(f"Capability {result['capability']:.1f} (Intelligence {result['intelligence']:.1f}, "
210
+ f"Calibration {result['calibration']:.1f}); {result['predicted']} of {result['items']} items predicted")
211
+ for t in TYPES:
212
+ if t in result["accuracy_per_type"]:
213
+ print(f" {t:7s} accuracy {result['accuracy_per_type'][t]:5.1f}% competence "
214
+ f"{result['competence_per_type'][t]:5.1f} calibration {result['calibration_per_type'][t]:5.1f}")
215
+
216
+
217
+ if __name__ == "__main__":
218
+ main()