basal-engine 3.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. basal/__init__.py +7 -0
  2. basal/adapter.py +420 -0
  3. basal/adapters.py +8 -0
  4. basal/agree.py +393 -0
  5. basal/attach.py +160 -0
  6. basal/attn512.py +132 -0
  7. basal/auth.py +194 -0
  8. basal/bench.py +367 -0
  9. basal/blockquant.py +227 -0
  10. basal/calibrate.py +2198 -0
  11. basal/chat.py +175 -0
  12. basal/cli.py +70 -0
  13. basal/client.py +8 -0
  14. basal/decision_log.py +189 -0
  15. basal/decision_rules.py +569 -0
  16. basal/decisions.py +158 -0
  17. basal/derive.py +98 -0
  18. basal/disconnect.py +85 -0
  19. basal/engine.py +6023 -0
  20. basal/evidence.py +133 -0
  21. basal/examples/choice.jsonl +8 -0
  22. basal/examples/complex.jsonl +5 -0
  23. basal/examples/labelled_tickets.jsonl +500 -0
  24. basal/examples/local_backend.py +34 -0
  25. basal/examples/noul.jsonl +8 -0
  26. basal/examples/questions.jsonl +20 -0
  27. basal/examples/score.jsonl +8 -0
  28. basal/examples/selfcheck_basal-omni-pico-Q8_0.json +1 -0
  29. basal/examples/selfcheck_basal-omni-pico.json +1 -0
  30. basal/examples/types_demo.py +74 -0
  31. basal/facts.py +497 -0
  32. basal/feedback.py +234 -0
  33. basal/file_identity.py +39 -0
  34. basal/finetune.py +321 -0
  35. basal/fit_decisions.py +944 -0
  36. basal/fla_configs.json +1822 -0
  37. basal/fold.py +206 -0
  38. basal/fonts/OFL-DMSans.txt +93 -0
  39. basal/fonts/OFL-SpaceGrotesk.txt +93 -0
  40. basal/fonts/dm-sans-latin-ext.woff2 +0 -0
  41. basal/fonts/dm-sans-latin.woff2 +0 -0
  42. basal/fonts/space-grotesk-latin-ext.woff2 +0 -0
  43. basal/fonts/space-grotesk-latin.woff2 +0 -0
  44. basal/fp8block.py +100 -0
  45. basal/gdn_graph.py +1792 -0
  46. basal/gemma4.py +726 -0
  47. basal/gemma4_graph.py +931 -0
  48. basal/gguf_export.py +497 -0
  49. basal/identity.py +217 -0
  50. basal/int8block.py +50 -0
  51. basal/interpolate.py +330 -0
  52. basal/jsonl.py +172 -0
  53. basal/lean.py +204 -0
  54. basal/llama_attn.py +252 -0
  55. basal/llama_attn_kernels.py +266 -0
  56. basal/llama_graph.py +587 -0
  57. basal/llama_kernels.py +593 -0
  58. basal/loadtest.py +189 -0
  59. basal/mcp_server.py +432 -0
  60. basal/media.py +138 -0
  61. basal/metrics.py +16 -0
  62. basal/mlx_attn_kernels.py +1057 -0
  63. basal/mlx_forward.py +326 -0
  64. basal/mlx_kernels.py +543 -0
  65. basal/mlx_metal.py +510 -0
  66. basal/navcut.py +283 -0
  67. basal/navigate.py +646 -0
  68. basal/navtree.py +397 -0
  69. basal/nvfp4.py +245 -0
  70. basal/ordercheck.py +165 -0
  71. basal/pdf.py +183 -0
  72. basal/prepared.py +355 -0
  73. basal/presets.py +8 -0
  74. basal/prompt.py +462 -0
  75. basal/rank.py +373 -0
  76. basal/readout.py +121 -0
  77. basal/request.py +327 -0
  78. basal/response_cache.py +105 -0
  79. basal/router.py +1551 -0
  80. basal/router_ui.html +902 -0
  81. basal/router_ui.py +277 -0
  82. basal/run.py +376 -0
  83. basal/selfcheck.py +215 -0
  84. basal/server.py +5279 -0
  85. basal/sets.py +214 -0
  86. basal/signals.py +28 -0
  87. basal/state_disk.py +942 -0
  88. basal/strix.py +505 -0
  89. basal/synth.py +92 -0
  90. basal/tasks.py +848 -0
  91. basal/textio.py +21 -0
  92. basal/think.py +390 -0
  93. basal/tools.py +171 -0
  94. basal/tpu.py +336 -0
  95. basal/tpu_kernels.py +129 -0
  96. basal/trace.py +125 -0
  97. basal/ui.html +861 -0
  98. basal/ui.py +526 -0
  99. basal/varloop.py +813 -0
  100. basal/varloop_graph.py +1377 -0
  101. basal/varloop_kernels.py +907 -0
  102. basal/viz.html +660 -0
  103. basal/viz.py +375 -0
  104. basal/vllm_unified.py +100 -0
  105. basal_engine-3.0.3.dist-info/METADATA +416 -0
  106. basal_engine-3.0.3.dist-info/RECORD +111 -0
  107. basal_engine-3.0.3.dist-info/WHEEL +5 -0
  108. basal_engine-3.0.3.dist-info/entry_points.txt +21 -0
  109. basal_engine-3.0.3.dist-info/licenses/LICENSE +202 -0
  110. basal_engine-3.0.3.dist-info/licenses/NOTICE +34 -0
  111. basal_engine-3.0.3.dist-info/top_level.txt +1 -0
