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.
- basal/__init__.py +7 -0
- basal/adapter.py +420 -0
- basal/adapters.py +8 -0
- basal/agree.py +393 -0
- basal/attach.py +160 -0
- basal/attn512.py +132 -0
- basal/auth.py +194 -0
- basal/bench.py +367 -0
- basal/blockquant.py +227 -0
- basal/calibrate.py +2198 -0
- basal/chat.py +175 -0
- basal/cli.py +70 -0
- basal/client.py +8 -0
- basal/decision_log.py +189 -0
- basal/decision_rules.py +569 -0
- basal/decisions.py +158 -0
- basal/derive.py +98 -0
- basal/disconnect.py +85 -0
- basal/engine.py +6023 -0
- basal/evidence.py +133 -0
- basal/examples/choice.jsonl +8 -0
- basal/examples/complex.jsonl +5 -0
- basal/examples/labelled_tickets.jsonl +500 -0
- basal/examples/local_backend.py +34 -0
- basal/examples/noul.jsonl +8 -0
- basal/examples/questions.jsonl +20 -0
- basal/examples/score.jsonl +8 -0
- basal/examples/selfcheck_basal-omni-pico-Q8_0.json +1 -0
- basal/examples/selfcheck_basal-omni-pico.json +1 -0
- basal/examples/types_demo.py +74 -0
- basal/facts.py +497 -0
- basal/feedback.py +234 -0
- basal/file_identity.py +39 -0
- basal/finetune.py +321 -0
- basal/fit_decisions.py +944 -0
- basal/fla_configs.json +1822 -0
- basal/fold.py +206 -0
- basal/fonts/OFL-DMSans.txt +93 -0
- basal/fonts/OFL-SpaceGrotesk.txt +93 -0
- basal/fonts/dm-sans-latin-ext.woff2 +0 -0
- basal/fonts/dm-sans-latin.woff2 +0 -0
- basal/fonts/space-grotesk-latin-ext.woff2 +0 -0
- basal/fonts/space-grotesk-latin.woff2 +0 -0
- basal/fp8block.py +100 -0
- basal/gdn_graph.py +1792 -0
- basal/gemma4.py +726 -0
- basal/gemma4_graph.py +931 -0
- basal/gguf_export.py +497 -0
- basal/identity.py +217 -0
- basal/int8block.py +50 -0
- basal/interpolate.py +330 -0
- basal/jsonl.py +172 -0
- basal/lean.py +204 -0
- basal/llama_attn.py +252 -0
- basal/llama_attn_kernels.py +266 -0
- basal/llama_graph.py +587 -0
- basal/llama_kernels.py +593 -0
- basal/loadtest.py +189 -0
- basal/mcp_server.py +432 -0
- basal/media.py +138 -0
- basal/metrics.py +16 -0
- basal/mlx_attn_kernels.py +1057 -0
- basal/mlx_forward.py +326 -0
- basal/mlx_kernels.py +543 -0
- basal/mlx_metal.py +510 -0
- basal/navcut.py +283 -0
- basal/navigate.py +646 -0
- basal/navtree.py +397 -0
- basal/nvfp4.py +245 -0
- basal/ordercheck.py +165 -0
- basal/pdf.py +183 -0
- basal/prepared.py +355 -0
- basal/presets.py +8 -0
- basal/prompt.py +462 -0
- basal/rank.py +373 -0
- basal/readout.py +121 -0
- basal/request.py +327 -0
- basal/response_cache.py +105 -0
- basal/router.py +1551 -0
- basal/router_ui.html +902 -0
- basal/router_ui.py +277 -0
- basal/run.py +376 -0
- basal/selfcheck.py +215 -0
- basal/server.py +5279 -0
- basal/sets.py +214 -0
- basal/signals.py +28 -0
- basal/state_disk.py +942 -0
- basal/strix.py +505 -0
- basal/synth.py +92 -0
- basal/tasks.py +848 -0
- basal/textio.py +21 -0
- basal/think.py +390 -0
- basal/tools.py +171 -0
- basal/tpu.py +336 -0
- basal/tpu_kernels.py +129 -0
- basal/trace.py +125 -0
- basal/ui.html +861 -0
- basal/ui.py +526 -0
- basal/varloop.py +813 -0
- basal/varloop_graph.py +1377 -0
- basal/varloop_kernels.py +907 -0
- basal/viz.html +660 -0
- basal/viz.py +375 -0
- basal/vllm_unified.py +100 -0
- basal_engine-3.0.3.dist-info/METADATA +416 -0
- basal_engine-3.0.3.dist-info/RECORD +111 -0
- basal_engine-3.0.3.dist-info/WHEEL +5 -0
- basal_engine-3.0.3.dist-info/entry_points.txt +21 -0
- basal_engine-3.0.3.dist-info/licenses/LICENSE +202 -0
- basal_engine-3.0.3.dist-info/licenses/NOTICE +34 -0
- basal_engine-3.0.3.dist-info/top_level.txt +1 -0
basal/fit_decisions.py
ADDED
|
@@ -0,0 +1,944 @@
|
|
|
1
|
+
"""basal-fit-decisions (experimental): fit decision rules on your own labelled requests, as a running basal-serve
|
|
2
|
+
answers them, and report how they do on data the fit never saw.
|
|
3
|
+
|
|
4
|
+
basal-fit-decisions fit labelled.jsonl --url http://127.0.0.1:8000 --out RULES.json --report REPORT.json
|
|
5
|
+
basal-fit-decisions fit train.jsonl --test test.jsonl --url http://127.0.0.1:8000 --save-rows rows.jsonl
|
|
6
|
+
basal-fit-decisions fit --from-rows rows.jsonl # again, offline, from the saved probabilities
|
|
7
|
+
basal-fit-decisions evaluate RULES.json new.jsonl --url http://127.0.0.1:8000
|
|
8
|
+
|
|
9
|
+
Input (JSONL): basal-calibrate's labelled requests, one /v1/systemone request per line, whose questions are noul or
|
|
10
|
+
score questions with their correct answer in "gold" and the answer space they belong to in "answer_space":
|
|
11
|
+
{"id": "t-17", "state": "...", "group": "customer-17",
|
|
12
|
+
"questions": {"late": {"type": "noul", "instructions": "...", "answer_space": "late-payment", "gold": "yes"},
|
|
13
|
+
"urg": {"type": "score", "instructions": "...", "criteria": ["low", "mid", "high"],
|
|
14
|
+
"answer_space": "urgency", "gold": 2}}}
|
|
15
|
+
An answer space is one question asked of many states (its rule is fitted on all of them); every question of a space
|
|
16
|
+
must be the same question (type, language, instructions, options and option_keys: decision_rules.schema_hash) asked
|
|
17
|
+
the same way (facts, early_exit): two schemas in one space are an error, and a space asked in two ways gets no rule.
|
|
18
|
+
gold and group read as basal-calibrate reads them (group: on the question or the line, else the line's id, else
|
|
19
|
+
the line). Refused, so that nothing is dropped quietly: another question type, ask_if / depends_on, media, think,
|
|
20
|
+
a question without answer_space or gold, and any request the server does not answer.
|
|
21
|
+
|
|
22
|
+
Collection (--url): every request is sent to the server as it will be served (the probabilities after its option
|
|
23
|
+
orders and temperatures, so a server with its calibration, without --think), --concurrency 1 by default; the
|
|
24
|
+
inference signature of GET /v1/models (decision_rules.inference_signature) is read before and after, and must not
|
|
25
|
+
change. A server whose weights it cannot identify is refused before any request (--mode ollama / llamacpp, or a GGUF
|
|
26
|
+
file without its content digest: decision_rules.check_backend). A server without --deterministic can answer a
|
|
27
|
+
request slightly differently under load: warned, and recorded in the file, as are its serving numerics (the GPU and
|
|
28
|
+
the resolved graph shapes, which are not in the signature: evaluate warns when they differ). --save-rows keeps the
|
|
29
|
+
collected probabilities; --from-rows fits or evaluates from them without a server.
|
|
30
|
+
|
|
31
|
+
Method (fit):
|
|
32
|
+
* split by a hash of the group (a group is never on two sides; the labels play no part): FIT / GATE / FINAL
|
|
33
|
+
60 / 20 / 20, or with --test FIT / GATE 80 / 20 of the training file and FINAL = the test file, which must share
|
|
34
|
+
no id and no group with it;
|
|
35
|
+
* per answer space, on FIT: a noul space needs at least 20 groups and both answers among its golds; a threshold
|
|
36
|
+
from an exact sweep of every breakpoint between its P(true) values (accuracy; equally good thresholds: the one
|
|
37
|
+
nearest 0.5) is compared with the baseline (P(true) >= P(false)) in 5 grouped folds (each fold's threshold swept on
|
|
38
|
+
the other four); a score space needs at least 20 groups, and the expected level rounded half up is compared with
|
|
39
|
+
the argmax level the same way. The change is chosen only with strictly more correct out-of-fold decisions (a tie
|
|
40
|
+
keeps the baseline), and its rule is then fitted on the whole of FIT;
|
|
41
|
+
* retention, on GATE: a one-sided paired bootstrap of the accuracy gain, --draws resamples of whole groups,
|
|
42
|
+
p = (1 + #{gain* <= 0}) / (draws + 1), Holm across the tests at --alpha. --retention bundle (default): one test per
|
|
43
|
+
type over the GATE decisions of all its changed spaces, all kept or all back to the baseline; per-space: one test
|
|
44
|
+
per changed space. A refused change keeps the baseline, with the reason in its "fit";
|
|
45
|
+
* the rules file is written, read back (decision_rules.load) and then reported once on FINAL: per space and in
|
|
46
|
+
total the decisions, groups, baseline and rules accuracy, the paired gain with its two-sided 95% bootstrap interval,
|
|
47
|
+
wins and losses (score: also the mean absolute error of each and of the expected level).
|
|
48
|
+
"""
|
|
49
|
+
import argparse
|
|
50
|
+
import asyncio
|
|
51
|
+
import datetime
|
|
52
|
+
import hashlib
|
|
53
|
+
import json
|
|
54
|
+
import math
|
|
55
|
+
import sys
|
|
56
|
+
import zlib
|
|
57
|
+
from collections import defaultdict
|
|
58
|
+
from pathlib import Path
|
|
59
|
+
|
|
60
|
+
from . import __version__
|
|
61
|
+
from . import decision_rules as dr
|
|
62
|
+
from .cli import add_api_key, headers, positive, refused
|
|
63
|
+
from .jsonl import JSONLError, read_lines, write, write_json
|
|
64
|
+
|
|
65
|
+
ROWS_FORMAT = "basal.decision_rows/1"
|
|
66
|
+
REPORT_FORMAT = "basal.decision_rules.report/1"
|
|
67
|
+
METRIC = "accuracy"
|
|
68
|
+
MIN_GROUPS = 20 # FIT groups an answer space needs to be fitted
|
|
69
|
+
FOLDS = 5
|
|
70
|
+
SPLIT = (0.6, 0.8) # FIT below the first, GATE below the second, FINAL above (no --test)
|
|
71
|
+
SPLIT_TEST = 0.8 # with --test: FIT below, GATE above
|
|
72
|
+
DRAWS, ALPHA = 10_000, 0.05
|
|
73
|
+
LABELLED = ("gold", "group", "family", "answer_space", "decision_rule") # question fields that are not sent
|
|
74
|
+
LINE_FIELDS = ("id", "group", "family") # line fields that are not sent
|
|
75
|
+
ROW_KEYS = ("part", "line", "id", "question", "answer_space", "type", "schema_hash", "keys", "gold", "group",
|
|
76
|
+
"explicit_group", "request", "p")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class FitError(ValueError):
|
|
80
|
+
"""Input, data or a server answer the fitter refuses: the run stops with its message."""
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def problems(errors, what):
|
|
84
|
+
more = f"\n ... and {len(errors) - 20} more" if len(errors) > 20 else ""
|
|
85
|
+
return FitError(f"{what}: {len(errors)} problem(s)\n " + "\n ".join(errors[:20]) + more)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
# -- input ---------------------------------------------------------------------------------------------------------
|
|
89
|
+
def strict_json(line):
|
|
90
|
+
"""One JSON line; a key given twice in an object is a ValueError (json keeps the last one: a labelled question
|
|
91
|
+
or a row's field would be dropped without a word)."""
|
|
92
|
+
return json.loads(line, object_pairs_hook=dr._no_duplicates)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def space_ok(s):
|
|
96
|
+
return dr._id_ok(s) and not s.startswith(dr.BUILTIN_PREFIX)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def served_state(rec):
|
|
100
|
+
"""The state basal-serve reads the request's questions over: with "facts": "auto", the facts appended (the
|
|
101
|
+
language of its questions is detected on it)."""
|
|
102
|
+
state = rec["state"]
|
|
103
|
+
if rec.get("facts") != "auto":
|
|
104
|
+
return state
|
|
105
|
+
from .facts import MAX_CHARS, inject
|
|
106
|
+
text = state if isinstance(state, str) else json.dumps(state, ensure_ascii=False)
|
|
107
|
+
return inject(text) if len(text) <= MAX_CHARS else text # (longer: the server refuses it)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def read_labelled(path, part):
|
|
111
|
+
"""Labelled JSONL -> (requests to send, decisions). Raises FitError listing every problem with its line."""
|
|
112
|
+
from .calibrate import gold_index
|
|
113
|
+
from .server import to_items
|
|
114
|
+
errors, bodies, decisions = [], [], []
|
|
115
|
+
for n, line in enumerate(read_lines(path), 1):
|
|
116
|
+
if not line.strip():
|
|
117
|
+
continue
|
|
118
|
+
try:
|
|
119
|
+
rec = strict_json(line)
|
|
120
|
+
except ValueError as e:
|
|
121
|
+
errors.append(f"line {n}: not JSON ({getattr(e, 'msg', e)})")
|
|
122
|
+
continue
|
|
123
|
+
if not isinstance(rec, dict) or "state" not in rec or not isinstance(rec.get("questions"), dict) \
|
|
124
|
+
or not rec["questions"]:
|
|
125
|
+
errors.append(f'line {n}: a request needs "state" and a non-empty "questions" object')
|
|
126
|
+
continue
|
|
127
|
+
where = f"line {n}" + (f" (id {rec['id']})" if rec.get("id") is not None else "")
|
|
128
|
+
if rec.get("facts", "off") not in dr.FACTS:
|
|
129
|
+
errors.append(f'{where}: facts must be "off" or "auto"')
|
|
130
|
+
continue
|
|
131
|
+
if rec.get("media") is not None or rec.get("images") is not None:
|
|
132
|
+
errors.append(f"{where}: requests with media are not supported by decision rules")
|
|
133
|
+
continue
|
|
134
|
+
if rec.get("think", "off") != "off":
|
|
135
|
+
errors.append(f'{where}: decision rules are fitted on answers without think ("think": "off")')
|
|
136
|
+
continue
|
|
137
|
+
body = {k: v for k, v in rec.items() if k not in LINE_FIELDS}
|
|
138
|
+
body["questions"] = {}
|
|
139
|
+
try:
|
|
140
|
+
state = served_state(rec)
|
|
141
|
+
except Exception as e: # noqa: BLE001 (a state the facts cannot read: the server would refuse it too)
|
|
142
|
+
errors.append(f"{where}: {e}")
|
|
143
|
+
continue
|
|
144
|
+
for name, q in rec["questions"].items():
|
|
145
|
+
at = f"{where}, question {name!r}"
|
|
146
|
+
if not isinstance(q, dict):
|
|
147
|
+
errors.append(f"{at}: not an object")
|
|
148
|
+
continue
|
|
149
|
+
t = q.get("type", "choice")
|
|
150
|
+
if t not in dr.TYPES:
|
|
151
|
+
errors.append(f"{at}: type {t!r} (decision rules apply to noul and score questions)")
|
|
152
|
+
continue
|
|
153
|
+
if "ask_if" in q or "depends_on" in q:
|
|
154
|
+
errors.append(f"{at}: ask_if / depends_on are not supported by decision rules")
|
|
155
|
+
continue
|
|
156
|
+
if "gold" not in q:
|
|
157
|
+
errors.append(f'{at}: no "gold" answer')
|
|
158
|
+
continue
|
|
159
|
+
space = q.get("answer_space")
|
|
160
|
+
if not isinstance(space, str) or not space_ok(space):
|
|
161
|
+
errors.append(f'{at}: "answer_space" must name its answer space (a non-empty printable string of at '
|
|
162
|
+
f"most {dr.MAX_ID} characters, not starting with {dr.BUILTIN_PREFIX!r})")
|
|
163
|
+
continue
|
|
164
|
+
clean = {k: v for k, v in q.items() if k not in LABELLED}
|
|
165
|
+
try:
|
|
166
|
+
item = to_items(state, {name: clean}, 255, force_lang=rec.get("lang"))[0]
|
|
167
|
+
gold = gold_index(q, item)
|
|
168
|
+
except (ValueError, KeyError, TypeError) as e:
|
|
169
|
+
errors.append(f"{at}: {str(e).removeprefix(f'question {name!r}: ')}")
|
|
170
|
+
continue
|
|
171
|
+
body["questions"][name] = clean
|
|
172
|
+
explicit = next((x for x in (q.get("group"), rec.get("group"), rec.get("id")) if x is not None), None)
|
|
173
|
+
decisions.append(dict(part=part, line=n, id=None if rec.get("id") is None else str(rec["id"]),
|
|
174
|
+
question=name, answer_space=space, type=t, schema_hash=dr.schema_hash(item),
|
|
175
|
+
keys=[str(k) for k in item["keys"]], gold=gold,
|
|
176
|
+
group=str(n) if explicit is None else str(explicit),
|
|
177
|
+
explicit_group=explicit is not None, req=len(bodies)))
|
|
178
|
+
bodies.append(body)
|
|
179
|
+
if errors:
|
|
180
|
+
raise problems(errors, path)
|
|
181
|
+
if not decisions:
|
|
182
|
+
raise FitError(f"{path}: no labelled questions")
|
|
183
|
+
return bodies, decisions
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
# -- collection ----------------------------------------------------------------------------------------------------
|
|
187
|
+
def base_url(url):
|
|
188
|
+
return url.rstrip("/").removesuffix("/v1/systemone").removesuffix("/v1/basal")
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def model_entry(base, api_key):
|
|
192
|
+
"""GET /v1/models of the server -> its first model entry."""
|
|
193
|
+
import httpx
|
|
194
|
+
try:
|
|
195
|
+
r = httpx.get(base + "/v1/models", timeout=30, headers=headers(api_key))
|
|
196
|
+
why = refused(base, r.status_code, api_key)
|
|
197
|
+
if why:
|
|
198
|
+
raise FitError(why)
|
|
199
|
+
r.raise_for_status()
|
|
200
|
+
return r.json()["models"][0]
|
|
201
|
+
except (httpx.HTTPError, ValueError, KeyError, IndexError, TypeError) as e:
|
|
202
|
+
if isinstance(e, FitError):
|
|
203
|
+
raise
|
|
204
|
+
raise FitError(f"{base}: no basal server answers GET /v1/models ({e})") from None
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
async def post_all(endpoint, bodies, concurrency, api_key):
|
|
208
|
+
"""Every request to the server -> its JSON answer, or the error (an Exception) it got."""
|
|
209
|
+
import httpx
|
|
210
|
+
sem, done, step = asyncio.Semaphore(concurrency), 0, max(1, len(bodies) // 10)
|
|
211
|
+
async with httpx.AsyncClient(timeout=600, headers=headers(api_key)) as c:
|
|
212
|
+
async def one(b):
|
|
213
|
+
nonlocal done
|
|
214
|
+
async with sem:
|
|
215
|
+
try:
|
|
216
|
+
r = await c.post(endpoint, json=b)
|
|
217
|
+
out = r.json() if r.status_code == 200 else RuntimeError(f"HTTP {r.status_code}: {r.text[:300]}")
|
|
218
|
+
except Exception as e: # noqa: BLE001 (every failure is reported, none dropped)
|
|
219
|
+
out = e
|
|
220
|
+
done += 1
|
|
221
|
+
if done % step == 0 or done == len(bodies):
|
|
222
|
+
print(f" {done}/{len(bodies)} requests", file=sys.stderr, flush=True)
|
|
223
|
+
return out
|
|
224
|
+
return await asyncio.gather(*(one(b) for b in bodies))
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def is_probability(x):
|
|
228
|
+
return isinstance(x, (int, float)) and not isinstance(x, bool) and math.isfinite(x) and 0 <= x <= 1
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def deterministic_warning(entry):
|
|
232
|
+
d = entry.get("deterministic")
|
|
233
|
+
if d is True:
|
|
234
|
+
return None
|
|
235
|
+
how = "does not run --deterministic" if d is False else "does not say whether it runs --deterministic"
|
|
236
|
+
return (f"warning: the server {how}: requests batched together can get slightly different probabilities, so the "
|
|
237
|
+
"rules are fitted on noisy answers (start basal-serve with --deterministic to collect)")
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def collect(url, parts, concurrency, api_key):
|
|
241
|
+
"""The labelled requests of each part ({part: (bodies, decisions)}) through the server -> (header, rows)."""
|
|
242
|
+
base = base_url(url)
|
|
243
|
+
before = model_entry(base, api_key)
|
|
244
|
+
sig = dr.inference_signature(before)
|
|
245
|
+
try:
|
|
246
|
+
dr.check_backend(sig)
|
|
247
|
+
except dr.DecisionRulesError as e:
|
|
248
|
+
raise FitError(f"{base}: {e}") from None
|
|
249
|
+
if sig["think"] not in (None, "off"):
|
|
250
|
+
raise FitError(f"{base}: the server runs --think, so requests without \"think\" reason before they are "
|
|
251
|
+
"answered: decision rules are fitted on answers without think (start it without --think)")
|
|
252
|
+
warning = deterministic_warning(before)
|
|
253
|
+
if warning:
|
|
254
|
+
print(warning, file=sys.stderr)
|
|
255
|
+
rows, errors = [], []
|
|
256
|
+
for part, (bodies, decisions) in parts.items():
|
|
257
|
+
print(f"{part}: {len(bodies)} requests, {len(decisions)} labelled decisions", file=sys.stderr)
|
|
258
|
+
answers = asyncio.run(post_all(base + "/v1/systemone", bodies, concurrency, api_key))
|
|
259
|
+
rows += answer_rows(decisions, bodies, answers, before.get("early_exit_default"), errors)
|
|
260
|
+
after = dr.inference_signature(model_entry(base, api_key))
|
|
261
|
+
diff = dr.signature_diff(sig, after)
|
|
262
|
+
if diff:
|
|
263
|
+
raise FitError(f"{base}: the server's inference signature changed during the collection ({', '.join(diff)}): "
|
|
264
|
+
"collect again on a server that keeps its setup")
|
|
265
|
+
if errors:
|
|
266
|
+
raise problems(errors, f"{base}: requests without a usable answer")
|
|
267
|
+
header = {"format": ROWS_FORMAT, "experimental": True, "basal_version": __version__, "inference_signature": sig,
|
|
268
|
+
"deterministic": before.get("deterministic"), "serving_numerics": before.get("serving_numerics")}
|
|
269
|
+
return header, rows
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def answer_rows(decisions, bodies, answers, early_exit_default, errors):
|
|
273
|
+
"""Decisions + the server's answers -> rows (probabilities over the decision's keys, in order); a failed request or
|
|
274
|
+
an answer without finite probabilities for exactly its keys goes to errors."""
|
|
275
|
+
rows, failed = [], set()
|
|
276
|
+
for d in decisions:
|
|
277
|
+
r, at = answers[d["req"]], f"{d['part']} line {d['line']}, question {d['question']!r}"
|
|
278
|
+
if isinstance(r, Exception):
|
|
279
|
+
if d["req"] not in failed:
|
|
280
|
+
failed.add(d["req"])
|
|
281
|
+
errors.append(f"{d['part']} line {d['line']}: {r}")
|
|
282
|
+
continue
|
|
283
|
+
a = (r.get("answers") or {}).get(d["question"]) if isinstance(r, dict) else None
|
|
284
|
+
p = a.get("probabilities") if isinstance(a, dict) else None
|
|
285
|
+
if not isinstance(p, dict) or set(p) != set(d["keys"]) or not all(
|
|
286
|
+
is_probability(p[k]) for k in d["keys"]):
|
|
287
|
+
errors.append(f"{at}: no probabilities over its keys {d['keys']} in the answer")
|
|
288
|
+
continue
|
|
289
|
+
cond = dr.request_conditions(bodies[d["req"]], early_exit_default)
|
|
290
|
+
rows.append({**{k: d[k] for k in ROW_KEYS if k in d}, "request": cond,
|
|
291
|
+
"p": [float(p[k]) for k in d["keys"]]})
|
|
292
|
+
return rows
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
# -- rows ----------------------------------------------------------------------------------------------------------
|
|
296
|
+
def row_problem(r):
|
|
297
|
+
"""Why a saved row is not one (None when it is)."""
|
|
298
|
+
if not isinstance(r, dict) or set(r) != set(ROW_KEYS):
|
|
299
|
+
return f"a row has the fields {', '.join(ROW_KEYS)}"
|
|
300
|
+
if r["part"] not in ("train", "test") or not isinstance(r["line"], int) or not isinstance(r["question"], str):
|
|
301
|
+
return "part (train / test), line and question"
|
|
302
|
+
if not (r["id"] is None or isinstance(r["id"], str)) or not isinstance(r["group"], str) \
|
|
303
|
+
or not isinstance(r["explicit_group"], bool):
|
|
304
|
+
return "id, group and explicit_group"
|
|
305
|
+
if not isinstance(r["answer_space"], str) or not space_ok(r["answer_space"]) or r["type"] not in dr.TYPES:
|
|
306
|
+
return "answer_space and type"
|
|
307
|
+
if not dr._is_sha256(r["schema_hash"]):
|
|
308
|
+
return "schema_hash"
|
|
309
|
+
keys, p, g = r["keys"], r["p"], r["gold"]
|
|
310
|
+
if not isinstance(keys, list) or len(keys) < 2 or not all(isinstance(k, str) for k in keys) \
|
|
311
|
+
or len(set(keys)) != len(keys) or (r["type"] == "noul" and keys != ["true", "false"]):
|
|
312
|
+
return "keys"
|
|
313
|
+
if not isinstance(p, list) or len(p) != len(keys) or not all(is_probability(x) for x in p):
|
|
314
|
+
return "p (a probability per key, 0 to 1)"
|
|
315
|
+
if isinstance(g, bool) or not isinstance(g, int) or not 0 <= g < len(keys):
|
|
316
|
+
return "gold (the index of the correct key)"
|
|
317
|
+
if not dr._conditions_ok(r["request"]):
|
|
318
|
+
return "request (facts, early_exit, media)"
|
|
319
|
+
return None
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def save_rows(path, header, rows):
|
|
323
|
+
write(path, [header] + rows)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def load_rows(path):
|
|
327
|
+
"""A --save-rows file -> (header, rows); FitError naming every bad line."""
|
|
328
|
+
lines = [x for x in enumerate(read_lines(path), 1) if x[1].strip()]
|
|
329
|
+
if not lines:
|
|
330
|
+
raise FitError(f"{path}: empty")
|
|
331
|
+
try:
|
|
332
|
+
header = strict_json(lines[0][1])
|
|
333
|
+
except ValueError as e:
|
|
334
|
+
raise FitError(f"{path}: line {lines[0][0]}: not JSON ({getattr(e, 'msg', e)})") from None
|
|
335
|
+
if not isinstance(header, dict) or header.get("format") != ROWS_FORMAT \
|
|
336
|
+
or not isinstance(header.get("inference_signature"), dict) \
|
|
337
|
+
or any(k not in header["inference_signature"] for k in dr.SIGNATURE_FIELDS):
|
|
338
|
+
raise FitError(f"{path}: not a rows file of basal-fit-decisions (its first line: format {ROWS_FORMAT!r} and "
|
|
339
|
+
"the inference_signature)")
|
|
340
|
+
rows, errors = [], []
|
|
341
|
+
for n, line in lines[1:]:
|
|
342
|
+
try:
|
|
343
|
+
r = strict_json(line)
|
|
344
|
+
except ValueError as e:
|
|
345
|
+
errors.append(f"line {n}: not JSON ({getattr(e, 'msg', e)})")
|
|
346
|
+
continue
|
|
347
|
+
why = row_problem(r)
|
|
348
|
+
if why:
|
|
349
|
+
errors.append(f"line {n}: {why}")
|
|
350
|
+
continue
|
|
351
|
+
rows.append(r)
|
|
352
|
+
if errors:
|
|
353
|
+
raise problems(errors, path)
|
|
354
|
+
if not rows:
|
|
355
|
+
raise FitError(f"{path}: no rows")
|
|
356
|
+
return header, rows
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
# -- split ---------------------------------------------------------------------------------------------------------
|
|
360
|
+
def unit(salt, group):
|
|
361
|
+
"""A number in [0, 1) from the group alone (sha256): the same group always lands on the same side."""
|
|
362
|
+
return int.from_bytes(hashlib.sha256(f"{salt}\0{group}".encode("utf-8")).digest()[:8], "big") / 2.0**64
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def group_key(r):
|
|
366
|
+
"""The group a row is resampled and split with: its given group (or id), else its line, apart from given ones."""
|
|
367
|
+
return ("g:" if r["explicit_group"] else "line:") + r["group"]
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def split_of(r, with_test):
|
|
371
|
+
if r["part"] == "test":
|
|
372
|
+
return "final"
|
|
373
|
+
u = unit("basal.decision_rules/split", group_key(r))
|
|
374
|
+
if with_test:
|
|
375
|
+
return "fit" if u < SPLIT_TEST else "gate"
|
|
376
|
+
return "fit" if u < SPLIT[0] else "gate" if u < SPLIT[1] else "final"
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def fold_of(r):
|
|
380
|
+
return int.from_bytes(hashlib.sha256(f"basal.decision_rules/fold\0{group_key(r)}".encode("utf-8")).digest()[:8],
|
|
381
|
+
"big") % FOLDS
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def check_overlap(rows):
|
|
385
|
+
"""Training and test rows that share an id or a given group: FitError."""
|
|
386
|
+
ids, groups = defaultdict(set), defaultdict(set)
|
|
387
|
+
for r in rows:
|
|
388
|
+
if r["id"] is not None:
|
|
389
|
+
ids[r["part"]].add(r["id"])
|
|
390
|
+
if r["explicit_group"]:
|
|
391
|
+
groups[r["part"]].add(r["group"])
|
|
392
|
+
both_ids, both_groups = ids["train"] & ids["test"], groups["train"] & groups["test"]
|
|
393
|
+
if both_ids or both_groups:
|
|
394
|
+
what = []
|
|
395
|
+
if both_ids:
|
|
396
|
+
what.append(f"{len(both_ids)} id(s) ({', '.join(sorted(both_ids)[:5])})")
|
|
397
|
+
if both_groups:
|
|
398
|
+
what.append(f"{len(both_groups)} group(s) ({', '.join(sorted(both_groups)[:5])})")
|
|
399
|
+
raise FitError(f"the training and the test data share {' and '.join(what)}: the test must be data the fit "
|
|
400
|
+
"never saw")
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def spaces_of(rows):
|
|
404
|
+
"""Rows by answer space -> {space: rows}; FitError for a space with two schemas (or types, or keys)."""
|
|
405
|
+
by, errors = defaultdict(list), []
|
|
406
|
+
for r in rows:
|
|
407
|
+
by[r["answer_space"]].append(r)
|
|
408
|
+
for space, rs in by.items():
|
|
409
|
+
schemas = {(r["schema_hash"], r["type"], tuple(r["keys"])) for r in rs}
|
|
410
|
+
if len(schemas) > 1:
|
|
411
|
+
lines = ", ".join(sorted({f"{r['part']} line {r['line']}" for r in rs})[:6])
|
|
412
|
+
errors.append(f"answer space {space!r} holds {len(schemas)} different questions ({lines}): a space is one "
|
|
413
|
+
"question (type, language, instructions, options and option_keys)")
|
|
414
|
+
if errors:
|
|
415
|
+
raise problems(errors, "answer spaces")
|
|
416
|
+
return dict(by)
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
# -- decisions -----------------------------------------------------------------------------------------------------
|
|
420
|
+
def probs_of(r):
|
|
421
|
+
return dict(zip(r["keys"], r["p"]))
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def correct(rule, r):
|
|
425
|
+
key, _ = dr.decide(rule, r["keys"], probs_of(r))
|
|
426
|
+
return int(r["keys"].index(key) == r["gold"])
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def baseline_rule(t):
|
|
430
|
+
return dr.Rule("baseline", t, "baseline")
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def midpoint(a, b):
|
|
434
|
+
"""A threshold between two adjacent P(true) values a < b that splits them as they are: a < t <= b."""
|
|
435
|
+
m = a + (b - a) / 2
|
|
436
|
+
return m if a < m <= b else b
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def sweep(rows):
|
|
440
|
+
"""The exact breakpoint sweep of a noul space: every threshold that splits its P(true) values differently ->
|
|
441
|
+
the most accurate one (rule "true" iff P(true) >= t); equally accurate ones: the nearest to 0.5, then the lower."""
|
|
442
|
+
pts = sorted((r["p"][0], 1 - r["gold"]) for r in rows) # (P(true), 1 when the gold is true)
|
|
443
|
+
vals = sorted({p for p, _ in pts})
|
|
444
|
+
pos_below, neg_below, i = {}, {}, 0
|
|
445
|
+
pos = neg = 0
|
|
446
|
+
for v in vals: # the golds below each distinct value
|
|
447
|
+
while i < len(pts) and pts[i][0] < v:
|
|
448
|
+
pos, neg, i = pos + pts[i][1], neg + 1 - pts[i][1], i + 1
|
|
449
|
+
pos_below[v], neg_below[v] = pos, neg
|
|
450
|
+
total_pos = sum(y for _, y in pts)
|
|
451
|
+
cands = []
|
|
452
|
+
for k, v in enumerate(vals): # "true" iff p >= v: right on the true golds at or above, the false ones below
|
|
453
|
+
t = v / 2 if k == 0 else midpoint(vals[k - 1], v)
|
|
454
|
+
cands.append((total_pos - pos_below[v] + neg_below[v], t))
|
|
455
|
+
if vals[-1] < 1.0: # every answer "false"
|
|
456
|
+
cands.append((len(pts) - total_pos, midpoint(vals[-1], 1.0)))
|
|
457
|
+
best = max(c for c, _ in cands)
|
|
458
|
+
return min((abs(t - 0.5), t) for c, t in cands if c == best)[1]
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def candidate(space_type, fit_rows):
|
|
462
|
+
"""The changed rule a space's FIT rows propose (noul: the swept threshold; score: round)."""
|
|
463
|
+
if space_type == "noul":
|
|
464
|
+
return dr.Rule("candidate", "noul", "threshold", sweep(fit_rows))
|
|
465
|
+
return dr.Rule("candidate", "score", "round")
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def cross_validate(space_type, fit_rows):
|
|
469
|
+
"""5 grouped folds within FIT -> (correct out-of-fold decisions of the baseline, of the change, per fold)."""
|
|
470
|
+
base, folds = baseline_rule(space_type), defaultdict(list)
|
|
471
|
+
for r in fit_rows:
|
|
472
|
+
folds[fold_of(r)].append(r)
|
|
473
|
+
per_fold = []
|
|
474
|
+
for f in range(FOLDS):
|
|
475
|
+
held = folds.get(f, [])
|
|
476
|
+
if not held:
|
|
477
|
+
continue
|
|
478
|
+
train = [r for g, rs in folds.items() if g != f for r in rs]
|
|
479
|
+
rule = candidate(space_type, train) if train else base
|
|
480
|
+
per_fold.append({"fold": f, "n": len(held), "candidate": rule.parameters,
|
|
481
|
+
"baseline": sum(correct(base, r) for r in held), "changed": sum(correct(rule, r) for r in held)})
|
|
482
|
+
return sum(x["baseline"] for x in per_fold), sum(x["changed"] for x in per_fold), per_fold
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
# -- bootstrap -----------------------------------------------------------------------------------------------------
|
|
486
|
+
def gains(rule, rows):
|
|
487
|
+
"""Per decision: correct under the rule minus correct under the baseline (the paired gain), and its group."""
|
|
488
|
+
base = baseline_rule(rows[0]["type"]) if rows else None
|
|
489
|
+
return [correct(rule, r) - correct(base, r) for r in rows], [group_key(r) for r in rows]
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def bootstrap(delta, groups, draws, seed, label):
|
|
493
|
+
"""The paired gain (mean over decisions) of `draws` resamples of whole groups -> (gain, resampled gains)."""
|
|
494
|
+
import numpy as np
|
|
495
|
+
uniq, inv = np.unique(np.array(groups, dtype=object).astype(str), return_inverse=True)
|
|
496
|
+
s = np.bincount(inv, weights=np.asarray(delta, dtype=float), minlength=len(uniq))
|
|
497
|
+
n = np.bincount(inv, minlength=len(uniq)).astype(float)
|
|
498
|
+
G = len(uniq)
|
|
499
|
+
rng = np.random.default_rng([seed, zlib.crc32(label.encode("utf-8"))])
|
|
500
|
+
out, chunk = np.empty(draws), max(1, min(draws, 2_000_000 // G))
|
|
501
|
+
for start in range(0, draws, chunk):
|
|
502
|
+
w = rng.multinomial(G, np.full(G, 1.0 / G), size=min(chunk, draws - start)).astype(float)
|
|
503
|
+
out[start:start + len(w)] = (w @ s) / (w @ n)
|
|
504
|
+
return float(s.sum() / n.sum()), out
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def summary_of(delta, groups, draws, seed, label):
|
|
508
|
+
"""The paired gain, its two-sided 95% interval and the one-sided p of no gain, (1 + #{gain* <= 0}) / (B + 1)."""
|
|
509
|
+
if not delta:
|
|
510
|
+
return {"n": 0, "groups": 0, "gain": None, "ci95": None, "p": 1.0}
|
|
511
|
+
import numpy as np
|
|
512
|
+
gain, boot = bootstrap(delta, groups, draws, seed, label)
|
|
513
|
+
lo, hi = np.percentile(boot, [2.5, 97.5])
|
|
514
|
+
return {"n": len(delta), "groups": len(set(groups)), "gain": gain, "ci95": [float(lo), float(hi)],
|
|
515
|
+
"p": float((1 + int(np.sum(boot <= 0))) / (draws + 1))}
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def holm(ps):
|
|
519
|
+
"""Holm's step-down adjusted p-values, in the order given."""
|
|
520
|
+
order = sorted(range(len(ps)), key=lambda i: ps[i])
|
|
521
|
+
adj, run = [0.0] * len(ps), 0.0
|
|
522
|
+
for rank, i in enumerate(order):
|
|
523
|
+
run = max(run, min(1.0, (len(ps) - rank) * ps[i]))
|
|
524
|
+
adj[i] = run
|
|
525
|
+
return adj
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
# -- fit -----------------------------------------------------------------------------------------------------------
|
|
529
|
+
def conditions_of(rs):
|
|
530
|
+
"""The request conditions of a space's FIT and GATE rows -> (the one value, None) or (None, why: they differ, or
|
|
531
|
+
there are none). FINAL rows never take part: they are checked against it once the fit is done (check_final)."""
|
|
532
|
+
if not rs:
|
|
533
|
+
return None, "no FIT or GATE decisions"
|
|
534
|
+
seen = {json.dumps(r["request"], sort_keys=True) for r in rs}
|
|
535
|
+
if len(seen) == 1:
|
|
536
|
+
return rs[0]["request"], None
|
|
537
|
+
return None, ("its FIT and GATE requests differ in " + ", ".join(
|
|
538
|
+
k for k in dr.REQUEST_FIELDS if len({json.dumps(r["request"][k]) for r in rs}) > 1)
|
|
539
|
+
+ " (a rule applies to requests asked one way)")
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
def check_final(records):
|
|
543
|
+
"""FINAL rows asked otherwise than their space's FIT and GATE rows (another facts mode, early-exit policy or media):
|
|
544
|
+
its rule could never be served on them, so FINAL cannot report it -> FitError listing them."""
|
|
545
|
+
errors = []
|
|
546
|
+
for space, rec in sorted(records.items()):
|
|
547
|
+
for r in rec["parts"]["final"]:
|
|
548
|
+
diff = [k for k in dr.REQUEST_FIELDS if r["request"][k] != rec["request"][k]]
|
|
549
|
+
if diff:
|
|
550
|
+
errors.append(f"{r['part']} line {r['line']}, question {r['question']!r} (answer space {space!r}): "
|
|
551
|
+
+ ", ".join(f"{k} {json.dumps(r['request'][k])}" for k in diff)
|
|
552
|
+
+ ", its FIT and GATE requests: " + ", ".join(f"{k} {json.dumps(rec['request'][k])}"
|
|
553
|
+
for k in diff))
|
|
554
|
+
if errors:
|
|
555
|
+
raise problems(errors, "FINAL decisions asked otherwise than their rule was fitted on (it could never be "
|
|
556
|
+
"served on them)")
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
def fit_spaces(rows, a):
|
|
560
|
+
"""Rows (train and test) -> (per space: its fit record, kept rules, the GATE tests, refused spaces)."""
|
|
561
|
+
with_test = any(r["part"] == "test" for r in rows)
|
|
562
|
+
if with_test:
|
|
563
|
+
check_overlap(rows)
|
|
564
|
+
trained = {r["answer_space"] for r in rows if r["part"] == "train"}
|
|
565
|
+
only = sorted({r["answer_space"] for r in rows if r["part"] == "test"} - trained)
|
|
566
|
+
if only:
|
|
567
|
+
raise FitError(f"answer space(s) {', '.join(map(repr, only[:10]))} are in the test data only")
|
|
568
|
+
spaces, records, refused = spaces_of(rows), {}, {}
|
|
569
|
+
for space, rs in sorted(spaces.items()):
|
|
570
|
+
parts = {p: [r for r in rs if split_of(r, with_test) == p] for p in ("fit", "gate", "final")}
|
|
571
|
+
cond, why = conditions_of(parts["fit"] + parts["gate"])
|
|
572
|
+
if why:
|
|
573
|
+
refused[space] = why
|
|
574
|
+
continue
|
|
575
|
+
t = rs[0]["type"]
|
|
576
|
+
fit_rows = parts["fit"]
|
|
577
|
+
n_groups, golds = len({group_key(r) for r in fit_rows}), {r["gold"] for r in fit_rows}
|
|
578
|
+
rec = {"type": t, "schema_hash": rs[0]["schema_hash"], "keys": rs[0]["keys"], "request": cond, "parts": parts,
|
|
579
|
+
"fit": {"n": len(fit_rows), "groups": n_groups}}
|
|
580
|
+
records[space] = rec
|
|
581
|
+
small = n_groups < MIN_GROUPS or (t == "noul" and golds != {0, 1})
|
|
582
|
+
if small:
|
|
583
|
+
need = f"at least {MIN_GROUPS} FIT groups" + (" with both answers among the golds" if t == "noul" else "")
|
|
584
|
+
rec.update(status="too_small", method="baseline", reason=f"needs {need}: has {n_groups} group(s)"
|
|
585
|
+
+ (f", golds {sorted('true' if g == 0 else 'false' for g in golds)}" if t == "noul" else ""))
|
|
586
|
+
continue
|
|
587
|
+
b, c, per_fold = cross_validate(t, fit_rows)
|
|
588
|
+
rec["cv"] = {"folds": FOLDS, "baseline_correct": b, "changed_correct": c, "per_fold": per_fold}
|
|
589
|
+
if c <= b:
|
|
590
|
+
rec.update(status="unchanged", method="baseline" if t == "noul" else "argmax",
|
|
591
|
+
reason=f"the change was not better out of fold on FIT ({c} vs {b} correct; a tie keeps the "
|
|
592
|
+
"baseline)")
|
|
593
|
+
continue
|
|
594
|
+
rule = candidate(t, fit_rows)
|
|
595
|
+
rec.update(status="tested", candidate=rule)
|
|
596
|
+
tests = retention(records, a)
|
|
597
|
+
return records, tests, refused, with_test
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
def retention(records, a):
|
|
601
|
+
"""GATE tests of the spaces whose change won on FIT: per type (bundle) or per space; Holm across the tests. Sets
|
|
602
|
+
each tested space's status to kept or refused."""
|
|
603
|
+
tested = sorted(s for s, r in records.items() if r["status"] == "tested")
|
|
604
|
+
if a.retention == "bundle":
|
|
605
|
+
groups_ = [(f"bundle:{t}", [s for s in tested if records[s]["type"] == t]) for t in dr.TYPES]
|
|
606
|
+
groups_ = [g for g in groups_ if g[1]]
|
|
607
|
+
else:
|
|
608
|
+
groups_ = [(s, [s]) for s in tested]
|
|
609
|
+
tests = []
|
|
610
|
+
for label, members in groups_:
|
|
611
|
+
delta, grp = [], []
|
|
612
|
+
for s in members:
|
|
613
|
+
d, g = gains(records[s]["candidate"], records[s]["parts"]["gate"])
|
|
614
|
+
delta += d
|
|
615
|
+
grp += g
|
|
616
|
+
tests.append(dict(name=label, spaces=members, **summary_of(delta, grp, a.draws, a.seed, label)))
|
|
617
|
+
for test, adj in zip(tests, holm([x["p"] for x in tests])):
|
|
618
|
+
test["p_holm"] = adj
|
|
619
|
+
test["kept"] = adj <= a.alpha and test["gain"] is not None and test["gain"] > 0
|
|
620
|
+
for s in test["spaces"]:
|
|
621
|
+
rec = records[s]
|
|
622
|
+
gate = {k: test[k] for k in ("name", "n", "groups", "gain", "ci95", "p", "p_holm")}
|
|
623
|
+
if a.retention == "bundle":
|
|
624
|
+
gate["space"] = summary_of(*gains(rec["candidate"], rec["parts"]["gate"]), a.draws, a.seed, s)
|
|
625
|
+
rec["gate"] = gate
|
|
626
|
+
if test["kept"]:
|
|
627
|
+
rule = rec["candidate"]
|
|
628
|
+
rec.update(status="kept", method=rule.method, reason=f"a gain on GATE ({test['name']}: p_holm "
|
|
629
|
+
f"{adj:.4g} <= {a.alpha})")
|
|
630
|
+
else:
|
|
631
|
+
why = "no GATE decisions" if test["n"] == 0 else f"p_holm {adj:.4g} > {a.alpha}" if adj > a.alpha \
|
|
632
|
+
else "no gain"
|
|
633
|
+
rec.update(status="refused", method="baseline", reason=f"refused on GATE ({test['name']}: {why})")
|
|
634
|
+
return tests
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
def rule_entry(space, rec):
|
|
638
|
+
"""A space's fit record -> its entry of the rules file."""
|
|
639
|
+
cand = rec.get("candidate")
|
|
640
|
+
params = cand.parameters if rec["status"] == "kept" else {}
|
|
641
|
+
fit = {"status": rec["status"], "reason": rec["reason"], "fit": rec["fit"]}
|
|
642
|
+
if "cv" in rec:
|
|
643
|
+
fit["cv"] = {k: rec["cv"][k] for k in ("folds", "baseline_correct", "changed_correct")}
|
|
644
|
+
if cand is not None:
|
|
645
|
+
fit["candidate"] = {"method": cand.method, "parameters": cand.parameters}
|
|
646
|
+
if "gate" in rec:
|
|
647
|
+
fit["gate"] = {k: v for k, v in rec["gate"].items() if k != "space"}
|
|
648
|
+
return {"answer_space": space, "type": rec["type"], "schema_hash": rec["schema_hash"], "method": rec["method"],
|
|
649
|
+
"parameters": params, "request": rec["request"], "fit": fit}
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
def sha256_of(paths):
|
|
653
|
+
return {k: hashlib.sha256(Path(p).read_bytes()).hexdigest() for k, p in paths.items() if p}
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
def rules_data(records, header, a, sources, tests, refused, with_test):
|
|
657
|
+
rules = {s: rule_entry(s, rec) for s, rec in records.items()}
|
|
658
|
+
if not rules:
|
|
659
|
+
raise FitError("no answer space can take a rule: " + "; ".join(f"{s}: {w}" for s, w in refused.items()))
|
|
660
|
+
sig = header["inference_signature"]
|
|
661
|
+
rid = a.id or "decision-rules-" + hashlib.sha256(dr._canonical([sig, rules]).encode("utf-8")).hexdigest()[:12]
|
|
662
|
+
if not dr._id_ok(rid):
|
|
663
|
+
raise FitError(f"--id {rid!r}: a non-empty printable string of at most {dr.MAX_ID} characters")
|
|
664
|
+
created = datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
|
|
665
|
+
prov = {"tool": "basal-fit-decisions", "sources_sha256": sources, "deterministic": header.get("deterministic"),
|
|
666
|
+
"serving_numerics": header.get("serving_numerics"),
|
|
667
|
+
"split": ("FIT / GATE 80 / 20 of the training data, FINAL = the test data" if with_test else
|
|
668
|
+
"FIT / GATE / FINAL 60 / 20 / 20"),
|
|
669
|
+
"grouping": "sha256 of the group", "folds": FOLDS, "min_groups": MIN_GROUPS, "retention": a.retention,
|
|
670
|
+
"alpha": a.alpha, "draws": a.draws, "seed": a.seed,
|
|
671
|
+
"tests": [{k: t[k] for k in ("name", "spaces", "n", "groups", "gain", "ci95", "p", "p_holm", "kept")}
|
|
672
|
+
for t in tests],
|
|
673
|
+
"refused_spaces": refused}
|
|
674
|
+
return {"format": dr.FORMAT, "id": rid, "experimental": True, "created": created, "basal_version": __version__,
|
|
675
|
+
"inference_signature": sig, "metric": METRIC, "rules": rules, "provenance": prov}
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
# -- evaluation ----------------------------------------------------------------------------------------------------
|
|
679
|
+
def rule_of(rules, r):
|
|
680
|
+
"""The frozen file's rule for a row, as basal-serve resolves it (the schema, the request conditions)."""
|
|
681
|
+
rule = rules.rules.get(r["answer_space"])
|
|
682
|
+
if rule is None:
|
|
683
|
+
raise dr.DecisionRulesError("unknown_rule", f"answer space {r['answer_space']!r} has no rule in "
|
|
684
|
+
f"{rules.id!r}")
|
|
685
|
+
if rule.schema_hash != r["schema_hash"] or rule.type != r["type"]:
|
|
686
|
+
raise dr.DecisionRulesError("schema_mismatch", f"answer space {r['answer_space']!r}: the rule was fitted on "
|
|
687
|
+
"another question")
|
|
688
|
+
dr.check_request(rule, r["request"], {"name": r["question"]})
|
|
689
|
+
return rule
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
def measure(rows, rule_for, draws, seed, label):
|
|
693
|
+
"""Rows and their rules -> n, groups, baseline and rules accuracy, the paired gain with its 95% interval, wins and
|
|
694
|
+
losses (score: the mean absolute errors)."""
|
|
695
|
+
if not rows:
|
|
696
|
+
return {"n": 0}
|
|
697
|
+
base_c, rule_c, err = [], [], defaultdict(float)
|
|
698
|
+
for r in rows:
|
|
699
|
+
rule, base = rule_for(r), baseline_rule(r["type"])
|
|
700
|
+
b, c = correct(base, r), correct(rule, r)
|
|
701
|
+
base_c.append(b)
|
|
702
|
+
rule_c.append(c)
|
|
703
|
+
if r["type"] == "score":
|
|
704
|
+
p = probs_of(r)
|
|
705
|
+
for name, rl in (("baseline", base), ("rules", rule)):
|
|
706
|
+
err[name] += abs(r["keys"].index(dr.decide(rl, r["keys"], p)[0]) - r["gold"])
|
|
707
|
+
err["expected_level"] += abs(sum(i * x for i, x in enumerate(r["p"])) - r["gold"])
|
|
708
|
+
delta = [c - b for b, c in zip(base_c, rule_c)]
|
|
709
|
+
s = summary_of(delta, [group_key(r) for r in rows], draws, seed, label)
|
|
710
|
+
out = {"n": len(rows), "groups": s["groups"], "baseline": sum(base_c) / len(rows), "rules": sum(rule_c) / len(rows),
|
|
711
|
+
"gain": s["gain"], "ci95": s["ci95"], "wins": delta.count(1), "losses": delta.count(-1)}
|
|
712
|
+
n_score = sum(r["type"] == "score" for r in rows)
|
|
713
|
+
if n_score:
|
|
714
|
+
out["mae"] = {k: v / n_score for k, v in err.items()}
|
|
715
|
+
return out
|
|
716
|
+
|
|
717
|
+
|
|
718
|
+
def evaluate_rows(rules, rows, draws, seed, no_rule=()):
|
|
719
|
+
"""Every row under the frozen file -> {spaces: {space: measures}, total}. The rows of the spaces in no_rule (the
|
|
720
|
+
fit gave them none) are decided as without a rule, the baseline (their gain 0) and count in the total; another
|
|
721
|
+
row without a rule is a FitError."""
|
|
722
|
+
def rule_for(r):
|
|
723
|
+
return baseline_rule(r["type"]) if r["answer_space"] in no_rule else rule_of(rules, r)
|
|
724
|
+
errors = []
|
|
725
|
+
for r in rows:
|
|
726
|
+
try:
|
|
727
|
+
rule_for(r)
|
|
728
|
+
except dr.DecisionRulesError as e:
|
|
729
|
+
errors.append(f"{r['part']} line {r['line']}, question {r['question']!r}: {e}")
|
|
730
|
+
if errors:
|
|
731
|
+
raise problems(errors, f"decision rules {rules.id!r}")
|
|
732
|
+
by = defaultdict(list)
|
|
733
|
+
for r in rows:
|
|
734
|
+
by[r["answer_space"]].append(r)
|
|
735
|
+
spaces = {s: measure(rs, rule_for, draws, seed, f"final:{s}") for s, rs in sorted(by.items())}
|
|
736
|
+
return {"spaces": spaces, "total": measure(rows, rule_for, draws, seed, "final:total")}
|
|
737
|
+
|
|
738
|
+
|
|
739
|
+
# -- report --------------------------------------------------------------------------------------------------------
|
|
740
|
+
def pct(x):
|
|
741
|
+
return "-" if x is None else f"{100 * x:.1f}%"
|
|
742
|
+
|
|
743
|
+
|
|
744
|
+
def signed(x):
|
|
745
|
+
return "-" if x is None else f"{100 * x:+.1f}"
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
def text_summary(report, out, report_path):
|
|
749
|
+
lines = [f"decision rules {report['rules_id']} (experimental), on {report['evaluated_on']}:"]
|
|
750
|
+
spaces = report["spaces"]
|
|
751
|
+
w = max([len(s) for s in spaces] + [len("answer space"), len("total")])
|
|
752
|
+
lines.append(f" {'answer space':<{w}} type rule status n baseline rules gain [95% CI]")
|
|
753
|
+
for s, sp in spaces.items():
|
|
754
|
+
m = sp.get("final") or {"n": 0}
|
|
755
|
+
rule = (sp["method"] or "no rule") + (f" {sp['parameters']['threshold']:.4g}" if sp.get("parameters") else "")
|
|
756
|
+
ci = f" [{signed(m['ci95'][0])}, {signed(m['ci95'][1])}]" if m.get("ci95") else ""
|
|
757
|
+
lines.append(f" {s:<{w}} {sp['type']:<5} {rule:<14} {sp['status']:<10} {m['n']:<5} "
|
|
758
|
+
f"{pct(m.get('baseline')):<8} {pct(m.get('rules')):<6} {signed(m.get('gain'))}{ci}")
|
|
759
|
+
t = report["total"]
|
|
760
|
+
if t.get("n"):
|
|
761
|
+
ci = f" [{signed(t['ci95'][0])}, {signed(t['ci95'][1])}]" if t.get("ci95") else ""
|
|
762
|
+
lines.append(f" {'total':<{w}} {'':<5} {'':<14} {'':<10} {t['n']:<5} {pct(t['baseline']):<8} "
|
|
763
|
+
f"{pct(t['rules']):<6} {signed(t['gain'])}{ci} ({t['wins']} wins, {t['losses']} losses)")
|
|
764
|
+
for s, why in report.get("refused_spaces", {}).items():
|
|
765
|
+
lines.append(f" {s}: no rule ({why}): its decisions count as the baseline's")
|
|
766
|
+
lines.append(" (gain: points of accuracy; baseline: the MAP answer the calibration certifies)")
|
|
767
|
+
written = [x for x in (out, report_path) if x]
|
|
768
|
+
if written:
|
|
769
|
+
lines.append(" written: " + ", ".join(map(str, written)))
|
|
770
|
+
return "\n".join(lines)
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
def space_report(space, rec):
|
|
774
|
+
out = {"type": rec["type"], "method": rec["method"],
|
|
775
|
+
"parameters": rec["candidate"].parameters if rec["status"] == "kept" else {},
|
|
776
|
+
"status": rec["status"], "reason": rec["reason"], "request": rec["request"], "fit": rec["fit"]}
|
|
777
|
+
for k in ("cv", "gate"):
|
|
778
|
+
if k in rec:
|
|
779
|
+
out[k] = rec[k]
|
|
780
|
+
if rec.get("candidate") is not None:
|
|
781
|
+
out["candidate"] = {"method": rec["candidate"].method, "parameters": rec["candidate"].parameters}
|
|
782
|
+
return out
|
|
783
|
+
|
|
784
|
+
|
|
785
|
+
# -- commands ------------------------------------------------------------------------------------------------------
|
|
786
|
+
def gather(a, parts):
|
|
787
|
+
"""The rows to fit or evaluate: from --from-rows, else collected from --url (and saved with --save-rows)."""
|
|
788
|
+
if a.from_rows:
|
|
789
|
+
if any(parts.values()) or a.url or a.save_rows:
|
|
790
|
+
raise FitError("--from-rows replaces the labelled files, --url and --save-rows")
|
|
791
|
+
header, rows = load_rows(a.from_rows)
|
|
792
|
+
try:
|
|
793
|
+
dr.check_backend(header["inference_signature"])
|
|
794
|
+
except dr.DecisionRulesError as e:
|
|
795
|
+
raise FitError(f"{a.from_rows}: {e}") from None
|
|
796
|
+
return header, rows, sha256_of({"rows": a.from_rows})
|
|
797
|
+
if not a.url:
|
|
798
|
+
raise FitError("give --url (a running basal-serve) or --from-rows")
|
|
799
|
+
if not next(iter(parts.values())):
|
|
800
|
+
raise FitError("give the labelled JSONL file")
|
|
801
|
+
labelled = {p: read_labelled(path, p) for p, path in parts.items() if path}
|
|
802
|
+
header, rows = collect(a.url, labelled, a.concurrency, a.api_key)
|
|
803
|
+
if a.save_rows:
|
|
804
|
+
save_rows(a.save_rows, header, rows)
|
|
805
|
+
print(f"rows: {a.save_rows}", file=sys.stderr)
|
|
806
|
+
return header, rows, sha256_of(parts)
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
def cmd_fit(a):
|
|
810
|
+
header, rows, sources = gather(a, {"train": a.data, "test": a.test})
|
|
811
|
+
if not any(r["part"] == "train" for r in rows):
|
|
812
|
+
raise FitError("no training rows to fit on (rows of an evaluation hold test rows only)")
|
|
813
|
+
records, tests, refused, with_test = fit_spaces(rows, a)
|
|
814
|
+
check_final(records)
|
|
815
|
+
data = rules_data(records, header, a, sources, tests, refused, with_test)
|
|
816
|
+
write_json(a.out, data, indent=1)
|
|
817
|
+
frozen = dr.load(a.out) # FINAL reads the file as served, once
|
|
818
|
+
part = [split_of(r, with_test) for r in rows] # (every input row: the spaces without a rule too)
|
|
819
|
+
final_rows = [r for r, p in zip(rows, part) if p == "final"]
|
|
820
|
+
final = evaluate_rows(frozen, final_rows, a.draws, a.seed, refused) if final_rows else \
|
|
821
|
+
{"spaces": {}, "total": {"n": 0}}
|
|
822
|
+
spaces = {}
|
|
823
|
+
for s in sorted(set(records) | set(refused)):
|
|
824
|
+
if s in records:
|
|
825
|
+
spaces[s] = space_report(s, records[s])
|
|
826
|
+
else:
|
|
827
|
+
t = next(r["type"] for r in rows if r["answer_space"] == s)
|
|
828
|
+
spaces[s] = {"type": t, "method": None, "parameters": {}, "status": "no_rule", "reason": refused[s]}
|
|
829
|
+
spaces[s]["final"] = final["spaces"].get(s, {"n": 0})
|
|
830
|
+
split = {p: {"n": part.count(p), "groups": len({group_key(r) for r, q in zip(rows, part) if q == p})}
|
|
831
|
+
for p in ("fit", "gate", "final")}
|
|
832
|
+
report = {"format": REPORT_FORMAT, "experimental": True, "rules_id": frozen.id, "rules_sha256": frozen.sha256,
|
|
833
|
+
"basal_version": __version__, "metric": METRIC, "inference_signature": header["inference_signature"],
|
|
834
|
+
"deterministic": header.get("deterministic"), "serving_numerics": header.get("serving_numerics"),
|
|
835
|
+
"evaluated_on": "FINAL", "split": split,
|
|
836
|
+
"retention": {"mode": a.retention, "alpha": a.alpha, "draws": a.draws, "seed": a.seed, "tests": [
|
|
837
|
+
{k: t[k] for k in ("name", "spaces", "n", "groups", "gain", "ci95", "p", "p_holm", "kept")}
|
|
838
|
+
for t in tests]},
|
|
839
|
+
"spaces": spaces, "refused_spaces": refused, "total": final["total"]}
|
|
840
|
+
if a.report:
|
|
841
|
+
write_json(a.report, report, indent=1)
|
|
842
|
+
print(text_summary(report, a.out, a.report))
|
|
843
|
+
return report
|
|
844
|
+
|
|
845
|
+
|
|
846
|
+
def numerics_compared(fitted, evaluated):
|
|
847
|
+
"""The serving numerics (GET /v1/models serving_numerics: the GPU and the resolved graph shapes) of the fit and of
|
|
848
|
+
the evaluating server -> {fitted, evaluated, differ: the keys that differ}, with a warning when they differ. They
|
|
849
|
+
are not in the signature: like batching under load they move answers only at the level of numeric noise."""
|
|
850
|
+
if fitted == evaluated:
|
|
851
|
+
differ = []
|
|
852
|
+
elif isinstance(fitted, dict) and isinstance(evaluated, dict):
|
|
853
|
+
differ = sorted(k for k in set(fitted) | set(evaluated) if fitted.get(k) != evaluated.get(k))
|
|
854
|
+
else:
|
|
855
|
+
differ = ["unknown"] # (one side does not report them)
|
|
856
|
+
if differ:
|
|
857
|
+
print(f"warning: the evaluating server's serving numerics differ from the fit's ({', '.join(differ)}): its "
|
|
858
|
+
"answers can differ from the fit's at the level of numeric noise (as on another GPU, or under load)",
|
|
859
|
+
file=sys.stderr)
|
|
860
|
+
return {"fitted": fitted, "evaluated": evaluated, "differ": differ}
|
|
861
|
+
|
|
862
|
+
|
|
863
|
+
def cmd_evaluate(a):
|
|
864
|
+
rules = dr.load(a.rules)
|
|
865
|
+
header, rows, _ = gather(a, {"test": a.data})
|
|
866
|
+
try:
|
|
867
|
+
rules.check_signature(header["inference_signature"])
|
|
868
|
+
except dr.DecisionRulesError as e:
|
|
869
|
+
raise FitError(str(e)) from None
|
|
870
|
+
numerics = numerics_compared(rules.data["provenance"].get("serving_numerics"), header.get("serving_numerics"))
|
|
871
|
+
result = evaluate_rows(rules, rows, a.draws, a.seed)
|
|
872
|
+
spaces = {}
|
|
873
|
+
for s, m in result["spaces"].items():
|
|
874
|
+
r = rules.rules[s]
|
|
875
|
+
spaces[s] = {"type": r.type, "method": r.method, "parameters": r.parameters, "status": r.fit.get("status", "-"),
|
|
876
|
+
"request": r.request, "final": m}
|
|
877
|
+
report = {"format": REPORT_FORMAT, "experimental": True, "rules_id": rules.id, "rules_sha256": rules.sha256,
|
|
878
|
+
"basal_version": __version__, "metric": METRIC, "inference_signature": header["inference_signature"],
|
|
879
|
+
"deterministic": header.get("deterministic"), "serving_numerics": numerics,
|
|
880
|
+
"evaluated_on": "the given data",
|
|
881
|
+
"draws": a.draws, "seed": a.seed, "spaces": spaces, "total": result["total"]}
|
|
882
|
+
if a.report:
|
|
883
|
+
write_json(a.report, report, indent=1)
|
|
884
|
+
print(text_summary(report, None, a.report))
|
|
885
|
+
return report
|
|
886
|
+
|
|
887
|
+
|
|
888
|
+
def probability(s):
|
|
889
|
+
v = float(s)
|
|
890
|
+
if not 0 < v < 1:
|
|
891
|
+
raise argparse.ArgumentTypeError(f"{s}: must be between 0 and 1")
|
|
892
|
+
return v
|
|
893
|
+
|
|
894
|
+
|
|
895
|
+
def parser():
|
|
896
|
+
ap = argparse.ArgumentParser(prog="basal-fit-decisions", description=__doc__.split("\n\n")[0],
|
|
897
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
898
|
+
sub = ap.add_subparsers(dest="command", required=True)
|
|
899
|
+
|
|
900
|
+
def common(p):
|
|
901
|
+
p.add_argument("--url", help="a running basal-serve, serving as the rules will be served (its calibration)")
|
|
902
|
+
p.add_argument("--from-rows", dest="from_rows", help="the rows of an earlier --save-rows, instead of a server")
|
|
903
|
+
p.add_argument("--save-rows", dest="save_rows", help="write the collected probabilities here (JSONL)")
|
|
904
|
+
p.add_argument("--report", help="REPORT.json: the full report")
|
|
905
|
+
p.add_argument("--concurrency", type=positive, default=1, help="requests in flight (default 1)")
|
|
906
|
+
p.add_argument("--draws", type=positive, default=DRAWS, help=f"bootstrap resamples (default {DRAWS})")
|
|
907
|
+
p.add_argument("--seed", type=int, default=0, help="the bootstrap's seed (default 0)")
|
|
908
|
+
add_api_key(p)
|
|
909
|
+
|
|
910
|
+
f = sub.add_parser("fit", help="fit rules on labelled requests and report them on FINAL",
|
|
911
|
+
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
912
|
+
f.add_argument("data", nargs="?", help="labelled JSONL (with --url)")
|
|
913
|
+
f.add_argument("--test", help="labelled JSONL kept for FINAL (the training file is then split FIT / GATE 80 / 20)")
|
|
914
|
+
f.add_argument("--out", default="RULES.json", help="the rules file (default RULES.json)")
|
|
915
|
+
f.add_argument("--retention", choices=["bundle", "per-space"], default="bundle",
|
|
916
|
+
help="GATE tests: one per type over its changed spaces (bundle, default) or one per changed space")
|
|
917
|
+
f.add_argument("--alpha", type=probability, default=ALPHA, help=f"the GATE tests' level after Holm (default {ALPHA})")
|
|
918
|
+
f.add_argument("--id", help="the rules file's id (default: decision-rules-<hash of its rules>)")
|
|
919
|
+
common(f)
|
|
920
|
+
f.set_defaults(report="REPORT.json")
|
|
921
|
+
e = sub.add_parser("evaluate", help="report a rules file on labelled requests",
|
|
922
|
+
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
923
|
+
e.add_argument("rules", help="the rules file (RULES.json)")
|
|
924
|
+
e.add_argument("data", nargs="?", help="labelled JSONL (with --url)")
|
|
925
|
+
common(e)
|
|
926
|
+
return ap
|
|
927
|
+
|
|
928
|
+
|
|
929
|
+
def run(argv=None):
|
|
930
|
+
"""The command of argv -> its report (SystemExit with the message of a refusal)."""
|
|
931
|
+
a = parser().parse_args(argv)
|
|
932
|
+
try:
|
|
933
|
+
return cmd_fit(a) if a.command == "fit" else cmd_evaluate(a)
|
|
934
|
+
except (FitError, JSONLError, dr.DecisionRulesError, OSError) as e:
|
|
935
|
+
raise SystemExit(f"basal-fit-decisions: {e}") from None
|
|
936
|
+
|
|
937
|
+
|
|
938
|
+
def main(argv=None):
|
|
939
|
+
"""The console script (sys.exit(main())): None, exit status 0, once the command has run."""
|
|
940
|
+
run(argv)
|
|
941
|
+
|
|
942
|
+
|
|
943
|
+
if __name__ == "__main__":
|
|
944
|
+
sys.exit(main())
|