basal/calibrate.py ADDED
@@ -0,0 +1,2198 @@
1
+ """Fit the calibration on your own labelled requests: one temperature per question type (for prompt-format-2 models
2
+ also one per option-count bucket of choice questions), the certified confidence thresholds of act's max_error (1%
3
+ and 5% by default), the calibration gates, from labelled multi questions the fallback_threshold of each label set
4
+ and, with --conformal, the answer-set thresholds of each coverage level, written as a calibration file for basal-serve.
5
+
6
+ basal-calibrate labelled.jsonl --model Remek/basal-1.5-4.5B --mode mlx # the engine in process
7
+ basal-calibrate labelled.jsonl --url http://127.0.0.1:8000 --model Remek/basal-1.5-4.5B
8
+ # a running `basal-serve ... --no-calibration`; --model (or --calibration) gives the shipped file to compare with
9
+ basal-serve --model Remek/basal-1.5-4.5B --mode mlx --calibration CALIBRATION.custom.json
10
+
11
+ Input (JSONL): one /v1/systemone request per line, every question with its correct answer in "gold":
12
+ {"id": "t-17", "state": "...", "group": "customer-17",
13
+ "questions": {"dept": {"type": "choice", "instructions": "...", "criteria": {"returns": "...", "it": "..."},
14
+ "gold": "returns"},
15
+ "late": {"type": "noul", "instructions": "...", "gold": "yes"},
16
+ "urg": {"type": "score", "instructions": "...", "criteria": ["low", "mid", "high"], "gold": 2}}}
17
+ gold choice: an option key or its description; noul: "yes" / "no" (true / false); score: the level index
18
+ (0 = first level; an integer is always the index), key or text; act: an outcome, as for choice (yes / no for true / false outcomes);
19
+ multi: the list of labels that apply (keys or descriptions; [] = none)
20
+ group optional, on the line or on a question: decisions of one group (twins, duplicates, one customer) stay on
21
+ the same side of the FIT / CERT split; default: one group per line (its questions share the state). When the
22
+ errors of a group's decisions go together (claims or fields of one document), the bound counts them as
23
+ fewer independent decisions (design effect 1 + (m - 1) ICC)
24
+ family optional, on the line or on a question: the task family of the leave-one-family-out ECE gate (default: the
25
+ question name)
26
+ id optional, used in messages.
27
+ multi questions with a "fallback" label only (and the objective, threshold, min, max and exclusive they are served
28
+ with): they fit the fallback_threshold of their label set; they do not enter the temperatures (to calibrate
29
+ the labels, ask each one as a noul question with its gold).
30
+ The simple items of basal-run and basal-bench ({"state", "question", "options", "type", "gold": <index>}) are
31
+ accepted too, e.g. basal/examples/questions.jsonl.
32
+ tasks classify (single label; gold = a label key, "none" with "none": true), verify (gold = {claim key: verdict},
33
+ or a list in the order of the claims; supported / contradicted / not_stated, binary: supported /
34
+ not_supported; null = not labelled) and extract (gold = the field values nested as in the schema; null = not
35
+ stated; a field left out is not labelled; arrays of enum are not certified) certify the task_thresholds of
36
+ their `automated` flag. They need the engine in process (not --url): the thresholds are certified on the
37
+ answers as served with the fitted temperatures. A file with task questions only keeps the decision
38
+ calibration it compares with and adds the task thresholds.
39
+
40
+ Method (the one the shipped files were fitted with):
41
+ * the decisions are split by a hash of their group into FIT (70%) and CERT (30%);
42
+ * one temperature per type (choice / noul / score; act counts as its base type) minimises the NLL of the served
43
+ prediction on FIT; a type with fewer than --min-per-type FIT decisions but at least --min-blend (10) gets it
44
+ blended in log space with the shipped one in proportion n / --min-per-type; with fewer it keeps the shipped one;
45
+ * prompt-format-2 models (basal.json "prompt": 2): the file is calibration file 2 ("prompt": 2), and choice questions
46
+ also get a temperature per option-count bucket (2-10, 11-26, 27-255) fitted the same way where FIT has at least
47
+ --min-per-type decisions in the bucket (otherwise the shipped bucket temperature, else the type temperature);
48
+ * for each target error r, the threshold comes from a fixed-sequence test on FIT: the confidence levels (equal
49
+ confidences accepted together) are tested from the most confident down, each with the one-sided 95%
50
+ Clopper-Pearson upper bound of its accepted decisions <= r, and the scan stops at the first level that fails; the
51
+ threshold is the last level that passed (none when the first fails). The first level tested is set by the counts
52
+ alone: the first that accepts enough decisions to meet the bound with one error (93 at 5%, 473 at 1%) when the
53
+ type has at least twice that many FIT decisions, else without an error (59 / 299; at least 50). CERT reports its coverage, error and bound, and a threshold CERT refutes (its
54
+ one-sided 95% lower bound of the error above r) is withdrawn. The threshold is fitted per type (thresholds[r].per_type[type], on the type's own decisions), and
55
+ once pooled over all types (thresholds[r].confidence, informational: basal-serve never applies it). A type
56
+ without a certified threshold of its own ("confidence": null, or no entry) has every automatic action of act and
57
+ tool with that max_error deferred ("no certified threshold for this type at this max_error"). A few hundred
58
+ decisions usually certify 5%; 1% needs at least 299 accepted FIT decisions of the type without an error (about
59
+ 1,000 items of the type or more);
60
+ * gates: ece_lofo per type, for every family the temperatures fitted on the FIT decisions of the other families and
61
+ the ECE measured on its CERT decisions (mean and max over the families with at least --min-family CERT decisions
62
+ of the type, and pooled over all of them), next to --reference (basal-1.5: the same statistic on our calibration
63
+ split); automated_at, the share of CERT decisions at or above their type's certified threshold. --strict exits with
64
+ status 1 when a type's mean LOFO ECE is above the reference (a type without a family of --min-family CERT
65
+ decisions is not tested: a warning on stderr and in the report, status unchanged);
66
+ * multi: per label set (its labels and fallback; id = basal.sets.label_set_id) the fallback_threshold with the best
67
+ mean IoU on FIT over a log grid (null = the default rule wins), with IoU, empty-set accuracy and false-empty rate
68
+ on CERT next to the default. basal-serve uses it for a request with the same label set and fallback and no
69
+ fallback_threshold of its own;
70
+ * --conformal 0.8,0.9,0.95 (off by default): split-conformal answer sets per type and coverage level L. The score
71
+ of a CERT decision is 1 - p(gold) under the fitted temperatures (CERT took no part in fitting them); p_min is the
72
+ k-th largest p(gold) of the type's CERT decisions, k = ceil((n + 1) L), and the set of an answer is every option
73
+ with p >= p_min (the top one always). The set then holds the correct answer with probability >= L, on average
74
+ over requests like the labelled ones. With n < L / (1 - L) CERT decisions of a type there is no p_min and the set
75
+ is every option. The FIT decisions report the coverage and mean size of the sets. basal-serve returns the set for
76
+ a choice / noul / score question with "coverage": L;
77
+ * tasks: per task (classify, verify, extract; every claim and field is one decision) the certified threshold of each
78
+ target error, by the same bound on FIT, with its coverage, error and bound on CERT ("task_thresholds" and
79
+ "task_gates"). The task thresholds a shipped file holds are kept only when the temperatures are (no decision
80
+ questions in the input); otherwise a task without labelled questions has none and its answers report
81
+ automated: null.
82
+ * --keep-shipped noul (a list of choice / noul / score; an act question counts as its base type): those types keep the compared
83
+ file's temperature (and for choice its option-count bucket temperatures) together with its per-type threshold of
84
+ every target, since a shipped threshold is certified only with the shipped temperature. For a type the labels do
85
+ not certify at a max_error the compared file did (the warning names it), this keeps automating it as the shipped
86
+ file did instead of deferring it. The report shows how the kept thresholds do on this file's FIT and CERT split
87
+ ("kept": "shipped" in the file, fitted_on.kept_shipped lists the types and kept_shipped_from names the file).
88
+ A kept threshold your FIT and CERT decisions refute is withdrawn; a pooled-only threshold (a file without per-type
89
+ ones) and a file of another engine are refused; the other types are fitted as usual;
90
+ * fitted_on names the model (and its Hugging Face revision, and model_files: the identity of the snapshot's files
91
+ but its card; model_content: the identity of the folder's files by their content, which matches a local folder):
92
+ basal-serve keeps a --calibration file fitted on another model, or on a revision with other model files, for its
93
+ temperatures only (its thresholds are not applied, the answers are marked unvalidated) with a warning, and refuses
94
+ it with --strict-calibration. A revision that changes only the card keeps the file.
95
+ """
96
+ import argparse
97
+ import asyncio
98
+ import datetime
99
+ import hashlib
100
+ import json
101
+ import math
102
+ import re
103
+ import sys
104
+ from collections import defaultdict
105
+ from pathlib import Path
106
+
107
+ import numpy as np
108
+ import torch
109
+
110
+ from . import __version__
111
+ from . import tasks as task_types
112
+ from .cli import add_api_key, headers, positive, refused
113
+ from .engine import resolve
114
+ from .jsonl import JSONLError, finite, read_lines, write, write_json
115
+ from .prompt import max_options, model_format, model_layout
116
+ from .server import (MODES, QUESTION_TYPES, UNVALIDATED_OUT, Server, _text, add_engine_args, answer_set,
117
+ calibration_file, calibration_name, certified, check_calibration, default_mode, identity_mismatch,
118
+ load_calibration, model_content_id, model_files_id, model_identity, model_weights_id,
119
+ refuse_lean_flex, temper, temperature, to_items, validate_baseline)
120
+ from .sets import label_set_id
121
+ from .sets import select as select_set
122
+ from .textio import read_text
123
+
124
+ PRIMS = ("choice", "noul", "score")
125
+ BUCKETS = (("2-10", 2, 10), ("11-26", 11, 26), ("27-255", 27, 255)) # option-count buckets of calibration file 2
126
+ ALPHA = 0.05 # one-sided 95% bounds
127
+ MIN_ACCEPTED = 50 # a threshold must accept at least this many FIT decisions
128
+ MIN_BLEND = 10 # from this many FIT decisions (below --min-per-type) a temperature is blended, not kept
129
+ RECOMMENDED = 200 # fewer labelled decisions: loose bounds
130
+ T_GRID = (0.25, 8.0) # temperatures searched (as for the shipped files)
131
+ METHOD = "bound-controlled (one-sided 95% Clopper-Pearson on FIT)"
132
+ CONFORMAL_METHOD = "split conformal on CERT (score 1 - p(gold), p_min = k-th largest p(gold), k = ceil((n + 1) L))"
133
+ POOLED_NOTE = ("informational: \"confidence\" here is one threshold pooled over all types; basal-serve applies only "
134
+ "per_type[type].confidence and defers a type without one")
135
+ YES, NO = {"yes", "true", "tak"}, {"no", "false", "nie"}
136
+ TASKS = ("classify", "verify", "extract") # the tasks with an `automated` flag (compress has none)
137
+ VERDICTS = ("supported", "contradicted", "not_stated")
138
+ KEPT_SOURCE = "shipped (--keep-shipped, with its thresholds)"
139
+ # what a file with task questions only does not take over from the file it keeps (written anew, or merged)
140
+ KEPT_OUT = ("fitted_on", "certified_on", "baseline", "engine", "task_thresholds", "task_gates", "decision_calibration")
141
+ # mean leave-one-family-out ECE of basal-1.5 (4.5B) per type on our calibration split (--reference basal-1.5)
142
+ REFERENCE = {"basal-1.5": {"choice": 0.082, "noul": 0.062, "score": 0.109}}
143
+ # fallback_threshold candidates of the multi fit (None: the default rule), 0.001-0.81 log-spaced and 0.05-0.95
144
+ FALLBACK_GRID = (None,) + tuple(sorted({round(0.001 * 1.25 ** k, 4) for k in range(31)} |
145
+ {x / 100 for x in range(5, 96, 5)}))
146
+
147
+
148
+ class InputError(ValueError):
149
+ pass
150
+
151
+
152
+ # -- input ---------------------------------------------------------------------------------------------------------
153
+ def gold_index(q, item):
154
+ """The gold answer of a question -> index of the correct option among the item's keys."""
155
+ g, keys = q["gold"], [str(k) for k in item["keys"]]
156
+ if keys == ["true", "false"]: # noul, or act with yes/no outcomes
157
+ s = str(g).strip().lower() if isinstance(g, (str, bool)) else None
158
+ if s in YES or s in NO:
159
+ return 0 if s in YES else 1
160
+ raise ValueError(f'gold must be "yes" or "no" (or true / false), got {g!r}')
161
+ crit = q.get("criteria") or q.get("levels") or []
162
+ if isinstance(g, int) and not isinstance(g, bool) and item["type"] == "score": # an integer is the level index
163
+ if not 0 <= g < len(keys):
164
+ raise ValueError(f"gold level {g} is out of range 0..{len(keys) - 1}")
165
+ if str(g) in keys and keys.index(str(g)) != g:
166
+ raise ValueError(f"gold {g} is ambiguous: level index {g} is key {keys[g]!r}, while key {str(g)!r} is "
167
+ f"level {keys.index(str(g))}; give the key as a string")
168
+ return g
169
+ if not isinstance(g, (dict, list)) and str(g) in keys:
170
+ return keys.index(str(g))
171
+ texts = list(crit.values()) if isinstance(crit, dict) else list(crit)
172
+ hits = {i for i, t in enumerate(texts) if t is not None and _text(t) == _text(g)}
173
+ hits |= {i for i, t in enumerate(item["options"]) if t == _text(g)}
174
+ if len(hits) == 1:
175
+ return hits.pop()
176
+ if hits:
177
+ raise ValueError(f"gold {g!r} matches several options; give the key")
178
+ what = "a level index, key or text" if item["type"] == "score" else "an option key or description"
179
+ raise ValueError(f"gold {g!r} is not an option (give {what}; keys: {', '.join(keys[:10])})")
180
+
181
+
182
+ def gold_set(q, item):
183
+ """The gold of a multi question (the labels that apply) -> sorted label indices."""
184
+ g, keys = q["gold"], [str(k) for k in item["keys"]]
185
+ if not isinstance(g, list):
186
+ raise ValueError("gold of a multi question must be the list of labels that apply ([] = none)")
187
+ out = set()
188
+ for x in g:
189
+ if not isinstance(x, (dict, list)) and str(x) in keys:
190
+ out.add(keys.index(str(x)))
191
+ continue
192
+ hits = [i for i, t in enumerate(item["labels"]) if t == _text(x)]
193
+ if len(hits) != 1:
194
+ raise ValueError(f"gold label {x!r} " + ("matches several labels; give the key" if hits else
195
+ f"is not a label (keys: {', '.join(keys[:10])})"))
196
+ out.add(hits[0])
197
+ return sorted(out)
198
+
199
+
200
+ def simple(rec):
201
+ """A simple item of basal-run / basal-bench (state, question, options, type, gold index) -> a labelled request."""
202
+ from .run import to_request
203
+ body = to_request(rec)
204
+ q = body["questions"]["q"]
205
+ if "gold" in rec:
206
+ g = rec["gold"]
207
+ q["gold"] = {0: "yes", 1: "no"}.get(g, g) if q["type"] == "noul" and not isinstance(g, bool) else g
208
+ return dict(body, **{k: rec[k] for k in ("id", "group", "family") if k in rec})
209
+
210
+
211
+ def _at(obj, keys):
212
+ """(found, value) at a field of a nested gold object: its property names from the root (tasks.field_keys)."""
213
+ for k in keys:
214
+ if not isinstance(obj, dict) or k not in obj:
215
+ return False, None
216
+ obj = obj[k]
217
+ return True, obj
218
+
219
+
220
+ def field_gold(path, kind, spec, v, lang=None):
221
+ """The gold of an extract field -> the value basal-serve would return for it (None = not stated); a number given as
222
+ text is read as basal-serve reads it in the question's language."""
223
+ if v is None:
224
+ return None
225
+ if kind == "enum":
226
+ vals = [c for c, _ in task_types._consts(spec)]
227
+ hit = [c for c in vals if type(c) is type(v) and c == v] or [c for c in vals if str(c) == str(v)]
228
+ if not hit:
229
+ raise ValueError(f"field {path!r}: gold {v!r} is not one of its values {vals[:10]}")
230
+ if len(hit) > 1:
231
+ raise ValueError(f"field {path!r}: gold {v!r} matches several values {hit[:10]}; give it with its JSON type")
232
+ return hit[0]
233
+ if kind == "boolean":
234
+ s = str(v).strip().lower()
235
+ if s in YES or s in NO:
236
+ return s in YES
237
+ raise ValueError(f"field {path!r}: gold {v!r} is not true / false")
238
+ if kind in ("number", "integer"):
239
+ x = v if isinstance(v, (int, float)) and not isinstance(v, bool) else task_types.parse_number(str(v), lang=lang)
240
+ if x is None:
241
+ raise ValueError(f"field {path!r}: gold {v!r} is not a number")
242
+ return x
243
+ if isinstance(v, (dict, list)):
244
+ raise ValueError(f"field {path!r}: gold must be the text of the value")
245
+ return str(v)
246
+
247
+
248
+ def field_correct(kind, value, gold):
249
+ """Whether an extract field's value is its gold: numbers by value, text up to spacing and case."""
250
+ if value is None or gold is None:
251
+ return value is None and gold is None
252
+ if kind in ("number", "integer"):
253
+ if isinstance(value, int) and isinstance(gold, int): # exact, also beyond a float's 53 bits
254
+ return value == gold
255
+ try:
256
+ return abs(float(value) - float(gold)) <= 1e-9 * max(1.0, abs(float(gold)))
257
+ except OverflowError: # an integer beyond a float's range against a fraction
258
+ return False
259
+ if kind == "string":
260
+ norm = lambda s: " ".join(str(s).split()).casefold()
261
+ return norm(value) == norm(gold)
262
+ return type(value) is type(gold) and value == gold # enum 1 is not true, nor "1"
263
+
264
+
265
+ def task_units(name, q, gold, state, lang=None):
266
+ """A labelled task question -> its labelled decisions [(part, gold)]: classify one (part None), verify one per
267
+ labelled claim, extract one per labelled field. The question must expand as basal-serve expands it."""
268
+ t = q["type"]
269
+ if t == "compress":
270
+ raise ValueError("compress has no automated flag, so there is nothing to certify: leave it out")
271
+ _, plans = task_types.expand({"state": state, "questions": {name: q}, **({"lang": lang} if lang else {})})
272
+ lang = plans[name].get("lang") # the errors basal-serve would give, and the language it reads numbers in
273
+ if t == "classify":
274
+ if q.get("multi_label"):
275
+ raise ValueError("multi-label classify has no automated flag (it reports set_confidence): ask it "
276
+ "single-label, or each label as a noul question")
277
+ keys = list(task_types._labels(q.get("labels") or q.get("criteria"), name)) + (["none"] if q.get("none") else [])
278
+ if isinstance(gold, (dict, list)) or str(gold) not in keys:
279
+ raise ValueError(f"gold {gold!r} is not a label (keys: {', '.join(keys[:10])})")
280
+ return [(None, str(gold))]
281
+ if t == "verify":
282
+ claims = q["claims"]
283
+ keys = [str(i) for i in range(len(claims))] if isinstance(claims, list) else [str(k) for k in claims]
284
+ if isinstance(gold, list):
285
+ if len(gold) != len(keys):
286
+ raise ValueError(f"gold has {len(gold)} verdicts for {len(keys)} claims")
287
+ gold = dict(zip(keys, gold))
288
+ if not isinstance(gold, dict):
289
+ raise ValueError("gold of verify: {claim key: verdict}, or a list in the order of the claims "
290
+ "(null = not labelled)")
291
+ allowed = ("supported", "not_supported") if q.get("binary") else VERDICTS
292
+ out = []
293
+ for k, v in gold.items():
294
+ if str(k) not in keys:
295
+ raise ValueError(f"gold names claim {k!r}, which is not one of {keys[:10]}")
296
+ if v is None:
297
+ continue
298
+ if isinstance(v, bool) and q.get("binary"):
299
+ v = "supported" if v else "not_supported"
300
+ v = str(v).strip().lower().replace(" ", "_").replace("-", "_")
301
+ if v not in allowed:
302
+ raise ValueError(f"claim {k!r}: verdict {v!r} is not one of {', '.join(allowed)}")
303
+ out.append((str(k), v))
304
+ if not out:
305
+ raise ValueError("no claim has a verdict")
306
+ return out
307
+ if not isinstance(gold, dict):
308
+ raise ValueError("gold of extract: the field values nested as in the schema (null = not stated; a field left "
309
+ "out is not labelled)")
310
+ out = []
311
+ keys = task_types.field_keys(q.get("schema") or {})
312
+ for path, kind, spec in task_types.leaves(q.get("schema") or {}):
313
+ found, v = _at(gold, keys[path])
314
+ if found and kind not in ("enum_list", "list"): # (a label set or a list: no certified threshold)
315
+ out.append((path, (kind, field_gold(path, kind, spec, v, lang))))
316
+ if not out:
317
+ raise ValueError("gold labels no field (enum, boolean, string, number or integer) of the schema")
318
+ return out
319
+
320
+
321
+ # a labelled question is asked whatever the answers of the others: its gold is its answer (and a condition can name a
322
+ # question of the other request, decisions or tasks)
323
+ CONDITIONAL = ("ask_if", "depends_on")
324
+
325
+
326
+ def group_of(q, rec, n):
327
+ """The split group of a labelled question: its own "group", else the line's "group", else the line's "id", else the
328
+ line number; null counts as not given (not one group "None" for every such line)."""
329
+ return str(next((x for x in (q.get("group"), rec.get("group"), rec.get("id")) if x is not None), n))
330
+
331
+
332
+ def load(path):
333
+ """Labelled JSONL -> (requests to send, decisions): the decision questions only (read() also returns the task
334
+ questions). Raises InputError listing every problem with its line."""
335
+ bodies, decisions, _, _ = read(path)
336
+ return bodies, decisions
337
+
338
+
339
+ def read(path):
340
+ """Labelled JSONL -> (decision requests, decisions, task requests, labelled task decisions). Raises InputError
341
+ listing every problem with its line."""
342
+ errors, bodies, decisions, task_bodies, units = [], [], [], [], []
343
+ for n, line in enumerate(read_lines(path), 1):
344
+ if not line.strip():
345
+ continue
346
+ try:
347
+ rec = json.loads(line)
348
+ except json.JSONDecodeError as e:
349
+ errors.append(f"line {n}: not JSON ({e.msg})")
350
+ continue
351
+ if isinstance(rec, dict) and "questions" not in rec and "question" in rec:
352
+ try:
353
+ rec = simple(rec)
354
+ except (ValueError, KeyError, TypeError) as e:
355
+ errors.append(f"line {n}: {e}")
356
+ continue
357
+ if not isinstance(rec, dict) or "state" not in rec or not isinstance(rec.get("questions"), dict) \
358
+ or not rec["questions"]:
359
+ errors.append(f'line {n}: a request needs "state" and a non-empty "questions" object')
360
+ continue
361
+ where = f"line {n}" + (f" (id {rec['id']})" if "id" in rec else "")
362
+ if rec.get("facts", "off") not in ("off", "auto"):
363
+ errors.append(f'{where}: facts must be "off" or "auto"')
364
+ continue
365
+ body = {k: v for k, v in rec.items() if k not in ("id", "group", "family")}
366
+ body["questions"], task_body = {}, dict(body, questions={})
367
+ for name, q in rec["questions"].items():
368
+ at = f"{where}, question {name!r}"
369
+ if not isinstance(q, dict):
370
+ errors.append(f"{at}: not an object")
371
+ continue
372
+ t = q.get("type", "choice")
373
+ if t in task_types.TASKS: # classify / verify / extract: their task thresholds (in process, served)
374
+ if "gold" not in q:
375
+ errors.append(f'{at}: no "gold" answer')
376
+ continue
377
+ clean = {k: v for k, v in q.items() if k not in ("gold", "group", "family") + CONDITIONAL}
378
+ try:
379
+ labelled = task_units(name, clean, q["gold"], rec["state"], rec.get("lang"))
380
+ except (ValueError, KeyError, TypeError) as e:
381
+ errors.append(f"{at}: {str(e).removeprefix(f'question {name!r}: ')}")
382
+ continue
383
+ task_body["questions"][name] = clean
384
+ group = group_of(q, rec, n)
385
+ units += [dict(line=n, req=len(task_bodies), name=name, task=t, part=part, gold=g, group=group)
386
+ for part, g in labelled]
387
+ continue
388
+ if t == "multi" and q.get("fallback") is None:
389
+ errors.append(f'{at}: multi needs a "fallback" label (its fallback_threshold is fitted); to calibrate '
390
+ "the labels, ask each one as a noul question with its own gold")
391
+ continue
392
+ if t not in ("choice", "noul", "score", "act", "multi"):
393
+ errors.append(f"{at}: unknown type {t!r} (choice, noul, score, act, multi, classify, verify or "
394
+ "extract)")
395
+ continue
396
+ if "gold" not in q:
397
+ errors.append(f'{at}: no "gold" answer')
398
+ continue
399
+ clean = {k: v for k, v in q.items()
400
+ if k not in ("gold", "group", "family", "evidence", "fallback_threshold") + CONDITIONAL}
401
+ try:
402
+ item = to_items(rec["state"], {name: clean}, max_options(2))[0] # the model's limit: when served
403
+ gold = gold_set(q, item) if t == "multi" else gold_index(q, item)
404
+ except (ValueError, KeyError, TypeError) as e:
405
+ errors.append(f"{at}: {str(e).removeprefix(f'question {name!r}: ')}")
406
+ continue
407
+ body["questions"][name] = clean
408
+ d = dict(line=n, req=len(bodies), name=name, prim=item.get("base", t), gold=gold,
409
+ keys=[str(k) for k in item["keys"]], group=group_of(q, rec, n),
410
+ family=str(next((x for x in (q.get("family"), rec.get("family")) if x is not None), name)))
411
+ if t == "multi":
412
+ d.update(prim="multi", set=dict(
413
+ id=label_set_id(item["keys"], item["labels"], item["fallback"]), objective=item["objective"],
414
+ threshold=item["threshold"], min=item["min"], max=item["max"], exclusive=item["exclusive"],
415
+ fallback=item["fallback"]))
416
+ decisions.append(d)
417
+ if body["questions"]:
418
+ bodies.append(body)
419
+ if task_body["questions"]:
420
+ task_bodies.append(task_body)
421
+ if errors:
422
+ more = f"\n ... and {len(errors) - 20} more" if len(errors) > 20 else ""
423
+ raise InputError(f"{path}: {len(errors)} problem(s)\n " + "\n ".join(errors[:20]) + more)
424
+ if not decisions and not units:
425
+ raise InputError(f"{path}: no labelled questions")
426
+ return bodies, decisions, task_bodies, units
427
+
428
+
429
+ # -- probabilities ---------------------------------------------------------------------------------------------------
430
+ async def collect(decide, bodies, concurrency=32):
431
+ """Every request through `decide` (Server.decide in process, or HTTP) -> responses (an Exception on failure)."""
432
+ sem, done, step = asyncio.Semaphore(concurrency), 0, max(1, len(bodies) // 10)
433
+
434
+ async def one(b):
435
+ nonlocal done
436
+ async with sem:
437
+ try:
438
+ r = await decide(b)
439
+ except Exception as e: # noqa: BLE001
440
+ r = e
441
+ done += 1
442
+ if done % step == 0 or done == len(bodies):
443
+ print(f" {done}/{len(bodies)} requests", file=sys.stderr, flush=True)
444
+ return r
445
+ return await asyncio.gather(*(one(b) for b in bodies))
446
+
447
+
448
+ async def in_process(srv, bodies, concurrency):
449
+ worker = asyncio.get_running_loop().create_task(srv.worker())
450
+ try:
451
+ return await collect(srv.decide, bodies, concurrency)
452
+ finally:
453
+ worker.cancel()
454
+
455
+
456
+ async def two_passes(srv, bodies, task_bodies, concurrency, settle):
457
+ """In process: the decision requests without calibration, then settle(responses) -> the calibration to serve, and
458
+ the task requests served with it (their thresholds are certified on the answers as served). One event loop for
459
+ both: the server's queue belongs to it."""
460
+ worker = asyncio.get_running_loop().create_task(srv.worker())
461
+ try:
462
+ responses = await collect(srv.decide, bodies, concurrency) if bodies else []
463
+ cal = settle(responses)
464
+ if not task_bodies:
465
+ return responses, []
466
+ print(f" task requests, served with the {'fitted' if bodies else 'kept'} calibration", file=sys.stderr)
467
+ srv.cal, srv.temps = cal, cal.get("temperature_per_prim", {})
468
+ return responses, await collect(srv.decide, task_bodies, concurrency)
469
+ finally:
470
+ worker.cancel()
471
+
472
+
473
+ async def over_http(endpoint, bodies, concurrency, api_key=None):
474
+ import httpx
475
+ async with httpx.AsyncClient(timeout=600, headers=headers(api_key)) as c:
476
+ async def decide(b):
477
+ r = await c.post(endpoint, json=b)
478
+ if r.status_code != 200:
479
+ raise RuntimeError(r.text)
480
+ return r.json()
481
+ return await collect(decide, bodies, concurrency)
482
+
483
+
484
+ def uncalibrated(entry, base):
485
+ """The GET /v1/models entry of a running server -> the entry; refuses a server that applies temperatures."""
486
+ temps = entry.get("temperature_per_prim")
487
+ buckets = entry.get("temperature_per_bucket") or {} # {type: {bucket: T}}, a server with a file-2 calibration
488
+ if buckets:
489
+ temps = dict(temps or {})
490
+ for prim, per_bucket in buckets.items():
491
+ for bucket, t in per_bucket.items():
492
+ temps[f"{prim}/{bucket}"] = t
493
+ if temps is None:
494
+ print(f"warning: {base} does not report its temperatures (basal-serve before 2.0.0); make sure it runs with "
495
+ "--no-calibration", file=sys.stderr)
496
+ elif any(float(t) != 1.0 for t in temps.values()):
497
+ raise SystemExit(f"{base} serves calibrated probabilities (temperatures {temps}); start basal-serve with "
498
+ "--no-calibration for basal-calibrate")
499
+ return entry
500
+
501
+
502
+ def raw_rows(decisions, responses):
503
+ """Decisions + responses -> (rows with the uncalibrated probabilities `p` over their keys, failed requests)."""
504
+ rows, failed = [], {}
505
+ for d in decisions:
506
+ r = responses[d["req"]]
507
+ if isinstance(r, Exception):
508
+ failed[d["req"]] = f"line {d['line']}: {r}"
509
+ continue
510
+ a = (r.get("answers") or {}).get(d["name"])
511
+ if not isinstance(a, dict) or not isinstance(a.get("probabilities"), dict):
512
+ failed[(d["req"], d["name"])] = f"line {d['line']}, question {d['name']!r}: no answer"
513
+ continue
514
+ p = a["probabilities"]
515
+ rows.append(dict(d, p=[float(p[k]) if isinstance(p.get(k), (int, float)) else math.nan for k in d["keys"]]))
516
+ return rows, list(failed.values())
517
+
518
+
519
+ # -- method ----------------------------------------------------------------------------------------------------------
520
+ def is_cert(group):
521
+ """FIT / CERT split by group: 30% of the groups certify (the hash the shipped files used)."""
522
+ return int(hashlib.sha256(group.encode()).hexdigest(), 16) % 10 < 3
523
+
524
+
525
+ T_POINTS = np.exp(np.linspace(np.log(T_GRID[0]), np.log(T_GRID[1]), 241)) # the grid of fit_temperature
526
+
527
+
528
+ def row_nll(rows, K):
529
+ """The NLL of each row's gold answer at every temperature of T_POINTS, the rows padded to K options with -inf
530
+ -> array (len(T_POINTS), len(rows)). A row's values depend only on the row and K (not on the other rows)."""
531
+ L = np.full((len(rows), K), -np.inf)
532
+ for i, r in enumerate(rows):
533
+ L[i, : len(r["p"])] = np.log(np.clip(r["p"], 1e-12, 1))
534
+ gold = np.array([r["gold"] for r in rows])
535
+ out = np.empty((len(T_POINTS), len(rows)))
536
+ for j, t in enumerate(T_POINTS):
537
+ z = L / t
538
+ m = z.max(1, keepdims=True)
539
+ out[j] = m[:, 0] + np.log(np.exp(z - m).sum(1)) - z[np.arange(len(rows)), gold]
540
+ return out
541
+
542
+
543
+ def fit_temperature(rows, memo=None):
544
+ """Temperature minimising the mean NLL of the gold answers on the log grid T_POINTS over T_GRID (the first of
545
+ equal minima). memo: a dict kept by the caller across fits on overlapping rows (lofo: one fit per family left
546
+ out) with each row's NLLs at this fit's padding K, {(id(row), K): array}; the rows must stay alive and unchanged
547
+ while it is used. The means are the same bit for bit as without it."""
548
+ K = max(len(r["p"]) for r in rows)
549
+ memo = {} if memo is None else memo
550
+ new = [r for r in rows if (id(r), K) not in memo]
551
+ if new:
552
+ for r, v in zip(new, row_nll(new, K).T):
553
+ memo[id(r), K] = v
554
+ nll = np.stack([memo[id(r), K] for r in rows], axis=1).mean(1)
555
+ return float(T_POINTS[int(np.argmin(nll))])
556
+
557
+
558
+ def buckets_cover(buckets, prim="choice", lo=2, hi=255):
559
+ """Whether the bucket temperatures of `prim` cover every option count lo..hi, so that basal-serve never applies its
560
+ type temperature (server.temperature: the bucket first)."""
561
+ seen = set()
562
+ for b in (buckets or {}).get(prim) or {}:
563
+ a, z = (int(x) for x in b.split("-"))
564
+ seen.update(range(a, z + 1))
565
+ return seen >= set(range(lo, hi + 1))
566
+
567
+
568
+ class Tempered:
569
+ """The probabilities of rows as basal-serve returns them with one set of temperatures (same float32 maths, one row
570
+ at a time): temps per type, buckets {type: {"lo-hi": T}} (calibration file 2) before them. Each row is tempered
571
+ once: fit() asks for the same rows at every target, per type and in every report."""
572
+
573
+ def __init__(self, temps, buckets=None):
574
+ self.cal, self.memo = dict(temperature_per_prim=temps or {}, temperature_per_bucket=buckets or {}), {}
575
+
576
+ def p(self, rows):
577
+ out = []
578
+ for r in rows:
579
+ hit = self.memo.get(id(r))
580
+ if hit is None: # the row is kept with its result, so its id is not reused while the cache lives
581
+ hit = self.memo[id(r)] = (r, temper(torch.tensor(r["p"]),
582
+ temperature(self.cal, r["prim"], len(r["p"]))).tolist())
583
+ out.append(hit[1])
584
+ return out
585
+
586
+ def cs(self, rows):
587
+ """(confidence, correct) of every row as served."""
588
+ return [(float(max(p)), int(np.argmax(p)) == r["gold"]) for r, p in zip(rows, self.p(rows))]
589
+
590
+
591
+ def served_p(rows, temps, buckets=None):
592
+ """The probabilities of every row as basal-serve returns them with these temperatures (Tempered)."""
593
+ return Tempered(temps, buckets).p(rows)
594
+
595
+
596
+ def served(rows, temps, buckets=None):
597
+ """(confidence, correct) of every row as basal-serve returns it with these temperatures."""
598
+ return Tempered(temps, buckets).cs(rows)
599
+
600
+
601
+ def ece(cs, bins=10):
602
+ """Expected calibration error of the top answer (equal-width bins)."""
603
+ if not cs:
604
+ return None
605
+ c, ok = np.array([x for x, _ in cs]), np.array([o for _, o in cs], float)
606
+ e = 0.0
607
+ for lo, hi in zip(np.linspace(0, 1, bins + 1)[:-1], np.linspace(0, 1, bins + 1)[1:]):
608
+ m = (c > lo) & (c <= hi)
609
+ if m.any():
610
+ e += m.mean() * abs(c[m].mean() - ok[m].mean())
611
+ return float(e)
612
+
613
+
614
+ _LF = np.zeros(1) # _LF[i] = log(i!), grown on demand
615
+
616
+
617
+ def log_factorials(n):
618
+ """log(i!) for i = 0..n at least: one table grown by doubling (a slice of it costs nothing, where a list turned
619
+ into an array on every bound cost O(n) and made a threshold scan over n decisions O(n^2))."""
620
+ global _LF
621
+ if len(_LF) <= n:
622
+ _LF = np.array([math.lgamma(i + 1) for i in range(max(n + 1, 2 * len(_LF)))])
623
+ return _LF
624
+
625
+
626
+ def cp_upper(e, n, alpha=ALPHA):
627
+ """One-sided Clopper-Pearson upper bound of a binomial error rate (bisection on the binomial CDF, in log space)."""
628
+ if n == 0:
629
+ return 1.0
630
+ lf = log_factorials(n)
631
+ i = np.arange(e + 1)
632
+ comb = lf[n] - lf[i] - lf[n - i]
633
+
634
+ def cdf(p):
635
+ if p >= 1.0:
636
+ return 1.0 if e >= n else 0.0
637
+ t = comb + i * math.log(p) + (n - i) * math.log1p(-p)
638
+ m = t.max()
639
+ return math.exp(m) * float(np.exp(t - m).sum())
640
+ lo, hi = e / n, 1.0
641
+ for _ in range(60):
642
+ mid = (lo + hi) / 2
643
+ lo, hi = (mid, hi) if cdf(mid) > alpha else (lo, mid)
644
+ return hi
645
+
646
+
647
+ def levels(cs):
648
+ """(confidence, correct) -> [(confidence, accepted, errors)] from the most confident level down, ties together."""
649
+ by = defaultdict(lambda: [0, 0])
650
+ for c, ok in cs:
651
+ by[c][0] += 1
652
+ by[c][1] += not ok
653
+ out, n, e = [], 0, 0
654
+ for c in sorted(by, reverse=True):
655
+ n, e = n + by[c][0], e + by[c][1]
656
+ out.append((c, n, e))
657
+ return out
658
+
659
+
660
+ def icc(cs, groups):
661
+ """The intraclass correlation of the errors of decisions (confidence, correct) within their groups (one-way ANOVA
662
+ estimator, clipped to [0, 1]): 0 for singleton groups; maximal dependence when error variation cannot be estimated. When one claim
663
+ or field of a document is wrong the others are likelier wrong too; the bound then counts fewer independent
664
+ decisions (design_effect)."""
665
+ by = defaultdict(list)
666
+ for (_, ok), g in zip(cs, groups):
667
+ by[g].append(0.0 if ok else 1.0)
668
+ N, k = len(cs), len(by)
669
+ if N == k:
670
+ return 0.0
671
+ if k < 2:
672
+ return 1.0 # one group gives no information on between-group variance
673
+ y = sum(sum(v) for v in by.values()) / N
674
+ ssb = sum(len(v) * (sum(v) / len(v) - y) ** 2 for v in by.values())
675
+ ssw = sum(sum((x - sum(v) / len(v)) ** 2 for x in v) for v in by.values())
676
+ msb, msw = ssb / (k - 1), ssw / (N - k)
677
+ n0 = (N - sum(len(v) ** 2 for v in by.values()) / N) / (k - 1)
678
+ den = msb + (n0 - 1) * msw
679
+ return min(1.0, max(0.0, (msb - msw) / den)) if den > 0 else 1.0
680
+
681
+
682
+ def design_effect(cs, groups):
683
+ """(rho, deff) of decisions in groups: rho = icc, deff = 1 + (m - 1) rho with m = the sum of the squared group
684
+ sizes over the decisions (Kish; the mean group size a decision is in). Every accepted set is discounted by the
685
+ deff of all the decisions: as if a group's decisions were always accepted together, which overstates it for the
686
+ most confident levels (where a group has few accepted decisions) and keeps the bound on the safe side when rho is
687
+ underestimated (rare errors). One decision per group, or rho 0: deff 1."""
688
+ rho = icc(cs, groups)
689
+ return rho, design_effect_of(groups, rho)
690
+
691
+
692
+ def design_effect_of(groups, rho):
693
+ """deff of decisions in these groups at a given rho (CERT's group sizes with FIT's rho)."""
694
+ if not rho or not groups:
695
+ return 1.0
696
+ size = defaultdict(int)
697
+ for g in groups:
698
+ size[g] += 1
699
+ return 1 + (sum(v * v for v in size.values()) / len(groups) - 1) * rho
700
+
701
+
702
+ def effective(n, e, deff=1.0):
703
+ """n decisions with e errors -> (n, e) as independent decisions: both divided by deff, n rounded down, e up."""
704
+ if deff <= 1:
705
+ return n, e
706
+ return math.floor(n / deff + 1e-9), math.ceil(e / deff - 1e-9)
707
+
708
+
709
+ def within(e, n, risk, alpha=ALPHA):
710
+ """Whether the one-sided Clopper-Pearson upper bound of e errors in n is at most risk: P(X <= e) <= alpha for
711
+ X ~ Binomial(n, risk) (the bound is the p where that probability is alpha, and it falls as p grows), one binomial
712
+ tail instead of a bisection."""
713
+ if n == 0 or e / n > risk:
714
+ return False
715
+ lf = log_factorials(n)
716
+ i = np.arange(e + 1)
717
+ t = lf[n] - lf[i] - lf[n - i] + i * math.log(risk) + (n - i) * math.log1p(-risk)
718
+ m = t.max()
719
+ return math.exp(m) * float(np.exp(t - m).sum()) <= alpha
720
+
721
+
722
+ def refutes(e, n, risk, alpha=ALPHA):
723
+ """Whether e errors among n accepted CERT decisions refute a threshold certified at `risk`: P(X >= e) <= alpha for
724
+ X ~ Binomial(n, risk), i.e. the one-sided 95% lower bound of their error is above risk. CERT took no part in the
725
+ fit, so a threshold whose error is at most risk is refuted at most alpha of the time; too few CERT decisions to
726
+ confirm it (cert_note) is not a refutation."""
727
+ if n == 0 or e <= risk * n:
728
+ return False
729
+ lf = log_factorials(n)
730
+ i = np.arange(e)
731
+ t = lf[n] - lf[i] - lf[n - i] + i * math.log(risk) + (n - i) * math.log1p(-risk)
732
+ m = t.max()
733
+ return 1.0 - math.exp(m) * float(np.exp(t - m).sum()) <= alpha
734
+
735
+
736
+ def withdrawn(entry, risk, deff=1.0):
737
+ """A per-type or task entry (certified on FIT, measured on CERT) -> the entry, or with its confidence withdrawn
738
+ (null: basal-serve defers) when CERT refutes it (its decisions counted as the independent ones they are worth, the
739
+ errors rounded down)."""
740
+ n = entry.get("cert_accepted") or 0
741
+ e = round((entry.get("cert_error") or 0.0) * n)
742
+ n_i, e_i = (n, e) if deff <= 1 else (math.ceil(n / deff - 1e-9), math.floor(e / deff + 1e-9))
743
+ if entry.get("confidence") is None or not refutes(e_i, n_i, risk):
744
+ return entry
745
+ return dict(entry, confidence=None, refuted=entry["confidence"],
746
+ reason=f"certified on FIT at {entry['confidence']:.4f}, but CERT refutes it: {e} error"
747
+ f"{'' if e == 1 else 's'} in {n} accepted, a one-sided 95% lower bound above {risk:g}")
748
+
749
+
750
+ def start_level(lv, risk, alpha=ALPHA, min_n=MIN_ACCEPTED):
751
+ """The first level the fixed sequence tests, of levels lv (levels()): the most confident one that accepts enough
752
+ decisions to meet the bound with one error (93 at 5%, 473 at 1%) when there are at least twice that many decisions,
753
+ else enough to meet it without an error (59 / 299; fewer cannot meet it at all). One error allowed at the start
754
+ keeps a single error among the very top decisions from ending the test, where the data can afford it. The start
755
+ depends on the counts only, never on which decisions are correct -> its index, None when no level accepts that
756
+ many."""
757
+ need = accepted_needed(risk, 1, alpha, min_n)
758
+ if not lv or lv[-1][1] < 2 * need:
759
+ need = accepted_needed(risk, 0, alpha, min_n)
760
+ return next((k for k, (_, n, _) in enumerate(lv) if n >= need), None)
761
+
762
+
763
+ def threshold(cs, risk, alpha=ALPHA, min_n=MIN_ACCEPTED, deff=1.0):
764
+ """The certified threshold of a fixed-sequence test: the levels are tested from the most confident down, starting
765
+ at start_level (set by the counts alone, before any outcome is read), each at the one-sided bound <= risk, and the
766
+ scan stops at the first level that fails; the threshold is the last level that passed, None when the first one
767
+ fails. Testing in a fixed order and stopping at the first failure keeps the chance of certifying a threshold whose
768
+ accepted decisions are above `risk` at <= alpha; scanning on past failures until one level passes does not. A
769
+ level that adds no error to a passing one passes too (more decisions, the same errors: a lower bound), so the
770
+ bound is computed only where errors are added. deff (design_effect, > 1 when errors go together within groups)
771
+ counts every level's decisions and errors as fewer independent ones."""
772
+ lv = [(c, *effective(n, e, deff)) for c, n, e in levels(cs)]
773
+ k = start_level(lv, risk, alpha, min_n)
774
+ thr, passed = None, None # passed: the errors of the last level that passed
775
+ for c, n, e in (lv[k:] if k is not None else ()):
776
+ if e != passed and not within(e, n, risk, alpha):
777
+ break
778
+ thr, passed = c, e
779
+ return thr
780
+
781
+
782
+ def accepted_needed(risk, errors=0, alpha=ALPHA, min_n=MIN_ACCEPTED):
783
+ """The fewest accepted decisions with `errors` errors whose one-sided upper bound is at most `risk` (0 / 1 / 2
784
+ errors: 299 / 473 / 628 at 1%, 59 / 93 / 124 at 5%)."""
785
+ if errors == 0:
786
+ return max(min_n, math.ceil(math.log(alpha) / math.log(1 - risk)))
787
+ lo = hi = accepted_needed(risk, 0, alpha, min_n)
788
+ while cp_upper(errors, hi, alpha) > risk:
789
+ lo, hi = hi, hi * 2
790
+ while lo < hi: # lo fails (or equals hi), hi passes
791
+ mid = (lo + hi) // 2
792
+ lo, hi = (mid + 1, hi) if cp_upper(errors, mid, alpha) > risk else (lo, mid)
793
+ return hi
794
+
795
+
796
+ def sample_size(decisions, units, targets):
797
+ """Before any readout: per question type (decisions) and task (units) and per target, whether its FIT decisions
798
+ (the groups outside CERT, about 70%) could certify the target at all, i.e. with every one of them accepted and
799
+ correct -> warnings for those that cannot."""
800
+ count = defaultdict(lambda: [0, 0]) # name -> [labelled decisions, FIT decisions]
801
+ for name, group in [(d["prim"], d["group"]) for d in decisions if d["prim"] != "multi"] + \
802
+ [(u["task"], u["group"]) for u in units]:
803
+ count[name][0] += 1
804
+ count[name][1] += not is_cert(group)
805
+ out = []
806
+ for name, (n, n_fit) in count.items():
807
+ what = {"verify": "claims", "extract": "fields"}.get(name, "questions")
808
+ for risk in sorted(targets):
809
+ need = accepted_needed(risk)
810
+ if n_fit >= need:
811
+ continue
812
+ falls = ("its answers report automated: null at this max_error" if name in TASKS else
813
+ f"basal-serve defers the automatic actions of act and tool on {name} at this max_error")
814
+ out.append(f"{name}: max_error {risk:g} needs >= {need} accepted FIT decisions without an error "
815
+ f"({accepted_needed(risk, 1)} with 1 error, {accepted_needed(risk, 2)} with 2); this file gives "
816
+ f"{n_fit} FIT decisions of {n} (FIT: about 70% of the groups); label about "
817
+ f"{max(1, math.ceil(need / 0.7) - n)} more {name} {what}. {name} will not be certified at "
818
+ f"max_error {risk:g}: {falls}")
819
+ return out
820
+
821
+
822
+ def cert_note(name, risk, x):
823
+ """A written threshold (entry x: confidence, cert_accepted, cert_error, cert_upper95) that CERT does not confirm:
824
+ its observed error is above the target, or too few accepted CERT decisions bring the upper bound below it. The
825
+ threshold is certified on FIT (a --keep-shipped one on the compared file's data) and stays; None when CERT confirms
826
+ it."""
827
+ if x.get("confidence") is None:
828
+ return None
829
+ where = "certified on FIT"
830
+ if x.get("kept"): # --keep-shipped: certified where the compared file was fitted, measured here
831
+ name, where = f"{name} (kept shipped threshold)", "certified on the compared file's data"
832
+ n = x.get("cert_accepted") or 0
833
+ e = round((x.get("cert_error") or 0.0) * n)
834
+ errs, need = f"{e} error{'' if e == 1 else 's'}", accepted_needed(risk)
835
+ if n == 0:
836
+ return (f"{name} at max_error {risk:g}: {where}; CERT accepts no decision at this threshold, so it "
837
+ f"cannot confirm it (0 errors would need >= {need} accepted CERT decisions)")
838
+ if e / n > risk:
839
+ return (f"{name} at max_error {risk:g}: {where}, but CERT has {n} accepted, {errs} "
840
+ f"({pct(e / n)}), above the target: the threshold does not hold on CERT; label more data before "
841
+ "relying on it")
842
+ if x.get("cert_upper95") is not None and x["cert_upper95"] > risk:
843
+ return (f"{name} at max_error {risk:g}: {where}; CERT has {n} accepted, {errs}, upper bound "
844
+ f"{100 * x['cert_upper95']:.2f}% > {100 * risk:g}%, too few to confirm on CERT (0 errors would need "
845
+ f">= {need} accepted CERT decisions)")
846
+ return None
847
+
848
+
849
+ def cert_notes(report, task_report, targets):
850
+ """cert_note for every written threshold of the decision types and the tasks."""
851
+ out = []
852
+ for risk in targets if report else ():
853
+ for t, x in ((report["targets"][risk]["fitted"].get("per_type")) or {}).items():
854
+ out.append(cert_note(t, risk, x))
855
+ for t, e in (task_report or {}).items():
856
+ for risk, x in e["targets"].items():
857
+ out.append(cert_note(t, float(risk), x))
858
+ return [x for x in out if x]
859
+
860
+
861
+ def no_threshold_reason(cs, risk, alpha=ALPHA, min_n=MIN_ACCEPTED, deff=1.0):
862
+ need = accepted_needed(risk, 0, alpha, min_n) # accepted decisions without an error
863
+ worth = "" if deff <= 1 else f" (worth {deff:.2f} times fewer independent ones: errors go together within groups)"
864
+ if effective(len(cs), 0, deff)[0] < need:
865
+ return (f"a {risk:g} bound needs at least {need} accepted FIT decisions without an error; FIT has {len(cs)}"
866
+ + worth)
867
+ lv = [(c, *effective(n, e, deff)) for c, n, e in levels(cs)]
868
+ c, n, e = lv[start_level(lv, risk, alpha, min_n)]
869
+ what = f"the top {n} FIT decisions" if deff <= 1 else f"FIT decisions worth {n} independent ones"
870
+ return (f"the first level tested (confidence {c:.4f}, {what}, {e} error{'' if e == 1 else 's'}) does not meet the "
871
+ f"bound (upper bound {cp_upper(e, n, alpha):.3f}), and the fixed sequence stops there")
872
+
873
+
874
+ def gate(cs, thr, deff=1.0):
875
+ """Coverage, error and upper bound of the decisions a threshold accepts (the bound on as many independent ones as
876
+ they are worth: effective)."""
877
+ acc = [ok for c, ok in cs if thr is not None and c >= thr]
878
+ e = len(acc) - sum(acc)
879
+ n_i, e_i = effective(len(acc), e, deff)
880
+ return dict(coverage=len(acc) / len(cs) if cs else None, accepted=len(acc), errors=e,
881
+ error=e / len(acc) if acc else None, upper95=cp_upper(e_i, n_i) if acc else None)
882
+
883
+
884
+ def certify(cf, cc, risk, deff=1.0, deff_c=1.0, veto=True, method=False):
885
+ """The one entry builder of a certified threshold (pooled, per type, per task): the fixed-sequence threshold of
886
+ the FIT decisions cf at target `risk`, with its FIT and CERT (cc) coverage, error and bound; withdrawn when CERT
887
+ refutes it (`veto`; the informational pooled entry is never withdrawn); deff / deff_c: the design effects of FIT
888
+ and CERT -> (entry, CERT gate at the threshold)."""
889
+ head = dict(method=METHOD) if method else {}
890
+ thr = threshold(cf, risk, deff=deff) if cf else None
891
+ g_cert = gate(cc, thr, deff_c)
892
+ if thr is None:
893
+ return dict(confidence=None, **head, reason=no_threshold_reason(cf, risk, deff=deff) if cf else
894
+ "no FIT decisions"), g_cert
895
+ g_fit = gate(cf, thr, deff)
896
+ entry = dict(confidence=thr, **head, fit_coverage=g_fit["coverage"], fit_error=g_fit["error"],
897
+ fit_upper95=g_fit["upper95"], cert_coverage=g_cert["coverage"], cert_error=g_cert["error"],
898
+ cert_upper95=g_cert["upper95"], cert_accepted=g_cert["accepted"])
899
+ return (withdrawn(entry, risk, deff_c) if veto else entry), g_cert
900
+
901
+
902
+ def floor(entries):
903
+ """The one floor of certified entries {target: entry} (in place): a confidence certified at a target error is
904
+ certified at every looser target too (its bound is below both), so a looser target never keeps a stricter
905
+ threshold than a tighter one: the fixed sequence stops at its first failing level, and at a loose target it starts
906
+ on a small top level and can stop on a few errors below it (5% at 0.9999 against 1% at 0.9587). The looser entry
907
+ becomes the tighter one, marked "floored_from" -> the targets whose entries changed."""
908
+ changed, ks = set(), sorted(entries, key=float)
909
+ for lo, hi in zip(ks, ks[1:]):
910
+ a, b = entries[lo], entries[hi]
911
+ if a.get("confidence") is not None and (b.get("confidence") is None or b["confidence"] > a["confidence"]):
912
+ entries[hi] = dict(a, floored_from=lo)
913
+ changed.add(hi)
914
+ return changed
915
+
916
+
917
+ def blend(T_fit, T_old, n, min_per_type):
918
+ """A temperature fitted on n < min_per_type decisions, blended in log space with the one it replaces in proportion
919
+ n / min_per_type (so the full fit takes over continuously at min_per_type) -> (temperature, weight of the fit)."""
920
+ w = n / min_per_type
921
+ return float(math.exp(w * math.log(T_fit) + (1 - w) * math.log(T_old))), w
922
+
923
+
924
+ def fit_temps(fit_rows, shipped_T, shipped_B, min_per_type, fmt, min_blend=MIN_BLEND, keep=(), memo=None):
925
+ """Temperatures per type (and per choice bucket for format 2) fitted on FIT rows where there are enough decisions,
926
+ blended with the shipped ones from min_blend decisions (0: never), else the shipped ones; the types in `keep`
927
+ (--keep-shipped) take the shipped ones as they are -> (temps, source, buckets, bucket source). memo: see
928
+ fit_temperature."""
929
+ temps, source = {}, {}
930
+ min_per_type = max(1, min_per_type) # 0 would fit a type that has no decision at all (max() of nothing)
931
+ for t in PRIMS:
932
+ rs = [r for r in fit_rows if r["prim"] == t]
933
+ if len(rs) >= min_per_type:
934
+ temps[t], source[t] = fit_temperature(rs, memo), f"fitted on {len(rs)} FIT decisions"
935
+ elif min_blend and len(rs) >= min_blend:
936
+ temps[t], w = blend(fit_temperature(rs, memo), shipped_T.get(t, 1.0), len(rs), min_per_type)
937
+ source[t] = (f"blended: {w:.0%} fitted on {len(rs)} FIT decisions, {1 - w:.0%} "
938
+ + ("shipped" if t in shipped_T else "default 1.0"))
939
+ elif t in shipped_T:
940
+ temps[t] = shipped_T[t]
941
+ source[t] = f"shipped ({len(rs)} FIT decisions < {min_per_type})" if rs else "shipped (no decisions)"
942
+ buckets, bsource = {}, {}
943
+ if fmt == 2:
944
+ for name, lo, hi in BUCKETS:
945
+ rs = [r for r in fit_rows if r["prim"] == "choice" and lo <= len(r["p"]) <= hi]
946
+ old = (shipped_B.get("choice") or {}).get(name)
947
+ if len(rs) >= min_per_type:
948
+ buckets.setdefault("choice", {})[name] = fit_temperature(rs, memo)
949
+ bsource[name] = f"fitted on {len(rs)} FIT decisions"
950
+ elif min_blend and len(rs) >= min_blend:
951
+ buckets.setdefault("choice", {})[name], w = blend(
952
+ fit_temperature(rs, memo), old if old is not None else temps.get("choice", 1.0), len(rs), min_per_type)
953
+ bsource[name] = (f"blended: {w:.0%} fitted on {len(rs)} FIT decisions, {1 - w:.0%} "
954
+ + ("shipped bucket" if old is not None else "type temperature"))
955
+ elif old is not None:
956
+ buckets.setdefault("choice", {})[name] = old
957
+ bsource[name] = f"shipped ({len(rs)} FIT decisions < {min_per_type})"
958
+ else:
959
+ bsource[name] = f"type temperature ({len(rs)} FIT decisions < {min_per_type})"
960
+ for t in keep: # with its thresholds: a shipped threshold is certified with the shipped temperature only
961
+ temps[t], source[t] = shipped_T[t], KEPT_SOURCE
962
+ if fmt == 2 and t == "choice":
963
+ buckets.pop("choice", None)
964
+ if shipped_B.get("choice"):
965
+ buckets["choice"] = dict(shipped_B["choice"])
966
+ for name, _, _ in BUCKETS:
967
+ bsource[name] = KEPT_SOURCE if name in (shipped_B.get("choice") or {}) else "type temperature (kept)"
968
+ return temps, source, buckets, bsource
969
+
970
+
971
+ def lofo(fit_rows, cert_rows, shipped_T, shipped_B, min_per_type, fmt, min_family=30, reference=None, draws=50, seed=0,
972
+ min_blend=MIN_BLEND, keep=()):
973
+ """Leave-one-family-out ECE per type: for every family the temperatures are fitted on the FIT decisions of the
974
+ other families and applied to its CERT decisions. mean / max over the families with >= min_family CERT decisions of
975
+ the type, mean_floor (the mean a perfectly calibrated predictor with the same confidences would show, `draws`
976
+ simulations: small families make the per-family ECE noisy), pooled over all held-out CERT decisions."""
977
+ fam = lambda r: r.get("family", "")
978
+ fams = sorted({fam(r) for r in fit_rows + cert_rows})
979
+ types = [t for t in PRIMS if any(r["prim"] == t for r in cert_rows)]
980
+ if len(fams) < 2:
981
+ return {t: dict(n=0, n_families=0, mean=None, pooled=None, reference=(reference or {}).get(t), regression=None,
982
+ reason='one family: give "family" on the lines or questions') for t in types}
983
+ per, pooled, rng = defaultdict(list), defaultdict(list), np.random.default_rng(seed)
984
+ memo = {} # each FIT row's NLLs, computed once for all the fits (fit_temperature)
985
+ for f in fams:
986
+ held = [r for r in cert_rows if fam(r) == f]
987
+ if not held:
988
+ continue
989
+ temps, _, buckets, _ = fit_temps([r for r in fit_rows if fam(r) != f], shipped_T, shipped_B,
990
+ min_per_type, fmt, min_blend, keep, memo)
991
+ for t in types:
992
+ cs = served([r for r in held if r["prim"] == t], temps, buckets)
993
+ pooled[t] += cs
994
+ if len(cs) >= min_family:
995
+ floor = float(np.mean([ece([(c, rng.random() < c) for c, _ in cs]) for _ in range(draws)]))
996
+ per[t].append((f, len(cs), ece(cs), floor))
997
+ out = {}
998
+ for t in types:
999
+ e, ref = dict(n=len(pooled[t]), n_families=len(per[t]), pooled=ece(pooled[t])), (reference or {}).get(t)
1000
+ if per[t]:
1001
+ worst = max(per[t], key=lambda x: x[2])
1002
+ e.update(mean=float(np.mean([x[2] for x in per[t]])), max=worst[2], worst_family=worst[0],
1003
+ mean_floor=float(np.mean([x[3] for x in per[t]])))
1004
+ else:
1005
+ e.update(mean=None, reason=f"no family has {min_family} CERT decisions of this type")
1006
+ e.update(reference=ref, regression=None if ref is None or e["mean"] is None else e["mean"] > ref)
1007
+ out[t] = e
1008
+ return out
1009
+
1010
+
1011
+ def set_probs(r, T):
1012
+ """P(label applies) of a multi row as served with the noul temperature T."""
1013
+ p = torch.tensor([[x, 1 - x] for x in r["p"]], dtype=torch.float32)
1014
+ return dict(zip(r["keys"], temper(p, T)[:, 0].tolist()))
1015
+
1016
+
1017
+ def set_metrics(prepared, fthr):
1018
+ """[(row, probs)] -> mean IoU, empty-set accuracy (gold empty, nothing selected) and false-empty rate (gold not
1019
+ empty, nothing selected) with this fallback_threshold (None: the default rule)."""
1020
+ iou, empty, false_empty = [], [], []
1021
+ for r, probs in prepared:
1022
+ s = r["set"]
1023
+ sel, _, _ = select_set(probs, s["objective"], s["threshold"], s["min"], s["max"], s["exclusive"], s["fallback"],
1024
+ fthr)
1025
+ S, G = set(sel), {r["keys"][i] for i in r["gold"]}
1026
+ iou.append(1.0 if not S and not G else len(S & G) / len(S | G))
1027
+ (false_empty if G else empty).append(not S)
1028
+ mean = lambda x: float(np.mean(x)) if x else None
1029
+ return dict(iou=mean(iou), empty_accuracy=mean(empty), false_empty=mean(false_empty))
1030
+
1031
+
1032
+ def fit_fallback(sets, T, min_per_set=30):
1033
+ """Multi rows -> {label set id: entry}: per label set the fallback_threshold of FALLBACK_GRID with the best mean
1034
+ IoU on FIT (None, the default rule, wins ties), and its CERT metrics next to the default's."""
1035
+ by = defaultdict(list)
1036
+ for r in sets:
1037
+ by[r["set"]["id"]].append(r)
1038
+ out = {}
1039
+ for sid, rs in by.items():
1040
+ fit_p = [(r, set_probs(r, T)) for r in rs if not is_cert(r["group"])]
1041
+ cert_p = [(r, set_probs(r, T)) for r in rs if is_cert(r["group"])]
1042
+ e = dict(fallback=rs[0]["set"]["fallback"], labels=rs[0]["keys"], n=len(rs), n_fit=len(fit_p),
1043
+ n_cert=len(cert_p))
1044
+ if len(fit_p) < max(1, min_per_set):
1045
+ out[sid] = dict(e, fallback_threshold=None, reason=f"{len(fit_p)} FIT questions < {max(1, min_per_set)}")
1046
+ continue
1047
+ best = max(FALLBACK_GRID, key=lambda t: set_metrics(fit_p, t)["iou"])
1048
+ fitted, default = set_metrics(cert_p, best), set_metrics(cert_p, None)
1049
+ accepted = bool(cert_p) and fitted["iou"] is not None and fitted["iou"] >= default["iou"]
1050
+ out[sid] = dict(e, fallback_threshold=best if accepted else None, fit_candidate=best,
1051
+ cert_accepted=accepted, method="mean IoU on FIT over a log grid (null: the default rule)",
1052
+ cert={**fitted, **{f"{k}_default": v for k, v in default.items()}})
1053
+ return out
1054
+
1055
+
1056
+ def per_type_thresholds(fit_rows, cert_rows, temps, buckets, risk, tempered=None, baseline=None, keep=()):
1057
+ """The certified threshold of every type on its own decisions, while one threshold pooled over the types moves
1058
+ with the temperatures of the others. A temperature keeps the order of a type's yes/no confidences (the top
1059
+ probability is monotone in T for two options), not of choice and score ones: with three or more options it can
1060
+ swap two decisions (logits [0, -3, -3] and [0, -2, -20]: 0.909 > 0.881 at T = 1, 0.403 < 0.512 at T = 10), and
1061
+ format-2 choice buckets have temperatures of their own. The levels are therefore ordered as served, with the
1062
+ temperatures fitted on the same FIT decisions. Decisions that share a group are counted as fewer independent ones
1063
+ when their errors correlate (icc on FIT). `tempered`: a Tempered of temps / buckets to reuse. A type in `keep`
1064
+ takes the threshold `baseline` certified for it (with the shipped temperature `temps` holds for it), measured on
1065
+ FIT and CERT."""
1066
+ tempered = tempered or Tempered(temps, buckets)
1067
+ out = {}
1068
+ for t in PRIMS:
1069
+ rf = [r for r in fit_rows if r["prim"] == t]
1070
+ if not rf and t not in keep:
1071
+ continue
1072
+ rc = [r for r in cert_rows if r["prim"] == t]
1073
+ cf, cc = tempered.cs(rf), tempered.cs(rc)
1074
+ rho, deff = design_effect(cf, [r["group"] for r in rf]) # FIT's rho, each side's own group sizes
1075
+ deff_c = design_effect_of([r["group"] for r in rc], rho)
1076
+ if t in keep: # FIT and CERT together test it (neither certified it), with their own design effect
1077
+ _, deff_all = design_effect(cf + cc, [r["group"] for r in rf + rc])
1078
+ out[t] = kept_entry(cf, cc, shipped_threshold(baseline, risk, t), risk, deff, deff_c, deff_all)
1079
+ else:
1080
+ out[t], _ = certify(cf, cc, risk, deff, deff_c)
1081
+ if rho:
1082
+ out[t].update(icc=rho, design_effect=deff)
1083
+ return out
1084
+
1085
+
1086
+ def kept_entry(cf, cc, thr, risk, deff=1.0, deff_c=1.0, deff_all=1.0):
1087
+ """--keep-shipped: the entry of a type's shipped threshold thr (certified on the compared file's data), with its
1088
+ coverage, error and bound on this file's FIT (cf) and CERT (cc) decisions; withdrawn (null: basal-serve defers)
1089
+ when they refute it at `risk`, as a fitted threshold CERT refutes (withdrawn). Neither split took part in
1090
+ certifying it, so both test it together, counted as the independent decisions they are worth (deff_all)."""
1091
+ if thr is None:
1092
+ return dict(confidence=None, kept="shipped", reason="the compared file has no threshold for this type at this "
1093
+ "max_error")
1094
+ g_fit, g_cert, g_all = gate(cf, thr, deff), gate(cc, thr, deff_c), gate(cf + cc, thr)
1095
+ entry = dict(confidence=thr, fit_coverage=g_fit["coverage"], fit_error=g_fit["error"], fit_upper95=g_fit["upper95"],
1096
+ cert_coverage=g_cert["coverage"], cert_error=g_cert["error"], cert_upper95=g_cert["upper95"],
1097
+ cert_accepted=g_cert["accepted"], kept="shipped")
1098
+ n, e = g_all["accepted"], g_all["errors"]
1099
+ if withdrawn(dict(confidence=thr, cert_accepted=n, cert_error=g_all["error"]), risk, deff_all)["confidence"] is None:
1100
+ entry = dict(entry, confidence=None, refuted=thr,
1101
+ reason=f"the compared file's threshold {thr:.4f}, but your FIT and CERT decisions refute it: {e} "
1102
+ f"error{'' if e == 1 else 's'} in {n} accepted, a one-sided 95% lower bound above {risk:g}")
1103
+ return entry
1104
+
1105
+
1106
+ def automated_gate(rows, tempered, cal, risk):
1107
+ """Share and error of the decisions basal-serve automates at max_error `risk` with calibration `cal` (rows tempered
1108
+ with its temperatures): each type at the threshold the server applies to it (server.certified: its own; a type
1109
+ without one is not automated)."""
1110
+ if not rows:
1111
+ return dict(coverage=None, error=None)
1112
+ acc = [ok for r, (c, ok) in zip(rows, tempered.cs(rows))
1113
+ if (thr := certified(cal, risk, r["prim"])) is not None and c >= thr]
1114
+ return dict(coverage=len(acc) / len(rows), error=(len(acc) - sum(acc)) / len(acc) if acc else None)
1115
+
1116
+
1117
+ def effective_gate(rows, temps, buckets, entry):
1118
+ """automated_gate of a fitted threshold entry (every type at its own certified threshold)."""
1119
+ return automated_gate(rows, Tempered(temps, buckets), {"thresholds": {"1.0": entry}}, 1.0)
1120
+
1121
+
1122
+ def served_gate(rows, temps, buckets, cal, risk):
1123
+ """automated_gate of a calibration as basal-serve applies it (its temperatures given as temps / buckets)."""
1124
+ return automated_gate(rows, Tempered(temps, buckets), cal, risk)
1125
+
1126
+
1127
+ def floor_thresholds(thresholds, targets):
1128
+ """floor() of the per-type entries and of the pooled ones of thresholds {target: entry} (in place) -> the targets
1129
+ whose entries changed."""
1130
+ keys, changed = [str(float(r)) for r in targets], set()
1131
+ for t in sorted({t for k in keys for t in (thresholds[k].get("per_type") or {})}):
1132
+ per = {k: ((thresholds[k].get("per_type") or {}).get(t) or {"confidence": None}) for k in keys}
1133
+ for k in floor(per):
1134
+ thresholds[k].setdefault("per_type", {})[t] = per[k]
1135
+ changed.add(k)
1136
+ pooled = {k: {x: v for x, v in thresholds[k].items() if x not in ("per_type", "pooled")} for k in keys}
1137
+ for k in floor(pooled):
1138
+ thresholds[k] = dict(pooled[k], **{x: thresholds[k][x] for x in ("per_type", "pooled") if x in thresholds[k]})
1139
+ changed.add(k)
1140
+ return changed
1141
+
1142
+
1143
+ def type_threshold(entry, q_type):
1144
+ """The threshold basal-serve applies to a question type: its own certified one, else None (the pooled one is
1145
+ never applied)."""
1146
+ return ((((entry or {}).get("per_type") or {}).get(q_type)) or {}).get("confidence")
1147
+
1148
+
1149
+ def conformal_p_min(p_gold, level):
1150
+ """Split conformal with the score 1 - p(gold): the k-th largest p(gold), k = ceil((n + 1) level); None when k > n
1151
+ (too few decisions for the level: the set is every option)."""
1152
+ k = math.ceil(round((len(p_gold) + 1) * level, 9))
1153
+ return sorted(p_gold, reverse=True)[k - 1] if k <= len(p_gold) else None
1154
+
1155
+
1156
+ def conformal_needed(level):
1157
+ """The fewest decisions of a type that give a coverage level a p_min (ceil((n + 1) level) <= n)."""
1158
+ n = 1
1159
+ while math.ceil(round((n + 1) * level, 9)) > n:
1160
+ n += 1
1161
+ return n
1162
+
1163
+
1164
+ def set_gate(rows, probs, p_min):
1165
+ """Coverage (the gold answer in the set), mean size and singleton share of the answer sets at p_min."""
1166
+ if not rows:
1167
+ return dict(coverage=None, mean_size=None, singleton=None)
1168
+ sets = [answer_set(p, p_min) for p in probs]
1169
+ return dict(coverage=float(np.mean([r["gold"] in s for r, s in zip(rows, sets)])),
1170
+ mean_size=float(np.mean([len(s) for s in sets])), singleton=float(np.mean([len(s) == 1 for s in sets])))
1171
+
1172
+
1173
+ def fit_conformal(fit_rows, cert_rows, temps, buckets, levels):
1174
+ """--conformal: per coverage level and type, p_min on the type's CERT decisions (as served with the fitted
1175
+ temperatures), with the coverage and size of the sets on CERT and, held out from p_min, on FIT."""
1176
+ by_type = {}
1177
+ for t in PRIMS:
1178
+ rf, rc = [r for r in fit_rows if r["prim"] == t], [r for r in cert_rows if r["prim"] == t]
1179
+ if rf or rc:
1180
+ by_type[t] = (rf, served_p(rf, temps, buckets), rc, served_p(rc, temps, buckets))
1181
+ out = {}
1182
+ for level in levels:
1183
+ per = {}
1184
+ for t, (rf, pf, rc, pc) in by_type.items():
1185
+ p_min = conformal_p_min([p[r["gold"]] for r, p in zip(rc, pc)], level)
1186
+ e = dict(p_min=p_min, n=len(rc))
1187
+ if p_min is None:
1188
+ e["reason"] = (f"{len(rc)} CERT decisions of this type, coverage {level:g} needs >= "
1189
+ f"{conformal_needed(level)}: the set is every option")
1190
+ g_c, g_f = set_gate(rc, pc, p_min), set_gate(rf, pf, p_min)
1191
+ e.update(cert_coverage=g_c["coverage"], cert_mean_size=g_c["mean_size"], fit_coverage=g_f["coverage"],
1192
+ fit_mean_size=g_f["mean_size"], fit_singleton=g_f["singleton"], fit_n=len(rf))
1193
+ per[t] = e
1194
+ out[str(float(level))] = dict(per_type=per)
1195
+ return dict(method=CONFORMAL_METHOD, levels=out)
1196
+
1197
+
1198
+ def row_problem(r):
1199
+ """Why a row (an engine readout, or a line of a --save-rows file) cannot enter the fit, None when it can: its
1200
+ probabilities must be finite numbers in [0, 1], one per option (at least two; multi: one per label), and its gold
1201
+ an option index (multi: a list of label indices)."""
1202
+ if not isinstance(r, dict) or r.get("prim") not in PRIMS + ("multi",):
1203
+ return "not a row of a decision type"
1204
+ p, g = r.get("p"), r.get("gold")
1205
+ if not isinstance(p, list) or len(p) < (1 if r["prim"] == "multi" else 2) or any(isinstance(x, bool) or not isinstance(x, (int, float))
1206
+ or not 0 <= x <= 1 for x in p): # NaN fails 0 <= x
1207
+ return "probabilities that are not finite numbers in [0, 1]"
1208
+ if r.get("keys") is not None and len(r["keys"]) != len(p):
1209
+ return f"{len(p)} probabilities for {len(r['keys'])} options"
1210
+ golds = g if r["prim"] == "multi" and isinstance(g, list) else [g]
1211
+ if r["prim"] != "multi" and isinstance(g, list) or any(isinstance(x, bool) or not isinstance(x, int)
1212
+ or not 0 <= x < len(p) for x in golds):
1213
+ return f"gold {g!r} is not an option index"
1214
+ return None
1215
+
1216
+
1217
+ def clean_rows(rows):
1218
+ """The one boundary of the rows (engine readouts through raw_rows, or the lines of a --save-rows file) -> (the rows
1219
+ that can enter the fit, "line N: why" of the others): row_problem."""
1220
+ kept, dropped = [], []
1221
+ for r in rows:
1222
+ why = row_problem(r)
1223
+ if why:
1224
+ dropped.append(f"line {r.get('line', '?') if isinstance(r, dict) else '?'}: {why}")
1225
+ else:
1226
+ kept.append(r)
1227
+ return kept, dropped
1228
+
1229
+
1230
+ def shipped_threshold(baseline, risk, t):
1231
+ """The compared file's own threshold for type t at max_error risk (thresholds[risk].per_type[t]), None when it has
1232
+ none. Unlike server.certified, never the pooled threshold of a format-1 file without per_type (the basal-1.5
1233
+ files): it was certified over all the types together, so kept per type it would become a certificate of each."""
1234
+ entry = ((baseline or {}).get("thresholds") or {}).get(str(float(risk))) or {}
1235
+ return ((entry.get("per_type") or {}).get(t) or {}).get("confidence")
1236
+
1237
+
1238
+ def check_keep(keep, baseline):
1239
+ """--keep-shipped: the types to keep, in PRIMS order; SystemExit when a type is not choice / noul / score, or the
1240
+ compared file has no temperature or no per-type threshold for it (a shipped threshold holds with its temperature
1241
+ only; shipped_threshold)."""
1242
+ keep = set(keep)
1243
+ if not keep:
1244
+ return ()
1245
+ if keep - set(PRIMS):
1246
+ raise SystemExit(f"--keep-shipped {','.join(sorted(keep - set(PRIMS)))}: give question types among "
1247
+ f"{', '.join(PRIMS)} (an act question counts as its base type)")
1248
+ shipped_T = (baseline or {}).get("temperature_per_prim") or {}
1249
+ for t in sorted(keep):
1250
+ if t not in shipped_T:
1251
+ raise SystemExit(f"--keep-shipped {t}: the compared calibration has no {t} temperature to keep "
1252
+ "(give --calibration FILE or --model; not with --no-calibration)")
1253
+ risks = [float(r) for r in (baseline.get("thresholds") or {})]
1254
+ if any(shipped_threshold(baseline, r, t) is not None for r in risks):
1255
+ continue
1256
+ if any(certified(baseline, r, t) is not None for r in risks):
1257
+ raise SystemExit(f"--keep-shipped {t}: the compared calibration has no {t} threshold of its own, only one "
1258
+ "pooled over all the types (a file written before per-type thresholds): it was not "
1259
+ f"certified on {t} decisions, so it is not kept as their certificate")
1260
+ raise SystemExit(f"--keep-shipped {t}: the compared calibration has no {t} threshold to keep (a file fitted "
1261
+ "on other option orders, another layout or another model loses its thresholds, as in "
1262
+ "basal-serve)")
1263
+ return tuple(t for t in PRIMS if t in keep)
1264
+
1265
+
1266
+ # the engines with a calibration file of their own, CALIBRATION.<engine>.json (server.calibration_name); the others
1267
+ # (fast, eager, mps, strix: the bf16 path) share CALIBRATION.json
1268
+ ENGINE_FILES = ("fp8", "nvfp4", "int8", "llamagraph", "vllm", "sglang", "mlx", "gguf", "ollama", "llamacpp", "tpu")
1269
+
1270
+
1271
+ def engine_family(engine):
1272
+ """The calibration file an engine name (calibration_name, or a file's "engine" field) stands for: its
1273
+ CALIBRATION.<engine>.json engine (a vLLM preset: vllm; llamagraph.<quant> and mlx.metal[.q8]: kept distinct),
1274
+ "bf16" for the engines of CALIBRATION.json, None when unknown."""
1275
+ if not engine or engine == "unknown":
1276
+ return None
1277
+ s = str(engine)
1278
+ head = s.split(".")[0]
1279
+ if head == "llamagraph" and "." in s:
1280
+ return s
1281
+ if s == "mlx.metal" or s.startswith("mlx.metal."):
1282
+ return s
1283
+ return head if head in ENGINE_FILES else "bf16"
1284
+
1285
+
1286
+ def file_engine(data, path):
1287
+ """The engine a compared calibration holds for (engine_family): its "engine" field (basal-calibrate writes it),
1288
+ else its file name (CALIBRATION.json and its .o<N> / .<layout> variants: bf16; CALIBRATION.<engine>...json: that
1289
+ engine); None when neither says (a file of another name)."""
1290
+ if data.get("engine"):
1291
+ return engine_family(data["engine"])
1292
+ m = re.fullmatch(r"CALIBRATION((?:\.[^.]+)*)\.json", Path(path).name if path else "")
1293
+ if not m:
1294
+ return None
1295
+ parts = m.group(1).split(".")[1:]
1296
+ if len(parts) >= 2 and parts[0] == "llamagraph" and parts[1] in ("fp8", "int8", "nvfp4"):
1297
+ return f"{parts[0]}.{parts[1]}"
1298
+ if len(parts) >= 2 and parts[0] == "mlx" and parts[1] == "metal":
1299
+ return "mlx.metal.q8" if len(parts) >= 3 and parts[2] == "q8" else "mlx.metal"
1300
+ return parts[0] if parts and parts[0] in ENGINE_FILES else "bf16"
1301
+
1302
+
1303
+ def check_keep_engine(keep, baseline, path, kind, quant, preset=None, llama_graph=False, mlx_metal=False):
1304
+ """--keep-shipped: SystemExit when the compared file holds for another engine than this run's (its thresholds were
1305
+ certified on that engine's probabilities, which a bf16 file's are not for GGUF or MLX); a warning when it does not
1306
+ say which engine."""
1307
+ if not keep or not baseline:
1308
+ return
1309
+ name = Path(path).name if path else "the compared calibration"
1310
+ have = file_engine(baseline, path)
1311
+ want = engine_family(calibration_name(kind, quant, preset, llama_graph, mlx_metal) or "fast")
1312
+ if have is None:
1313
+ print(f"warning: --keep-shipped: {name} does not say which engine it was fitted on (no \"engine\" field); its "
1314
+ "kept thresholds hold only on that engine's probabilities", file=sys.stderr)
1315
+ elif have != want:
1316
+ raise SystemExit(f"--keep-shipped: {name} holds for the {have} engine, this run reads the {want} one: its "
1317
+ "thresholds were certified on that engine's probabilities (compare with the file of this "
1318
+ "engine, or leave out --keep-shipped)")
1319
+
1320
+
1321
+ def kept_from(path, data):
1322
+ """fitted_on.kept_shipped_from: the compared file the kept types come from (its name, the sha256 of its bytes and
1323
+ its certified_on when it says), so that the written file names where their thresholds were certified."""
1324
+ out = dict(file=Path(path).name, sha256=hashlib.sha256(Path(path).read_bytes()).hexdigest())
1325
+ if isinstance(data.get("certified_on"), str):
1326
+ out["certified_on"] = data["certified_on"]
1327
+ return out
1328
+
1329
+
1330
+ def fit(rows, baseline, targets, min_per_type=50, fmt=1, min_family=30, reference=None, min_per_set=30,
1331
+ min_blend=MIN_BLEND, conformal=(), keep=()):
1332
+ """Rows with uncalibrated probabilities -> (calibration dict, report for the table). fmt 2: calibration file 2,
1333
+ with the choice temperatures per option-count bucket. Multi rows fit the fallback_threshold of their label set.
1334
+ Rows that cannot enter the fit (clean_rows: NaN probabilities, a gold out of range) are left out and reported.
1335
+ The types in `keep` (--keep-shipped, see check_keep) take the temperatures and thresholds of `baseline`."""
1336
+ rows, dropped = clean_rows(rows)
1337
+ if not rows:
1338
+ raise SystemExit("no decisions to fit: " + "; ".join(dropped[:3]))
1339
+ sets = [r for r in rows if r["prim"] == "multi"]
1340
+ rows = [r for r in rows if r["prim"] != "multi"]
1341
+ fit_rows = [r for r in rows if not is_cert(r["group"])]
1342
+ cert_rows = [r for r in rows if is_cert(r["group"])]
1343
+ shipped_T = baseline.get("temperature_per_prim", {})
1344
+ shipped_B = baseline.get("temperature_per_bucket", {}) if fmt == 2 else {}
1345
+ keep = check_keep(keep, baseline)
1346
+ temps, source, buckets, bsource = fit_temps(fit_rows, shipped_T, shipped_B, min_per_type, fmt, min_blend, keep)
1347
+ fitted, shipped = Tempered(temps, buckets), Tempered(shipped_T, shipped_B) # each row tempered once
1348
+ cs_fit, cs_cert = fitted.cs(fit_rows), fitted.cs(cert_rows)
1349
+ shipped_cert = shipped.cs(cert_rows)
1350
+ thresholds, report = {}, dict(types={}, targets={}, n_fit=len(fit_rows), n_cert=len(cert_rows), compared={},
1351
+ dropped=dropped)
1352
+ _, deff_pool = design_effect(cs_fit, [r["group"] for r in fit_rows])
1353
+ for risk in targets:
1354
+ entry, g_cert = certify(cs_fit, cs_cert, risk, deff_pool, veto=False, method=True) # informational
1355
+ entry["per_type"] = per_type_thresholds(fit_rows, cert_rows, temps, buckets, risk, fitted, baseline, keep)
1356
+ entry["pooled"] = POOLED_NOTE
1357
+ thresholds[str(float(risk))] = entry
1358
+ if (baseline.get("thresholds") or {}).get(str(float(risk))): # the compared file as basal-serve applies it
1359
+ report["compared"][str(float(risk))] = automated_gate(cert_rows, shipped, baseline, risk)
1360
+ old = ((baseline.get("thresholds") or {}).get(str(float(risk))) or {}).get("confidence")
1361
+ report["targets"][risk] = dict(shipped=old, shipped_cert=gate(shipped_cert, old) if old is not None else None,
1362
+ fitted=entry, fitted_cert=g_cert,
1363
+ shipped_per_type={t: c for t in PRIMS
1364
+ if (c := shipped_threshold(baseline, risk, t)) is not None})
1365
+ for k in floor_thresholds(thresholds, targets): # a floored target's figures, as served
1366
+ report["targets"][float(k)].update(fitted=thresholds[k], fitted_cert=gate(cs_cert, thresholds[k]["confidence"]))
1367
+ automated, automated_pooled, automated_error = {}, {}, {}
1368
+ for k, entry in thresholds.items():
1369
+ eff = automated_gate(cert_rows, fitted, {"thresholds": thresholds}, float(k))
1370
+ automated[k], automated_error[k] = eff["coverage"], eff["error"]
1371
+ automated_pooled[k] = gate(cs_cert, entry["confidence"])["coverage"] if cs_cert else None
1372
+ for t in PRIMS:
1373
+ rs = [r for r in rows if r["prim"] == t]
1374
+ if not rs:
1375
+ continue
1376
+ cert = [r for r in cert_rows if r["prim"] == t]
1377
+ # as served: a choice question of a format-2 file gets its option-count bucket temperature first
1378
+ fit_t = [r for r in rs if not is_cert(r["group"])]
1379
+ report["types"][t] = dict(n=len(rs), n_fit=len(rs) - len(cert), n_cert=len(cert),
1380
+ fit_groups=len({r["group"] for r in fit_t}),
1381
+ **dict(zip(("icc", "design_effect"),
1382
+ design_effect(fitted.cs(fit_t), [r["group"] for r in fit_t]))),
1383
+ accuracy=float(np.mean([ok for _, ok in served(rs, {})])),
1384
+ T_shipped=shipped_T.get(t), T=temps.get(t), source=source.get(t, "default 1.0"),
1385
+ ece_shipped=ece(shipped.cs(cert)), ece=ece(fitted.cs(cert)))
1386
+ if fmt == 2 and t == "choice": # format 2: a choice question takes its bucket's temperature first
1387
+ report["types"][t]["not_served"] = dict(shipped=buckets_cover(shipped_B), fitted=buckets_cover(buckets))
1388
+ gates = dict(ece_lofo=lofo(fit_rows, cert_rows, shipped_T, shipped_B, min_per_type, fmt, min_family, reference,
1389
+ min_blend=min_blend, keep=keep),
1390
+ automated_at=automated, automated_error=automated_error, automated_at_pooled=automated_pooled,
1391
+ min_family=min_family)
1392
+ report["gates"] = gates
1393
+ report["kept"] = list(keep)
1394
+ multi = fit_fallback(sets, temps.get("noul", 1.0), min_per_set) if sets else {}
1395
+ report["multi"] = multi
1396
+ extra = dict(gates=gates)
1397
+ if multi:
1398
+ extra["multi"] = {k: v for k, v in multi.items() if "reason" not in v}
1399
+ if conformal:
1400
+ extra["conformal"] = report["conformal"] = fit_conformal(fit_rows, cert_rows, temps, buckets, conformal)
1401
+ if fmt == 2:
1402
+ report["buckets"] = {}
1403
+ for name, lo, hi in BUCKETS:
1404
+ rs = [r for r in rows if r["prim"] == "choice" and lo <= len(r["p"]) <= hi]
1405
+ if rs:
1406
+ cert = [r for r in rs if is_cert(r["group"])]
1407
+ old = (shipped_B.get("choice") or {}).get(name)
1408
+ new = (buckets.get("choice") or {}).get(name)
1409
+ # as served: the bucket's temperature, else the type's (T_*_type: the type's stands in)
1410
+ report["buckets"][name] = dict(n=len(rs), n_cert=len(cert),
1411
+ T_shipped=old if old is not None else shipped_T.get("choice"),
1412
+ T_shipped_type=old is None,
1413
+ T=new if new is not None else temps.get("choice"), T_type=new is None,
1414
+ source=bsource[name],
1415
+ ece_shipped=ece(shipped.cs(cert)), ece=ece(fitted.cs(cert)))
1416
+ cal = {"prompt": 2, "temperature_per_prim": temps, "temperature_per_bucket": buckets,
1417
+ "temperature_source": dict(source, **{f"choice {k}": v for k, v in bsource.items()}),
1418
+ "thresholds": thresholds, **extra}
1419
+ return cal, report
1420
+ # (prompt 1 said, as a file 2 says 2: basal-serve refuses the file for a model of the other format at start-up)
1421
+ return dict(prompt=1, temperature_per_prim=temps, temperature_source=source, thresholds=thresholds, **extra), report
1422
+
1423
+
1424
+ def as_served(data, path, fmt=None):
1425
+ """The compared file as basal-serve reads it, checked before any readout: SystemExit where basal-serve refuses it
1426
+ at start-up (a temperature that is no finite number above 0, a bad bucket name, a file of another prompt format
1427
+ than fmt, the model's: check_calibration), and its temperatures as numbers (basal-serve reads "1.2" as 1.2; the
1428
+ fit blended and printed the text and failed after the whole readout). fmt None: the file's own format."""
1429
+ if not data:
1430
+ return data
1431
+ check_calibration(data, fmt if fmt is not None else data.get("prompt", 1), path)
1432
+ out = dict(data)
1433
+ prim, buckets = data.get("temperature_per_prim"), data.get("temperature_per_bucket")
1434
+ if isinstance(prim, dict):
1435
+ out["temperature_per_prim"] = {t: float(T) if t in QUESTION_TYPES else T for t, T in prim.items()}
1436
+ if isinstance(buckets, dict):
1437
+ out["temperature_per_bucket"] = {t: {b: float(T) for b, T in bs.items()} if t in QUESTION_TYPES else bs
1438
+ for t, bs in buckets.items()}
1439
+ return out
1440
+
1441
+
1442
+ def compared(md, kind, path, quant, orders, off, preset=None, layout="canonical", adapter=None, identity=None,
1443
+ fmt=None, served=None, llama_graph=False, mlx_metal=False):
1444
+ """The calibration to compare with and keep, as basal-serve would apply it with these option orders
1445
+ (server.load_calibration: the model's file for those orders when it ships one; a file fitted on other orders
1446
+ without its thresholds; with --adapter the adapter's file, else the model's without its thresholds) and, with
1447
+ `identity` = (model, revision, adapter identity) of the decisions, without the thresholds of a file fitted on
1448
+ another model, revision or adapter (as basal-serve keeps an own file: validate_baseline) -> (calibration, its file
1449
+ or None, why its thresholds were left out or None). --url to a server with --adapter (adapter None, the adapter's
1450
+ identity in `identity`): the model's file is the base model's, without its thresholds, as load_calibration keeps
1451
+ it in process. served: (snapshot, model_files digest) the identity's revision is checked on instead of md, when
1452
+ md is not that revision's snapshot (--url to a server that runs another revision: (None, its digest))."""
1453
+ if off or (md is None and not path):
1454
+ return {}, None, None
1455
+ if orders is None: # a server that does not report its orders: the file as it is
1456
+ f = calibration_file(md, kind, path, quant, preset, layout, llama_graph=llama_graph, mlx_metal=mlx_metal)
1457
+ data, why = (json.loads(read_text(f)) if f.exists() else {}), None
1458
+ else:
1459
+ data, f, why = load_calibration(md, kind, path, quant, orders, preset=preset, layout=layout, adapter=adapter,
1460
+ llama_graph=llama_graph, mlx_metal=mlx_metal)
1461
+ if why is None and identity is not None and data:
1462
+ imd, files = served if served is not None else (md, None)
1463
+ mismatch = identity_mismatch(data, *identity, md=imd, kind=kind, files=files)
1464
+ if mismatch:
1465
+ why, data = f"{f.name}: {mismatch}", {k: v for k, v in data.items() if k not in UNVALIDATED_OUT}
1466
+ if why is None and adapter is None and identity is not None and identity[2] and not path and data:
1467
+ why = f"{f.name} belongs to the base model, read with --adapter {identity[2]}"
1468
+ data = {k: v for k, v in data.items() if k not in UNVALIDATED_OUT}
1469
+ if why:
1470
+ print(f"warning: {why}: its thresholds are not compared or kept (as in basal-serve)", file=sys.stderr)
1471
+ return as_served(data, f, fmt), (f if f.exists() else None), why
1472
+
1473
+
1474
+ def task_rows(units, responses):
1475
+ """Labelled task decisions + the served task answers -> (rows {task, group, c: confidence, ok}, failed requests).
1476
+ An extract number that does not parse is left out: basal-serve never automates it."""
1477
+ rows, failed = [], {}
1478
+ for u in units:
1479
+ r = responses[u["req"]]
1480
+ if isinstance(r, Exception):
1481
+ failed[u["req"]] = f"line {u['line']}: {r}"
1482
+ continue
1483
+ a = (r.get("answers") or {}).get(u["name"])
1484
+ if not isinstance(a, dict):
1485
+ failed[(u["req"], u["name"])] = f"line {u['line']}, question {u['name']!r}: no answer"
1486
+ continue
1487
+ if u["task"] == "classify":
1488
+ conf, ok = a["confidence"], a["label"] == u["gold"]
1489
+ elif u["task"] == "verify":
1490
+ c = a["claims"][u["part"]]
1491
+ conf, ok = c["confidence"], c["verdict"] == u["gold"]
1492
+ else:
1493
+ f = a["fields"][u["part"]]
1494
+ if "error" in f:
1495
+ continue
1496
+ kind, gold = u["gold"]
1497
+ conf, ok = f["confidence"], field_correct(kind, f["value"], gold)
1498
+ if isinstance(conf, bool) or not isinstance(conf, (int, float)) or not 0 <= conf <= 1: # NaN is not in [0, 1]
1499
+ failed[(u["req"], u["name"], u["part"])] = f"line {u['line']}, question {u['name']!r}: confidence {conf!r}"
1500
+ continue
1501
+ rows.append(dict(task=u["task"], group=u["group"], c=float(conf), ok=bool(ok)))
1502
+ return rows, list(failed.values())
1503
+
1504
+
1505
+ def fit_tasks(rows, targets, shipped=None):
1506
+ """Task rows -> ({task: {target: threshold}} for the certified ones, report {task: ...}): the bound of the decision
1507
+ types on each task's FIT decisions, with coverage, error and bound on its CERT decisions; `shipped` (the task
1508
+ thresholds of the compared file, when the answers were served with its temperatures) is measured on CERT too."""
1509
+ thresholds, report = {}, {}
1510
+ for t in TASKS:
1511
+ rs = [r for r in rows if r["task"] == t]
1512
+ if not rs:
1513
+ continue
1514
+ cf = [(r["c"], r["ok"]) for r in rs if not is_cert(r["group"])]
1515
+ cc = [(r["c"], r["ok"]) for r in rs if is_cert(r["group"])]
1516
+ rho, deff = design_effect(cf, [r["group"] for r in rs if not is_cert(r["group"])])
1517
+ deff_c = design_effect_of([r["group"] for r in rs if is_cert(r["group"])], rho)
1518
+ e = dict(n=len(rs), n_fit=len(cf), n_cert=len(cc), accuracy=float(np.mean([r["ok"] for r in rs])),
1519
+ fit_groups=len({r["group"] for r in rs if not is_cert(r["group"])}), icc=rho, design_effect=deff,
1520
+ method=METHOD, targets={})
1521
+ for risk in targets:
1522
+ old = ((shipped or {}).get(t) or {}).get(str(float(risk)))
1523
+ if old is not None:
1524
+ e.setdefault("shipped", {})[str(float(risk))] = dict(confidence=old, cert=gate(cc, old))
1525
+ e["targets"][str(float(risk))], _ = certify(cf, cc, risk, deff, deff_c)
1526
+ floor(e["targets"]) # a looser target never keeps a stricter threshold
1527
+ thresholds.update({t: {k: x["confidence"] for k, x in e["targets"].items() if x["confidence"] is not None}}
1528
+ if any(x["confidence"] is not None for x in e["targets"].values()) else {})
1529
+ report[t] = e
1530
+ return thresholds, report
1531
+
1532
+
1533
+ def reference_values(ref):
1534
+ """--reference: a built-in name (basal-1.5) or a calibration file with gates.ece_lofo -> ({type: mean}, label)."""
1535
+ if ref is None:
1536
+ return None, None
1537
+ if ref in REFERENCE:
1538
+ return REFERENCE[ref], f"{ref} (4.5B): mean leave-one-family-out ECE on its calibration split"
1539
+ p = Path(ref)
1540
+ if not p.exists():
1541
+ raise SystemExit(f"--reference {ref}: not {' or '.join(REFERENCE)} and no such file")
1542
+ lf = (json.loads(read_text(p)).get("gates") or {}).get("ece_lofo") or {}
1543
+ vals = {t: v["mean"] for t, v in lf.items() if isinstance(v, dict) and v.get("mean") is not None}
1544
+ if not vals:
1545
+ raise SystemExit(f"--reference {ref}: the file has no gates.ece_lofo means")
1546
+ return vals, p.name
1547
+
1548
+
1549
+ # -- output ----------------------------------------------------------------------------------------------------------
1550
+ def pct(x):
1551
+ return "-" if x is None else f"{100 * x:.1f}%"
1552
+
1553
+
1554
+ def num(x, f="{:.3f}"):
1555
+ return "-" if x is None else f.format(x)
1556
+
1557
+
1558
+ def table(report):
1559
+ w = 52
1560
+ lines = ["", f"{'type':<7}{'n':>6}{'FIT':>6}{'CERT':>6}{'accuracy':>10} {'temperature shipped -> fitted':<{w}}"
1561
+ f"ECE on CERT shipped -> fitted"]
1562
+ for t, r in report["types"].items():
1563
+ ns = r.get("not_served") or {} # format 2, choice: buckets cover every option count
1564
+ temp = (f"{num(r['T_shipped'])}{' (not served: buckets)' if ns.get('shipped') else ''} -> {num(r['T'])}"
1565
+ f"{' (not served)' if ns.get('fitted') else ''}") + (
1566
+ "" if r["source"].startswith("fitted") else " (blended)" if r["source"].startswith("blended") else " (kept)")
1567
+ lines.append(f"{t:<7}{r['n']:>6}{r['n_fit']:>6}{r['n_cert']:>6}{r['accuracy']:>10.3f} {temp:<{w}}"
1568
+ f"{num(r['ece_shipped'])} -> {num(r['ece'])}")
1569
+ for name, r in (report.get("buckets") or {}).items(): # calibration file 2: choice per option-count bucket
1570
+ temp = (f"{num(r.get('T_shipped'))}{' (type)' if r.get('T_shipped_type') else ''} -> "
1571
+ f"{num(r['T'])}{' (type)' if r.get('T_type') else ''}")
1572
+ lines.append(f" {name:<9}{r['n']:>6}{'':>6}{r['n_cert']:>6}{'':>10} {temp:<{w}}"
1573
+ f"{num(r['ece_shipped'])} -> {num(r['ece'])}")
1574
+ lines += ["", f"max_error on CERT {'shipped: threshold':>18}{'coverage':>10}{'error':>8} "
1575
+ f"{'fitted: threshold':>17}{'coverage':>10}{'error':>8}{'bound':>8}"]
1576
+ for risk, r in report["targets"].items():
1577
+ s = r["shipped_cert"] or {}
1578
+ left = f"{risk:<20g}{num(r['shipped'], '{:.4f}'):>18}{pct(s.get('coverage')):>10}{pct(s.get('error')):>8} "
1579
+ f = r["fitted"]
1580
+ if f["confidence"] is None:
1581
+ lines.append(left + f"none: {f['reason']}")
1582
+ else:
1583
+ g = r["fitted_cert"]
1584
+ lines.append(left + f"{f['confidence']:>17.4f}{pct(g['coverage']):>10}{pct(g['error']):>8}"
1585
+ f"{pct(g['upper95']):>8}")
1586
+ lines.append("(one threshold pooled over the types, informational: basal-serve applies each type's own, as in "
1587
+ "\"automated on CERT\" below)")
1588
+ gates = report.get("gates") or {}
1589
+ if gates.get("ece_lofo"):
1590
+ lines += ["", f"LOFO ECE on CERT {'families':>9}{'mean':>8}{'floor':>8} {'max (family)':<26}{'pooled':>8}"
1591
+ f"{'reference':>11}"]
1592
+ for t, g in gates["ece_lofo"].items():
1593
+ if g.get("mean") is None:
1594
+ lines.append(f"{t:<18}{g['n_families']:>9} none: {g['reason']}")
1595
+ continue
1596
+ worst = f"{g['max']:.3f} ({str(g['worst_family'])[:16]})"
1597
+ mark = " REGRESSION" if g["regression"] else ""
1598
+ lines.append(f"{t:<18}{g['n_families']:>9}{g['mean']:>8.3f}{g['mean_floor']:>8.3f} {worst:<26}"
1599
+ f"{num(g['pooled']):>8}{num(g['reference']):>11}{mark}")
1600
+ if gates.get("automated_at"):
1601
+ compared = report.get("compared") or {}
1602
+ lines += ["", f"automated on CERT {'per-type thresholds':>20}{'error':>8} {'pooled (not applied)':>20}"
1603
+ + (" compared file, as served" if compared else "")]
1604
+ for k, v in gates["automated_at"].items():
1605
+ c = compared.get(k)
1606
+ lines.append(f"max_error {float(k):<9g} {pct(v):>20}{pct(gates['automated_error'].get(k)):>8} "
1607
+ f"{pct(gates['automated_at_pooled'].get(k)):>20}"
1608
+ + (f" {pct(c['coverage'])} at {pct(c['error'])} error" if c else ""))
1609
+ for risk, r in report["targets"].items():
1610
+ per = r["fitted"].get("per_type") or {}
1611
+ lines.append(f" {risk:g} per type: " + ", ".join(
1612
+ f"{t} " + (f"{x['confidence']:.4f} ({pct(x['cert_coverage'])})" if x.get("confidence") is not None
1613
+ else "none (defers)") + (" kept shipped" if x.get("kept") else "")
1614
+ for t, x in per.items()))
1615
+ if report.get("multi"):
1616
+ lines += ["", f"multi fallback {'label set':<18}{'n':>5}{'threshold':>11} {'IoU default -> fitted':<22}"
1617
+ f"{'empty acc.':<17}false-empty"]
1618
+ for sid, m in report["multi"].items():
1619
+ head = f"{str(m['fallback'])[:18]:<19}{sid:<18}{m['n']:>5}"
1620
+ if "reason" in m:
1621
+ lines.append(head + f" none: {m['reason']}")
1622
+ continue
1623
+ c = m["cert"]
1624
+ thr = "default" if m["fallback_threshold"] is None else f"{m['fallback_threshold']:.4g}"
1625
+ lines.append(head + f"{thr:>11} {num(c['iou_default']) + ' -> ' + num(c['iou']):<22}"
1626
+ f"{pct(c['empty_accuracy_default']) + ' -> ' + pct(c['empty_accuracy']):<17}"
1627
+ f"{pct(c['false_empty_default'])} -> {pct(c['false_empty'])}")
1628
+ if report.get("conformal"):
1629
+ lines += ["", f"answer sets {'type':<7}{'CERT':>6}{'p_min':>9}{'CERT cover':>12} {'FIT cover':>9}"
1630
+ f"{'mean size':>11}{'singleton':>11} (p_min on CERT, checked on FIT)"]
1631
+ for level, e in report["conformal"]["levels"].items():
1632
+ for t, x in e["per_type"].items():
1633
+ head = f"coverage {float(level):<9g} {t:<7}{x['n']:>6}"
1634
+ if x["p_min"] is None:
1635
+ lines.append(head + f" none: {x['reason']}")
1636
+ continue
1637
+ lines.append(head + f"{x['p_min']:>9.4f}{pct(x['cert_coverage']):>12} {pct(x['fit_coverage']):>9}"
1638
+ f"{num(x['fit_mean_size'], '{:.2f}'):>11}{pct(x['fit_singleton']):>11}")
1639
+ return "\n".join(lines)
1640
+
1641
+
1642
+ def task_table(report):
1643
+ lines = ["", f"{'task':<9}{'n':>6}{'FIT':>6}{'CERT':>6}{'accuracy':>10} {'max_error':<10}{'threshold':>10}"
1644
+ f"{'automated':>11}{'error':>8}{'bound':>8} (automated share, error and bound on CERT)"]
1645
+ for t, e in report.items():
1646
+ head = f"{t:<9}{e['n']:>6}{e['n_fit']:>6}{e['n_cert']:>6}{e['accuracy']:>10.3f} "
1647
+ for i, (risk, x) in enumerate(e["targets"].items()):
1648
+ left = head if i == 0 else " " * len(head)
1649
+ if x["confidence"] is None:
1650
+ lines.append(left + f"{float(risk):<10g}none: {x['reason']}")
1651
+ else:
1652
+ lines.append(left + f"{float(risk):<10g}{x['confidence']:>10.4f}{pct(x['cert_coverage']):>11}"
1653
+ f"{pct(x['cert_error']):>8}{pct(x['cert_upper95']):>8}")
1654
+ for risk, x in (e.get("shipped") or {}).items():
1655
+ g = x["cert"]
1656
+ lines.append(f"{'':<9}compared file's threshold {float(risk):g}: {x['confidence']:.4f}, automated "
1657
+ f"{pct(g['coverage'])}, error {pct(g['error'])}, bound {pct(g['upper95'])} on CERT")
1658
+ return "\n".join(lines)
1659
+
1660
+
1661
+ def clustered(name, n_fit, groups, rho=None, deff=None):
1662
+ """The note of a type or task with more FIT decisions than groups (None when each group has one): how strongly
1663
+ their errors go together within a group, and so how much the bound discounts them."""
1664
+ if not groups or n_fit <= groups:
1665
+ return None
1666
+ head = f"{name}: {n_fit} FIT decisions in {groups} groups ({n_fit / groups:.1f} per group)"
1667
+ if not rho:
1668
+ return head + ": their errors do not go together within a group (ICC 0), so the bound counts them as they are"
1669
+ return (head + f": their errors go together within a group (ICC {rho:.2f}), so the bound counts them as "
1670
+ f"{deff:.2f} times fewer independent decisions; certifying a target takes more labelled groups, not more "
1671
+ "decisions per group")
1672
+
1673
+
1674
+ def task_warnings(report, dropped=()):
1675
+ out = []
1676
+ for t, e in report.items():
1677
+ if e["n"] < RECOMMENDED:
1678
+ out.append(f"{t}: only {e['n']} labelled decisions: the bounds are loose")
1679
+ if clustered(t, e["n_fit"], e.get("fit_groups"), e.get("icc"), e.get("design_effect")):
1680
+ out.append(clustered(t, e["n_fit"], e.get("fit_groups"), e.get("icc"), e.get("design_effect")))
1681
+ for risk, x in e["targets"].items():
1682
+ if x["confidence"] is None:
1683
+ out.append(f"max_error {float(risk):g}: {t} has no certified threshold; its answers report "
1684
+ "automated: null at this max_error")
1685
+ elif cert_note(t, float(risk), x):
1686
+ out.append(cert_note(t, float(risk), x))
1687
+ for t in dropped:
1688
+ out.append(f"{t}: the shipped task threshold was certified with the shipped temperatures, which this file "
1689
+ f"changes; it is left out (add labelled {t} questions to certify one)")
1690
+ return out
1691
+
1692
+
1693
+ def warnings(report, targets):
1694
+ out = []
1695
+ n = report["n_fit"] + report["n_cert"]
1696
+ if n < RECOMMENDED:
1697
+ out.append(f"only {n} labelled decisions: the bounds are loose (a few hundred usually certify 5%)")
1698
+ if not report["n_fit"] or not report["n_cert"]:
1699
+ out.append("one side of the FIT / CERT split is empty: use more groups")
1700
+ if report.get("dropped"):
1701
+ out.append(f"{len(report['dropped'])} row(s) left out of the fit: " + "; ".join(report["dropped"][:3]))
1702
+ for t, r in report["types"].items():
1703
+ if clustered(t, r["n_fit"], r.get("fit_groups"), r.get("icc"), r.get("design_effect")):
1704
+ out.append(clustered(t, r["n_fit"], r.get("fit_groups"), r.get("icc"), r.get("design_effect")))
1705
+ if r["source"].startswith("fitted") and any(math.isclose(r["T"], x) for x in T_GRID):
1706
+ out.append(f"{t}: the fitted temperature is at the edge of the search ({r['T']:.2f}): too few errors "
1707
+ "or too few decisions to fit it; label more or raise --min-per-type")
1708
+ for b, r in (report.get("buckets") or {}).items():
1709
+ if r.get("T") is not None and not r.get("T_type") and str(r.get("source", "")).startswith("fitted") \
1710
+ and any(math.isclose(r["T"], x) for x in T_GRID):
1711
+ out.append(f"choice {b} options: the fitted temperature is at the edge of the search ({r['T']:.2f}): too "
1712
+ "few errors or too few decisions to fit it")
1713
+ for risk in targets:
1714
+ r = report["targets"][risk]
1715
+ for t, x in (r["fitted"].get("per_type") or {}).items():
1716
+ if x.get("confidence") is None:
1717
+ shipped = (r.get("shipped_per_type") or {}).get(t)
1718
+ out.append(f"max_error {risk:g}: {t} has no certified threshold; basal-serve defers every automatic "
1719
+ f"action of act and tool on {t} questions with this max_error"
1720
+ + (f" (the compared file certified {shipped:.4f}: --keep-shipped {t} keeps its {t} "
1721
+ "temperature and thresholds together)" if shipped is not None and not x.get("kept")
1722
+ else "")
1723
+ + (f" (the kept shipped threshold {x['refuted']:.4f} is refuted by your FIT and CERT "
1724
+ "decisions)" if x.get("kept") and x.get("refuted") is not None else ""))
1725
+ elif cert_note(t, risk, x):
1726
+ out.append(cert_note(t, risk, x))
1727
+ for t, g in ((report.get("gates") or {}).get("ece_lofo") or {}).items():
1728
+ if g.get("regression"):
1729
+ out.append(f"{t}: the leave-one-family-out ECE {g['mean']:.3f} is above the reference {g['reference']:.3f}")
1730
+ elif g.get("mean") is None:
1731
+ out.append(f"{t}: no leave-one-family-out ECE, 0 families tested ({g['reason']}); --strict does not check "
1732
+ f"{t}")
1733
+ for sid, m in (report.get("multi") or {}).items():
1734
+ if "reason" in m:
1735
+ out.append(f"multi label set {sid} (fallback {m['fallback']}): no fallback_threshold fitted "
1736
+ f"({m['reason']})")
1737
+ return out
1738
+
1739
+
1740
+ def regressions(report):
1741
+ """Types whose mean LOFO ECE is above the reference (--strict)."""
1742
+ return [t for t, g in ((report.get("gates") or {}).get("ece_lofo") or {}).items() if g.get("regression")]
1743
+
1744
+
1745
+ def summary(lines):
1746
+ """End of a run, on stderr: the targets the labels could not certify (sample_size) and the written thresholds that
1747
+ CERT does not confirm (cert_notes), also in the report above."""
1748
+ if lines:
1749
+ print("basal-calibrate: summary\n" + "\n".join(f" warning: {x}" for x in lines), file=sys.stderr)
1750
+
1751
+
1752
+ def strict_check(report, min_family):
1753
+ """--strict: on stderr, every type the family check did not test (no family with min_family CERT decisions of the
1754
+ type, or one family: it passes them), then status 1 when a type's mean LOFO ECE is above the reference."""
1755
+ for t, g in ((report.get("gates") or {}).get("ece_lofo") or {}).items():
1756
+ if g.get("mean") is None:
1757
+ why = (f"each needs >= {min_family} CERT decisions of the type" if g["reason"].startswith("no family")
1758
+ else g["reason"])
1759
+ print(f"--strict: {t}: 0 families tested ({why}); the family check did not run", file=sys.stderr)
1760
+ bad = regressions(report)
1761
+ if bad:
1762
+ print(f"--strict: leave-one-family-out ECE above the reference for {', '.join(bad)}", file=sys.stderr)
1763
+ sys.exit(1)
1764
+
1765
+
1766
+ def engine_name(kind, quant, preset=None, llama_graph=False, mlx_metal=False):
1767
+ """The engine a calibration file is for (its "engine" field): the name of its CALIBRATION.<engine>.json, else
1768
+ fast for the basal CUDA engine and the backend's own name (eager, mps, gguf)."""
1769
+ return calibration_name(kind, quant, preset, llama_graph, mlx_metal) or {"graph": "fast", "exit": "fast"}.get(
1770
+ kind, kind or "unknown"
1771
+ )
1772
+
1773
+
1774
+ def write_out(path, cal):
1775
+ """The calibration file at --out, whole or not at all (an interrupted write leaves the file that was there); a
1776
+ NaN or an infinity in it stops the tool, naming where, and writes nothing (basal-serve would read it as a
1777
+ threshold)."""
1778
+ try:
1779
+ write_json(path, cal, indent=1)
1780
+ except JSONLError as e:
1781
+ raise SystemExit(f"basal-calibrate: no calibration file written: {e}") from None
1782
+
1783
+
1784
+ def refit(a, targets, reference, reference_name):
1785
+ """--from-rows: the fit on the probabilities a --save-rows run recorded (no engine). The baseline is --calibration,
1786
+ else the file that run compared with."""
1787
+ try:
1788
+ lines = read_lines(a.input)
1789
+ except (OSError, UnicodeDecodeError) as e: # a binary file, a directory
1790
+ raise SystemExit(f"{a.input}: not a file written by basal-calibrate --save-rows ({type(e).__name__})") from None
1791
+ try:
1792
+ head = json.loads(lines[0])
1793
+ except (IndexError, ValueError):
1794
+ head = {}
1795
+ if not isinstance(head, dict) or head.get("basal_calibrate_rows") != 1:
1796
+ raise SystemExit(f"{a.input}: not a file written by basal-calibrate --save-rows")
1797
+ rows = []
1798
+ for i, x in enumerate(lines[1:], 2):
1799
+ if not x.strip():
1800
+ continue
1801
+ try:
1802
+ row = json.loads(x)
1803
+ except ValueError:
1804
+ row = None
1805
+ if not isinstance(row, dict):
1806
+ raise SystemExit(f"{a.input}: line {i} is not a row written by basal-calibrate --save-rows")
1807
+ rows.append(row)
1808
+ good, _ = clean_rows(rows) # what fit() keeps (it reports the others): the counts below
1809
+ small = sample_size(good, [], targets)
1810
+ for w in small:
1811
+ print(f"warning: {w}", file=sys.stderr)
1812
+ base_file = None if a.no_calibration else (
1813
+ Path(a.calibration) if a.calibration else (Path(head["baseline"]) if head.get("baseline") else None))
1814
+ baseline = as_served(json.loads(read_text(base_file)), base_file, head.get("fmt")) \
1815
+ if base_file is not None and base_file.exists() else {}
1816
+ why = validate_baseline(baseline, base_file.name, head.get("orders"), head.get("layout"),
1817
+ (head.get("model") if head.get("model") not in (None, "None") else None,
1818
+ head.get("revision"), head.get("adapter"), None, head.get("kind"),
1819
+ head.get("model_files"), head.get("model_content"), head.get("model_weights"))) \
1820
+ if baseline else None
1821
+ if baseline and not why and not a.calibration and head.get("baseline_why"):
1822
+ why = head["baseline_why"] # the run left out this file's thresholds (the base model's under --adapter)
1823
+ if why: # basal-serve's rule, for the model, orders and layout the rows were read with
1824
+ print(f"warning: {why} (the rows): its thresholds are not compared or kept (as in basal-serve)",
1825
+ file=sys.stderr)
1826
+ baseline = {k: v for k, v in baseline.items() if k not in UNVALIDATED_OUT}
1827
+ lg = bool(head.get("llama_graph", False))
1828
+ mm = bool(head.get("mlx_metal", False))
1829
+ check_keep_engine(check_keep(a.keep_shipped, baseline), baseline, base_file, head["kind"], head["quant"],
1830
+ head.get("vllm_preset"), lg, mm)
1831
+ cal, report = fit(rows, baseline, targets, a.min_per_type, head["fmt"], a.min_family, reference, a.min_per_set,
1832
+ a.min_blend, a.conformal, a.keep_shipped)
1833
+ cal["gates"]["ece_reference"] = reference_name
1834
+ cal["engine"] = engine_name(head["kind"], head["quant"], head.get("vllm_preset"), lg, mm)
1835
+ cal["fitted_on"] = dict(data=head["data"], decisions=sum(r["prim"] != "multi" for r in good),
1836
+ requests=head["requests"], fit=report["n_fit"], cert=report["n_cert"],
1837
+ per_type={t: r["n"] for t, r in report["types"].items()},
1838
+ multi=sum(r["prim"] == "multi" for r in good), date=datetime.date.today().isoformat(),
1839
+ model=head["model"], engine=head["engine"], orders=head["orders"],
1840
+ split="FIT 70% / CERT 30% by group", tool=f"basal-calibrate {__version__} (--from-rows)")
1841
+ cal["fitted_on"].update({k: head[k] for k in ("layout", "adapter", "revision", "model_files", "model_content",
1842
+ "model_weights") if head.get(k) is not None})
1843
+ if report["kept"]:
1844
+ cal["fitted_on"].update(kept_shipped=report["kept"], kept_shipped_from=kept_from(base_file, baseline))
1845
+ cal["certified_on"] = "CERT split of fitted_on.data (30% by group)"
1846
+ cal["baseline"] = str(base_file) if baseline else "none"
1847
+ print(table(report))
1848
+ notes = [f"{t}: task thresholds are not refitted from rows (they are certified on the answers as served); the "
1849
+ "refitted file leaves them out: fit them with the engine" for t in sorted(baseline.get("task_thresholds") or {})]
1850
+ for w in warnings(report, targets) + notes:
1851
+ print(f"warning: {w}")
1852
+ if a.report_only:
1853
+ print("\n--report-only: no file written")
1854
+ else:
1855
+ write_out(a.out, cal)
1856
+ print(f"\nwrote {a.out} (calibration file {head['fmt']}, engine {cal['engine']}, refitted from {a.input})")
1857
+ summary(small + cert_notes(report, None, targets))
1858
+ if a.strict:
1859
+ strict_check(report, a.min_family)
1860
+
1861
+
1862
+ # -- command line ----------------------------------------------------------------------------------------------------
1863
+ def parser():
1864
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
1865
+ ap.add_argument("input", help="labelled requests (JSONL, format above)")
1866
+ ap.add_argument("--out", default="CALIBRATION.custom.json", help="calibration file to write")
1867
+ ap.add_argument("--url", default=None,
1868
+ help="a running basal-serve started with --no-calibration (instead of the engine in process)")
1869
+ add_api_key(ap)
1870
+ ap.add_argument("--calibration", default=None,
1871
+ help="the calibration to compare with and to keep for small types (default: the file basal-serve "
1872
+ "loads for --model and the engine)")
1873
+ ap.add_argument("--no-calibration", dest="no_calibration", action="store_true",
1874
+ help="no shipped calibration to compare with (types below --min-per-type keep temperature 1.0)")
1875
+ ap.add_argument("--targets", default="0.01,0.05", help="max_error targets (comma-separated)")
1876
+ ap.add_argument("--conformal", default=None,
1877
+ help="coverage levels of the conformal answer sets (comma-separated, e.g. 0.8,0.9,0.95; default: "
1878
+ "none), fitted per type on CERT; basal-serve answers \"coverage\": L with \"answer_set\"")
1879
+ ap.add_argument("--min-per-type", dest="min_per_type", type=int, default=50,
1880
+ help="FIT decisions needed to fit a type's temperature")
1881
+ ap.add_argument("--min-blend", dest="min_blend", type=int, default=MIN_BLEND,
1882
+ help="a type (or bucket) with fewer FIT decisions than --min-per-type but at least this many gets "
1883
+ "the fitted temperature blended with the shipped one in proportion n / --min-per-type; 0 "
1884
+ "keeps the shipped one")
1885
+ ap.add_argument("--keep-shipped", dest="keep_shipped", default=None,
1886
+ help="question types (choice,noul,score) that keep the compared file's temperature and thresholds "
1887
+ "together instead of being fitted, e.g. a type these labels do not certify (with task "
1888
+ "questions only, the compared file's decision calibration is kept whole anyway)")
1889
+ ap.add_argument("--min-family", dest="min_family", type=int, default=30,
1890
+ help="CERT decisions of a type a family needs for its leave-one-family-out ECE")
1891
+ ap.add_argument("--min-per-set", dest="min_per_set", type=int, default=30,
1892
+ help="FIT multi questions a label set needs to fit its fallback_threshold")
1893
+ ap.add_argument("--reference", nargs="?", const="basal-1.5", default=None,
1894
+ help="LOFO ECE reference: basal-1.5 (the default value of the flag) or a calibration file with "
1895
+ "gates.ece_lofo")
1896
+ ap.add_argument("--save-rows", dest="save_rows", default=None,
1897
+ help="also write the uncalibrated probabilities of every decision (JSONL), to refit without a model")
1898
+ ap.add_argument("--from-rows", dest="from_rows", action="store_true",
1899
+ help="the input is a file written by --save-rows: refit on it without running any engine")
1900
+ ap.add_argument("--report-only", dest="report_only", action="store_true",
1901
+ help="print the report on your labelled requests (accuracy, ECE, certified thresholds, automated "
1902
+ "share) without writing a calibration file")
1903
+ ap.add_argument("--strict", action="store_true",
1904
+ help="exit with status 1 when a type's leave-one-family-out ECE is above --reference")
1905
+ ap.add_argument("--concurrency", type=positive, default=32, help="requests in flight (the engine batches them)")
1906
+ add_engine_args(ap.add_argument_group("engine (in process, as basal-serve)"))
1907
+ ap.set_defaults(model=None)
1908
+ return ap
1909
+
1910
+
1911
+ def options(a):
1912
+ """The checked targets, conformal levels (into a.conformal) and LOFO reference of the command line -> (targets,
1913
+ reference values, reference name)."""
1914
+ try:
1915
+ targets = sorted({float(x) for x in a.targets.split(",") if x.strip()})
1916
+ except ValueError:
1917
+ raise SystemExit(f"--targets {a.targets!r}: give numbers such as 0.01,0.05") from None
1918
+ if not targets or not all(1e-6 <= r < 1 for r in targets):
1919
+ raise SystemExit("--targets must lie between 1e-06 and 1 (a smaller max_error needs millions of decisions)")
1920
+ try:
1921
+ a.conformal = sorted({float(x) for x in (a.conformal or "").split(",") if x.strip()})
1922
+ except ValueError:
1923
+ raise SystemExit(f"--conformal {a.conformal!r}: give coverage levels such as 0.8,0.9,0.95") from None
1924
+ if not all(0 < x < 1 for x in a.conformal):
1925
+ raise SystemExit("--conformal levels must lie between 0 and 1")
1926
+ # (checked before any readout: --min-family 0 and --min-blend -1 failed with a traceback after the whole run)
1927
+ for flag, value, low in (("--min-family", a.min_family, 1), ("--min-blend", a.min_blend, 0),
1928
+ ("--min-per-type", a.min_per_type, 0), ("--min-per-set", a.min_per_set, 0)):
1929
+ if value < low:
1930
+ raise SystemExit(f"{flag} {value}: give {low} or more")
1931
+ a.keep_shipped = tuple(x.strip() for x in (a.keep_shipped or "").split(",") if x.strip())
1932
+ if a.calibration and not Path(a.calibration).exists():
1933
+ raise SystemExit(f"--calibration {a.calibration}: no such file")
1934
+ if a.strict and a.reference is None:
1935
+ raise SystemExit("--strict needs --reference (basal-1.5 or a calibration file with gates.ece_lofo)")
1936
+ return (targets, *reference_values(a.reference))
1937
+
1938
+
1939
+ def labelled(a, targets):
1940
+ """The labelled input -> (decision requests, decisions, task requests, task decisions, sample-size warnings), the
1941
+ warnings printed before any readout (a target these labels cannot certify)."""
1942
+ try:
1943
+ bodies, decisions, task_bodies, units = read(a.input)
1944
+ except InputError as e:
1945
+ raise SystemExit(str(e)) from None
1946
+ except OSError as e: # (no such file, a directory, no permission: a message, not a traceback)
1947
+ raise SystemExit(f"{a.input}: {e.strerror or type(e).__name__}") from None
1948
+ except UnicodeDecodeError:
1949
+ raise SystemExit(f"{a.input}: not a text file (UTF-8, or UTF-16 with its BOM)") from None
1950
+ print(f"basal-calibrate: {len(decisions)} labelled decisions in {len(bodies)} requests"
1951
+ + (f", {len(units)} labelled task decisions in {len(task_bodies)} requests" if units else ""),
1952
+ file=sys.stderr)
1953
+ small = sample_size(decisions, units, targets)
1954
+ for w in small:
1955
+ print(f"warning: {w}", file=sys.stderr)
1956
+ if units and a.url:
1957
+ raise SystemExit("task questions (classify / verify / extract) need the engine in process: their thresholds "
1958
+ "are certified on the answers as served with the fitted temperatures; give --model and --mode "
1959
+ "instead of --url, or leave the task questions out")
1960
+ return bodies, decisions, task_bodies, units, small
1961
+
1962
+
1963
+ def server_identity(c, entry, a):
1964
+ """--url --model <repo id>: the revision and model files fitted_on records are the ones the server serves
1965
+ (GET /v1/models, 2.8), not those of the revision the local cache resolves --model to (c.revision, c.files),
1966
+ which may be another one. c.served: what the compared file's identity is checked against when they differ (no
1967
+ snapshot of the server's revision here, its model_files digest). As before: --model that is no repo id (no
1968
+ revision), and a server that serves no cache snapshot (revision null). A server before 2.8 does not report them:
1969
+ the cache's are kept, with a warning."""
1970
+ local = c.revision
1971
+ if not local:
1972
+ return
1973
+ if "revision" not in entry:
1974
+ print(f"warning: the server does not report the revision it serves (basal-serve before 2.8): fitted_on "
1975
+ f"records {local[:12]}, the revision the local cache resolves {a.model} to; if the server runs another "
1976
+ "one, pass it with --revision", file=sys.stderr)
1977
+ return
1978
+ if not entry["revision"]:
1979
+ return
1980
+ c.revision = entry["revision"]
1981
+ c.files = entry.get("model_files") or (c.files if local == c.revision else None)
1982
+ if local != c.revision:
1983
+ c.served = (None, c.files)
1984
+ print(f"warning: the server serves revision {c.revision[:12]} of {c.model}, the local cache resolves "
1985
+ f"{a.model} to {local[:12]}: fitted_on records the server's, and the file compared with is the "
1986
+ f"cache's (--revision {c.revision} compares with the server's own)", file=sys.stderr)
1987
+
1988
+
1989
+ def http_context(a):
1990
+ """--url: the running server (it must serve raw probabilities) and the calibration to compare with -> the engine
1991
+ context (base URL, mode, engine text, adapter identity, orders, kind, quant, preset, model, revision, model files,
1992
+ prompt format, baseline and its file)."""
1993
+ import httpx
1994
+ base = a.url.rstrip("/").removesuffix("/v1/systemone").removesuffix("/v1/basal")
1995
+ if not (a.model or a.calibration or a.no_calibration):
1996
+ raise SystemExit("with --url, give --model (its shipped calibration is compared with and kept for small "
1997
+ "types), --calibration FILE or --no-calibration")
1998
+ try:
1999
+ r = httpx.get(base + "/v1/models", timeout=30, headers=headers(a.api_key))
2000
+ if refused(base, r.status_code, a.api_key):
2001
+ raise SystemExit(f"--url {a.url}: {refused(base, r.status_code, a.api_key)}")
2002
+ entry = uncalibrated(r.json()["models"][0], base)
2003
+ except (httpx.HTTPError, ValueError, KeyError, IndexError) as e:
2004
+ raise SystemExit(f"--url {a.url}: no basal server answers ({e})") from None
2005
+ c = argparse.Namespace(base=base, mode=a.mode or entry.get("mode"))
2006
+ c.adapter = entry.get("adapter") # the server's --adapter identity (name@sha256)
2007
+ c.engine = f"{c.mode} at {base}" + (f" --adapter {c.adapter.split('@')[0]}" if c.adapter else "")
2008
+ c.orders = entry.get("orders") # the server's option orders (servers before this field: unknown)
2009
+ c.llama_graph = entry.get("llama_graph") == "on" or str(c.mode or "").startswith("llamagraph")
2010
+ c.mlx_metal = entry.get("mlx_forward") == "metal" or str(c.mode or "").startswith("mlx.metal")
2011
+ if str(c.mode or "").startswith("llamagraph"):
2012
+ c.kind = "graph"
2013
+ c.quant = c.mode.split(".", 1)[1] if "." in c.mode else entry.get("quant")
2014
+ elif str(c.mode or "").startswith("mlx.metal"):
2015
+ c.kind = "mlx"
2016
+ parts = c.mode.split(".")
2017
+ c.quant = parts[2] if len(parts) >= 3 else entry.get("quant")
2018
+ else:
2019
+ c.kind, c.quant = MODES.get(c.mode, ("", None, False))[:2]
2020
+ c.preset = entry.get("vllm_preset") # --mode vllm: the server's preset (servers before 2.2.1: none)
2021
+ md = resolve(a.model, a.revision, metadata_only=True) if a.model else None
2022
+ c.model, c.revision = model_identity(a.model, md) if md is not None else (a.model or entry.get("name"), None)
2023
+ c.files = model_files_id(md, c.kind) if md is not None else None # (when the cache holds the weights too)
2024
+ # The serving process owns the weights. Its digest also binds a fit made with --url alone.
2025
+ c.content = entry.get("model_content") or (model_content_id(md, c.kind) if md is not None else None)
2026
+ c.weights = model_weights_id(md, c.kind) if md is not None else None # (and its tensors)
2027
+ c.served = None
2028
+ if md is not None: # the revision and model files the server serves (2.8)
2029
+ server_identity(c, entry, a)
2030
+ c.fmt = entry.get("prompt_format") or (model_format(md) if md is not None else 1)
2031
+ # the layout the server reads prompts in (servers before 2.4.1 and canonical ones do not say)
2032
+ a.layout = getattr(a, "layout", None) or entry.get("layout") or (model_layout(md) if md is not None
2033
+ else "canonical")
2034
+ # without --model the server's name stands in for the model (its --name, or the folder's name with "+adapter"): no
2035
+ # identity to check the compared file against
2036
+ identity = (c.model, c.revision, c.adapter) if md is not None else None
2037
+ c.baseline, c.base_file, c.base_why = compared(md, c.kind, a.calibration, c.quant, c.orders, a.no_calibration,
2038
+ c.preset, a.layout, fmt=c.fmt, identity=identity, served=c.served,
2039
+ llama_graph=c.llama_graph, mlx_metal=c.mlx_metal)
2040
+ return c
2041
+
2042
+
2043
+ def local_context(a):
2044
+ """The engine in process, as basal-serve starts it without calibration -> (server, engine context as
2045
+ http_context's)."""
2046
+ a.model = a.model or add_engine_args(argparse.ArgumentParser()).get_default("model") # basal-serve's
2047
+ refuse_lean_flex(a.lean, a.tree) # before default_mode, which resolves the model on CUDA GPUs without FA3
2048
+ mode = a.mode or default_mode(a.model, a.revision)
2049
+ srv = Server(argparse.Namespace(**{**vars(a), "mode": mode, "name": None, "calibration": None,
2050
+ "no_calibration": True, "log_decisions": None}))
2051
+ c = argparse.Namespace(mode=mode, kind=srv.kind, quant=a.quant or MODES[mode][1], fmt=srv.fmt, orders=srv.orders,
2052
+ preset=getattr(srv.backend, "preset", None), llama_graph=getattr(srv, "llama_graph", False),
2053
+ mlx_metal=getattr(srv, "mlx_metal", False))
2054
+ a.layout = srv.layout # --layout, else the model's basal.json "layout"
2055
+ c.model, c.revision = model_identity(a.model, srv.md)
2056
+ c.files = model_files_id(srv.md, srv.kind)
2057
+ c.content = model_content_id(srv.md, srv.kind)
2058
+ c.weights = model_weights_id(srv.md, srv.kind)
2059
+ c.adapter = srv.adapter.identity if srv.adapter else None
2060
+ c.baseline, c.base_file, c.base_why = compared(srv.md, srv.kind, a.calibration, c.quant, c.orders,
2061
+ a.no_calibration, c.preset, a.layout, srv.adapter,
2062
+ identity=(c.model, c.revision, c.adapter), fmt=c.fmt,
2063
+ llama_graph=c.llama_graph, mlx_metal=c.mlx_metal)
2064
+ c.engine = mode + (f" --quant {a.quant}" if a.quant else "") + (f" --gguf {Path(a.gguf).name}" if a.gguf else "") \
2065
+ + (f" --vllm-preset {c.preset}" if c.preset not in (None, "default") else "") \
2066
+ + (" --llama-graph on" if c.llama_graph else "") \
2067
+ + (" --mlx-forward metal" if c.mlx_metal else "") \
2068
+ + (f" --adapter {srv.adapter.name}" if srv.adapter else "")
2069
+ return srv, c
2070
+
2071
+
2072
+ def main(argv=None):
2073
+ from . import cli
2074
+ cli.warn_mixed_install() # basal 2.x next to basal-engine: one line
2075
+ a = parser().parse_args(argv)
2076
+ targets, reference, reference_name = options(a)
2077
+ if a.from_rows:
2078
+ return refit(a, targets, reference, reference_name)
2079
+ bodies, decisions, task_bodies, units, small = labelled(a, targets)
2080
+ fitted, c = {}, None # settle(): the decision rows, the file to serve and the report; c: the engine context
2081
+
2082
+ def settle(responses):
2083
+ """The decision part: the fit on the decision questions, else the compared calibration kept as it is."""
2084
+ rows, failed = raw_rows(decisions, responses)
2085
+ if failed:
2086
+ print(f"warning: {len(failed)} request(s) failed and are left out:\n " + "\n ".join(failed[:5]),
2087
+ file=sys.stderr)
2088
+ if decisions and not rows:
2089
+ raise SystemExit("no decisions to fit")
2090
+ if rows:
2091
+ check_keep_engine(check_keep(a.keep_shipped, c.baseline), c.baseline, c.base_file, c.kind, c.quant,
2092
+ c.preset, getattr(c, "llama_graph", False), getattr(c, "mlx_metal", False))
2093
+ cal, report = fit(rows, c.baseline, targets, a.min_per_type, c.fmt, a.min_family, reference, a.min_per_set,
2094
+ a.min_blend, a.conformal, a.keep_shipped)
2095
+ cal["gates"]["ece_reference"] = reference_name
2096
+ else: # task questions only: the temperatures and thresholds of the compared file stay as they are
2097
+ cal, report = {k: v for k, v in c.baseline.items() if k not in KEPT_OUT}, None
2098
+ fitted.update(rows=rows, failed=failed, cal=cal, report=report)
2099
+ return cal
2100
+
2101
+ if a.url:
2102
+ c = http_context(a)
2103
+ settle(asyncio.run(over_http(c.base + "/v1/systemone", bodies, a.concurrency, a.api_key)) if bodies else [])
2104
+ task_responses = []
2105
+ else:
2106
+ srv, c = local_context(a)
2107
+ _, task_responses = asyncio.run(two_passes(srv, bodies, task_bodies, a.concurrency, settle))
2108
+ finish(a, c, fitted, targets, small, len(bodies), units, len(task_bodies), task_responses)
2109
+
2110
+
2111
+ def finish(a, c, fitted, targets, small, n_bodies, units, n_task_bodies, task_responses):
2112
+ """After the readouts: the task thresholds, the saved rows, the file's provenance (fitted_on), the report and the
2113
+ file."""
2114
+ rows, failed, cal, report = fitted["rows"], fitted["failed"], fitted["cal"], fitted["report"]
2115
+ trows, tfailed = task_rows(units, task_responses) if units else ([], [])
2116
+ if tfailed:
2117
+ print(f"warning: {len(tfailed)} task request(s) failed and are left out:\n " + "\n ".join(tfailed[:5]),
2118
+ file=sys.stderr)
2119
+ if units and not trows:
2120
+ raise SystemExit("no task decisions to fit")
2121
+ shipped_tasks = c.baseline.get("task_thresholds") or {}
2122
+ # the compared file's task thresholds are measured on your data when the answers were served with its temperatures
2123
+ task_thr, task_report = fit_tasks(trows, targets, None if rows else shipped_tasks) if trows else ({}, {})
2124
+ # a shipped task threshold holds for the shipped temperatures: kept only when this file keeps them too
2125
+ dropped = sorted(t for t in shipped_tasks if t not in task_report) if rows else []
2126
+ kept = {} if rows else {t: v for t, v in shipped_tasks.items() if t not in task_report}
2127
+ if kept or task_thr:
2128
+ cal["task_thresholds"] = {**kept, **task_thr}
2129
+ if task_report:
2130
+ cal["task_gates"] = task_report
2131
+ if a.save_rows and rows:
2132
+ head = dict(basal_calibrate_rows=1, fmt=c.fmt, kind=c.kind, quant=c.quant, vllm_preset=c.preset,
2133
+ llama_graph=getattr(c, "llama_graph", False), mlx_metal=getattr(c, "mlx_metal", False),
2134
+ model=str(c.model), engine=c.engine, data=Path(a.input).name, requests=n_bodies - len(failed),
2135
+ baseline=str(c.base_file) if c.baseline else None, orders=c.orders)
2136
+ head.update(layout=a.layout, adapter=c.adapter, revision=c.revision, model_files=c.files,
2137
+ model_content=c.content, model_weights=c.weights,
2138
+ baseline_why=c.base_why if c.baseline else None) # (its thresholds left out: the refit too)
2139
+ # whole or not at all; a readout without a probability (a NaN) is written as null, which --from-rows drops
2140
+ # with the same reason (it wrote the token NaN, which is not JSON)
2141
+ write(a.save_rows, (finite(x) for x in [head] + rows))
2142
+ cal["engine"] = engine_name(c.kind, c.quant, c.preset, getattr(c, "llama_graph", False),
2143
+ getattr(c, "mlx_metal", False))
2144
+ good = clean_rows(rows)[0]
2145
+ cal["fitted_on"] = dict(data=Path(a.input).name, decisions=sum(r["prim"] != "multi" for r in good),
2146
+ requests=n_bodies - len(failed),
2147
+ fit=report["n_fit"] if report else 0, cert=report["n_cert"] if report else 0,
2148
+ per_type={t: r["n"] for t, r in report["types"].items()} if report else {},
2149
+ multi=sum(r["prim"] == "multi" for r in good),
2150
+ date=datetime.date.today().isoformat(), model=c.model, engine=c.engine,
2151
+ split="FIT 70% / CERT 30% by group", tool=f"basal-calibrate {__version__}")
2152
+ if c.revision:
2153
+ cal["fitted_on"]["revision"] = c.revision
2154
+ if c.revision and c.files: # basal-serve applies it to another revision with the same model files (model_files)
2155
+ cal["fitted_on"]["model_files"] = c.files
2156
+ if c.content: # a local folder: matched by its files, not its name (server.identity_mismatch)
2157
+ cal["fitted_on"]["model_content"] = c.content
2158
+ if c.weights: # ... and by every tensor, which model_content's samples of each file can miss
2159
+ cal["fitted_on"]["model_weights"] = c.weights
2160
+ if report and report["kept"]: # their temperatures and thresholds are the compared file's, not fitted here
2161
+ cal["fitted_on"].update(kept_shipped=report["kept"], kept_shipped_from=kept_from(c.base_file, c.baseline))
2162
+ if c.adapter: # basal-serve applies the file only with this adapter (calibration_mismatch)
2163
+ cal["fitted_on"]["adapter"] = c.adapter
2164
+ if task_report:
2165
+ cal["fitted_on"]["tasks"] = {t: e["n"] for t, e in task_report.items()}
2166
+ cal["fitted_on"]["task_requests"] = n_task_bodies - len(tfailed)
2167
+ if c.orders is not None: # basal-serve applies the file only to these orders (or loads CALIBRATION.o<N>.json)
2168
+ cal["fitted_on"]["orders"] = c.orders
2169
+ if getattr(a, "layout", None) not in (None, "canonical"): # basal-serve applies it only in this layout (2.4.1)
2170
+ cal["fitted_on"]["layout"] = a.layout
2171
+ cal["certified_on"] = "CERT split of fitted_on.data (30% by group)"
2172
+ cal["baseline"] = (str(a.calibration or f"{a.model}/{c.base_file.name}") if c.baseline else "none") + \
2173
+ (f" ({c.baseline['source_tag']})" if c.baseline.get("source_tag") else "")
2174
+ if not rows:
2175
+ cal["decision_calibration"] = (f"kept from {cal['baseline']} (no decision questions in the input)" if c.baseline
2176
+ else "none (no decision questions in the input, no calibration to keep)")
2177
+ if report:
2178
+ print(table(report))
2179
+ else:
2180
+ print(f"\ndecision questions: none; temperatures and thresholds kept from {cal['baseline']}")
2181
+ if task_report:
2182
+ print(task_table(task_report))
2183
+ for w in (warnings(report, targets) if report else []) + task_warnings(task_report, dropped):
2184
+ print(f"warning: {w}")
2185
+ if a.report_only:
2186
+ print("\n--report-only: no file written")
2187
+ else:
2188
+ write_out(a.out, cal)
2189
+ print(f"\nwrote {a.out} (calibration file {c.fmt}, engine {cal['engine']})\n"
2190
+ f" basal-serve --model {a.model or '<model>'} --mode {c.mode}"
2191
+ + (f" --adapter {a.adapter}" if getattr(a, "adapter", None) else "") + f" --calibration {a.out}")
2192
+ summary(small + cert_notes(report, task_report, targets))
2193
+ if a.strict and report:
2194
+ strict_check(report, a.min_family)
2195
+
2196
+
2197
+ if __name__ == "__main__":
2198
+ main()