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/router_ui.py ADDED
@@ -0,0 +1,277 @@
1
+ """basal-router --ui on (2.5): one live page for the router and every replica behind it, at GET /ui, read from
2
+ GET /ui/state.
3
+
4
+ The router's part (replicas, readiness, requests in flight, routing by state / by load, failures, the cascade, blend,
5
+ fallback and script counters, traffic through the router since start, the recent requests) comes from its own
6
+ counters and from a bounded ring: a decision request pays one append of its metadata (end time, endpoint, status,
7
+ seconds, the replica it went to and how it was chosen; never its text). Each replica's part is that replica's own
8
+ GET /ui/state (basal-serve --ui on), read when GET /ui/state of the router is read, at most once a second however
9
+ many pages poll it, with the client's API key headers passed on as for requests. A replica without --ui (404), one
10
+ that wants a key (401), or one that is not ready shows what the router knows of it. Nothing is read from the replicas
11
+ while no page is open, and everything lives in memory only: every start begins at zero. With --ui off (the default)
12
+ this module is not imported and the router handles requests as without it."""
13
+ import asyncio
14
+ import bisect
15
+ import hashlib
16
+ import json
17
+ import sys
18
+ import time
19
+ from collections import deque
20
+ from contextvars import ContextVar
21
+
22
+ from .router import POLL_S, key_headers
23
+ from .ui import END, FOLD, MEMO_S, RECENT, RING, Hist, _ms, exact, redact, with_page
24
+ from .ui import versions as ui_versions
25
+
26
+ DECISIONS = ("/v1/systemone", "/v1/basal", "/v1/decisions") # the router's routes whose requests are recorded
27
+ REPLICA_TIMEOUT = 2.0 # seconds a replica's GET /ui/state may take; then the page shows what the router knows
28
+ MEMO_KEYS = 8 # snapshots kept, one per set of key headers (a viewer's key never reads another key's snapshot)
29
+ KEEP = ("now", "started", "ready_at", "uptime", "status", "traffic", "cache", "telemetry") # of a replica's state
30
+ PACKAGES = ("starlette", "uvicorn", "httpx", "uvloop", "httptools")
31
+ UI_BY_STATUS = {404: "off", 401: "key", 403: "key", 503: "not ready"}
32
+ PICK = ContextVar("basal_router_ui_pick", default=None) # a recorded request's first (replica, how), set by choose
33
+
34
+
35
+ def routed_of(rt, url):
36
+ """A replica's requests by how they were routed: "state" counts those of --state-holders and --prefix-affinity
37
+ too (all routed by the state), which are also given as "held" and "prefix" when the options are on."""
38
+ got = {h: rt.routed.get((url, h), 0) for h in getattr(rt, "hows", ("state", "load"))}
39
+ return {"state": got.get("state", 0) + got.get("held", 0) + got.get("prefix", 0), "load": got.get("load", 0),
40
+ **{h: got[h] for h in ("held", "prefix") if h in got}}
41
+
42
+
43
+ def slim(state):
44
+ """The parts of a replica's GET /ui/state the router's page shows: status, traffic, state cache, telemetry and the
45
+ resolved facts of its configuration (not its option list nor its recent requests). None when it is not a state."""
46
+ if not isinstance(state, dict) or not isinstance(state.get("status"), dict):
47
+ return None
48
+ out = {k: state.get(k) for k in KEEP}
49
+ cfg = state.get("config")
50
+ out["facts"] = cfg.get("facts") if isinstance(cfg, dict) else None
51
+ return out
52
+
53
+
54
+ def shown(name, value):
55
+ """An option's value as the page shows it: redact()'s, and for --route SCRIPT=URL[,URL] each URL redacted on its
56
+ own (the whole value parses as no URL: its user, password and query would be shown)."""
57
+ if name == "fallback_extra":
58
+ return "(set)" if value else value
59
+ if name == "max_requests_per_key": # (a number, not a key: "key" in its name made redact hide it)
60
+ return value
61
+ if name == "route" and isinstance(value, list):
62
+ return [x.partition("=")[0] + "=" + ",".join(redact("url", u) for u in x.partition("=")[2].split(","))
63
+ if isinstance(x, str) and "=" in x else redact(name, x) for x in value]
64
+ return redact(name, value)
65
+
66
+
67
+ def versions():
68
+ return ui_versions(PACKAGES) # (basal-serve's reader; no torch here, so no CUDA line)
69
+
70
+
71
+ class RouterUI:
72
+ """The state behind the router's page. Built in main before the router serves; app takes its routes and page."""
73
+
74
+ def __init__(self, router, a=None, defaults=None):
75
+ from . import __version__
76
+ self.router, self.version = router, __version__
77
+ self.ring = deque(maxlen=RING) # (end perf_counter, endpoint, status, seconds, replica URL or None, how or None)
78
+ self.counts = [0, 0] # requests answered and failed (status >= 400) since start, whatever the ring kept
79
+ self.wall0, self.perf0 = time.time(), time.perf_counter()
80
+ self.folded, self.seen = self.perf0, 0 # end time of the last request in the totals, and their count
81
+ self.total, self.endpoints, self.codes, self.per = Hist(), {}, {}, {}
82
+ self.memo, self.lock = {}, None # {hash of the key headers: (perf_counter, bytes)}; asyncio.Lock at a read
83
+ self.pools = {}
84
+ for name, urls in router.pools.items():
85
+ for u in urls:
86
+ self.pools.setdefault(u, []).append(name)
87
+ defaults = defaults or {}
88
+ opts = vars(a) if a is not None else {}
89
+ self.config = {"options": [[k, shown(k, v), k in defaults and defaults[k] != v] for k, v in opts.items()],
90
+ "facts": self.facts()}
91
+ self.attach()
92
+
93
+ def attach(self):
94
+ """The router's choose, wrapped (on this router only) to tell a recorded request which replica it went to:
95
+ the first choice made for it (the replica its pool and state give; cascade / blend calls come after)."""
96
+ choose = self.router.choose
97
+
98
+ def chosen(key, pool="main", hs=None, only=None):
99
+ out = choose(key, pool, hs, only)
100
+ box = PICK.get()
101
+ if box is not None and not box:
102
+ box.extend(out)
103
+ return out
104
+ self.router.choose = chosen
105
+
106
+ def facts(self):
107
+ rt = self.router
108
+ pools = ", ".join(f"{name} ({len(u)})" for name, u in rt.pools.items() if u)
109
+ out = [["replicas", len(rt.replicas)], ["pools", pools],
110
+ ["routing", "consistent hash of the state, bounded load; no state: the less loaded of two"],
111
+ ["load factor", rt.factor], ["readiness", f"GET /health every {POLL_S:g} s"],
112
+ ["affinity", ", ".join(n for n, on in (("state holders", getattr(rt, "holding", False)),
113
+ ("prefix", getattr(rt, "prefix", False))) if on) or None],
114
+ ["cascade levels", len(rt.levels) + 1 if rt.levels else None],
115
+ ["blend models", len(rt.blends) + 1 if rt.blends else None],
116
+ ["fallback model", rt.fallback["model"] if rt.fallback else None],
117
+ ["python", sys.version.split()[0]]]
118
+ out += [[name, v] for name, v in versions().items()]
119
+ return [[k, v] for k, v in out if v not in (None, "")]
120
+
121
+ def record(self, handler, endpoint):
122
+ """handler with its request's metadata appended to the ring once it is answered: all the work --ui on adds to
123
+ a request (the replica comes from choose, through a context variable). The body is not read here."""
124
+ ring, clock, counts = self.ring, time.perf_counter, self.counts
125
+
126
+ async def recorded(request):
127
+ box = []
128
+ token = PICK.set(box)
129
+ t = clock()
130
+ try:
131
+ response = await handler(request)
132
+ finally:
133
+ PICK.reset(token)
134
+ t1 = clock()
135
+ status = response.status_code
136
+ counts[0] += 1
137
+ counts[1] += status >= 400
138
+ ring.append((t1, endpoint, status, t1 - t, *(box or (None, None))))
139
+ return response
140
+ recorded.__name__ = f"recorded_{handler.__name__}"
141
+ return recorded
142
+
143
+ def routes(self, routes):
144
+ """The router's routes with the decision routes recorded, and GET /ui/state."""
145
+ from starlette.responses import Response
146
+ from starlette.routing import Route
147
+
148
+ async def state(request):
149
+ body = await self.state(key_headers(request.headers.raw))
150
+ return Response(body, media_type="application/json", headers={"Cache-Control": "no-store"})
151
+ out = [Route(r.path, self.record(r.endpoint, r.path), methods=sorted(r.methods))
152
+ if isinstance(r, Route) and r.path in DECISIONS else r for r in routes]
153
+ return out + [Route("/ui/state", state)]
154
+
155
+ def page(self, app):
156
+ """app with GET /ui (the page) and its fonts (basal-serve's) in front of it."""
157
+ return with_page(app, "router_ui.html")
158
+
159
+ async def state(self, keys):
160
+ """GET /ui/state: the JSON snapshot, built at most once per MEMO_S for each set of key headers (the replicas'
161
+ parts depend on the key the page sent)."""
162
+ mk = hashlib.sha256(repr(sorted(keys.items())).encode()).digest()
163
+ hit = self.memo.get(mk)
164
+ if hit is not None and time.perf_counter() - hit[0] < MEMO_S:
165
+ return hit[1]
166
+ if self.lock is None:
167
+ self.lock = asyncio.Lock()
168
+ async with self.lock: # (pages polling at once: one build, the others take it)
169
+ hit = self.memo.get(mk)
170
+ if hit is not None and time.perf_counter() - hit[0] < MEMO_S:
171
+ return hit[1]
172
+ reps = await asyncio.gather(*(self.replica(r, keys) for r in self.router.replicas))
173
+ data = self.build(reps)
174
+ if len(self.memo) >= MEMO_KEYS:
175
+ self.memo.clear()
176
+ self.memo[mk] = (time.perf_counter(), data)
177
+ return data
178
+
179
+ async def replica(self, url, keys):
180
+ """(a replica's slimmed GET /ui/state or None, what its UI said: on, off, key, not ready, unreachable, error)."""
181
+ if url not in self.router.ready:
182
+ return None, "not ready", None
183
+ try:
184
+ r = await self.router.client.get(url + "/ui/state", headers=keys, timeout=REPLICA_TIMEOUT)
185
+ except Exception as e: # noqa: BLE001 (down, refused, slower than REPLICA_TIMEOUT)
186
+ return None, "unreachable", type(e).__name__
187
+ if r.status_code != 200:
188
+ return None, UI_BY_STATUS.get(r.status_code, "error"), r.status_code
189
+ try:
190
+ s = slim(json.loads(r.content))
191
+ except ValueError:
192
+ s = None
193
+ return (s, "on", None) if s is not None else (None, "error", "not a basal-serve state")
194
+
195
+ def fold(self, rows):
196
+ """Requests answered since the last read (rows: the ring's, oldest first) into the totals since start, at most
197
+ FOLD of them per read (the rest at the next); "seen" counts the ones in the totals."""
198
+ new = rows[bisect.bisect_right(rows, self.folded, key=END):][:FOLD]
199
+ if not new:
200
+ return
201
+ self.folded = new[-1][0]
202
+ self.seen += len(new)
203
+ bin_of, total, endpoints, codes, per = Hist.bin, self.total, self.endpoints, self.codes, self.per
204
+ for _, ep, status, s, rep, _ in new:
205
+ ms = s * 1000
206
+ i = bin_of(ms)
207
+ total.add(ms, i)
208
+ codes[status] = codes.get(status, 0) + 1
209
+ for name, table in ((ep, endpoints), (rep, per)):
210
+ if name is None:
211
+ continue
212
+ e = table.get(name)
213
+ if e is None:
214
+ e = table[name] = {"requests": 0, "failed": 0, "hist": Hist()}
215
+ e["requests"] += 1
216
+ e["failed"] += status >= 400
217
+ e["hist"].add(ms, i)
218
+
219
+ def build(self, reps):
220
+ rt = self.router
221
+ now = time.perf_counter()
222
+ rows = list(self.ring) # one copy; the rows are in the order of their end times
223
+ self.fold(rows)
224
+ i60 = bisect.bisect_left(rows, now - 60, key=END)
225
+ w60 = [r[3] for r in rows[i60:]] # seconds of the requests answered in the last 60 and 10 s
226
+ w10 = w60[bisect.bisect_left(rows, now - 10, lo=i60, key=END) - i60:]
227
+ up = now - self.perf0
228
+ q50, q95, q99 = self.total.quantiles()
229
+ index = {u: k for k, u in enumerate(rt.replicas)}
230
+ replicas = []
231
+ for k, (url, (state, ui, detail)) in enumerate(zip(rt.replicas, reps)):
232
+ e = self.per.get(url)
233
+ p50, p95 = e["hist"].quantiles((0.5, 0.95)) if e else (None, None)
234
+ replicas.append({
235
+ "index": k, "url": redact("url", url), "pools": self.pools.get(url, []), "ready": url in rt.ready,
236
+ "in_flight": rt.load.get(url, 0), "routed": routed_of(rt, url),
237
+ "failed": rt.failed.get(url, 0), "requests": e["requests"] if e else 0, "p50": p50, "p95": p95,
238
+ "ui": ui, "detail": detail, "state": state})
239
+ features = {}
240
+ if rt.levels:
241
+ features["cascade"] = {"below": [b for _, b in rt.levels], "answered": dict(rt.answered),
242
+ "levels": {str(k): n for k, n in rt.by_level.items()}}
243
+ if rt.blends:
244
+ features["blend"] = {"weights": [rt.blend_weight] + [w for _, w in rt.blends],
245
+ "blended": {str(k): n for k, n in sorted(rt.blended.items())}}
246
+ if rt.fallback:
247
+ features["fallback"] = {"model": rt.fallback["model"], "below": rt.fallback["below"],
248
+ "results": dict(rt.fallback_counts)}
249
+ scripts = [name[7:] for name in rt.pools if name.startswith("script:") and rt.pools[name]]
250
+ if scripts:
251
+ features["route"] = {"scripts": scripts, "requests": dict(sorted(rt.scripts.items()))}
252
+ d = {
253
+ # "now" on the rows' clock (wall0 + perf_counter), as basal/ui.py: no row ends after it
254
+ "now": round(self.wall0 + time.perf_counter() - self.perf0, 3), "started": round(self.wall0, 3),
255
+ "uptime": round(up, 3),
256
+ "version": self.version,
257
+ "router": {"replicas": len(rt.replicas), "ready": len(rt.ready), "in_flight": sum(rt.load.values()),
258
+ "load_factor": rt.factor},
259
+ "traffic": {
260
+ "requests": self.counts[0], "failed": self.counts[1], "seen": self.seen, "ring": RING,
261
+ "rate10": round(len(w10) / min(10.0, up), 3) if up > 0 else 0,
262
+ "rate60": round(len(w60) / min(60.0, up), 3) if up > 0 else 0,
263
+ "latency": {"p50": q50, "p95": q95, "p99": q99, "max": self.total.max or None,
264
+ "mean": self.total.sum / self.total.n if self.total.n else None},
265
+ "w10": dict(zip(("p50", "p95", "p99"), map(_ms, exact(w10))), n=len(w10)),
266
+ "w60": dict(zip(("p50", "p95", "p99"), map(_ms, exact(w60))), n=len(w60)),
267
+ "endpoints": [{"endpoint": ep, "requests": e["requests"], "failed": e["failed"],
268
+ **dict(zip(("p50", "p95"), e["hist"].quantiles((0.5, 0.95)))),
269
+ "mean": e["hist"].sum / e["hist"].n} for ep, e in sorted(self.endpoints.items())],
270
+ "codes": {str(k): v for k, v in sorted(self.codes.items())}},
271
+ "replicas": replicas,
272
+ "features": features,
273
+ "config": self.config,
274
+ "recent": [[round(self.wall0 + r[0] - self.perf0, 3), r[1], r[2], _ms(r[3]), index.get(r[4]), r[5]]
275
+ for r in reversed(rows[-RECENT:])],
276
+ }
277
+ return json.dumps(d, separators=(",", ":")).encode()
basal/run.py ADDED
@@ -0,0 +1,376 @@
1
+ """Batch inference: send every line of a JSONL file to a running basal server and write one answer per line.
2
+
3
+ basal-run --input basal/examples/questions.jsonl --output answers.jsonl --url http://127.0.0.1:8000/v1/systemone
4
+
5
+ Two input formats are accepted (they can be mixed):
6
+ simple {"id": ..., "state": "...", "question": "...", "options": ["...", "..."], "type": "choice"|"noul"|"score",
7
+ "gold": <index, optional>} type defaults to "choice"; for "noul" the options are [yes-text, no-text]
8
+ request {"id": ..., "state": ..., "questions": {...}, "early_exit": ..., ...} a full /v1/systemone request body:
9
+ every field is sent as it is (media, facts, lang, think, ...) except the line's own "id", "gold", "group",
10
+ "family" and fields whose name starts with "_"
11
+
12
+ Output (one line per input line, same order): {"id", "answers", "latency_ms"} plus, for simple lines, "prediction"
13
+ (index of the chosen option), "confidence" and "correct" when "gold" is given; a line that cannot be sent or read
14
+ back gets "error" instead, and the other lines go on. Lines are read and answers written as they go (at most a few
15
+ times --concurrency lines are held), into <output>.part, renamed to <output> at the end (an existing <output> is
16
+ replaced then): an interrupted run keeps the answers so far, in order, in <output>.part. A summary (accuracy if gold is present, latency) is printed at the end.
17
+
18
+ Resuming (2.8): the same command, run again after an interruption, goes on from <output>.part instead of starting
19
+ again: its answers are kept and only the lines after them are sent (a line cut short by the interruption, and errors
20
+ after the last answer, are sent again). <output>.part.json records the run: the --input file's size and sha256, the
21
+ options that make the requests (--preset, --lang, --early-exit) and the server's GET /v1/models. A .part of another
22
+ input, other options or another server is refused, as is one without that record; --restart replaces it.
23
+ --concurrency may differ.
24
+
25
+ A server that stops answering (2.8): after --stop-after (16) lines in a row that it did not answer (a connection
26
+ error, or HTTP 502, 503 or 504), the run stops instead of failing every line after them. Those lines are not written,
27
+ so <output>.part ends with the last answer, and the same command, run again once the server is back, goes on from
28
+ there. Fewer such lines between answers are each an "error" line, as any other failed line.
29
+ """
30
+ import argparse
31
+ import asyncio
32
+ import collections
33
+ import hashlib
34
+ import json
35
+ import os
36
+ import statistics
37
+ import sys
38
+ import time
39
+ from pathlib import Path
40
+
41
+ import httpx
42
+
43
+ from .cli import add_api_key, headers, positive, refused
44
+ from .jsonl import dumps, finite
45
+ from .textio import open_text
46
+
47
+ LOCAL = ("id", "gold", "group", "family") # a line's own fields (as basal-calibrate reads them), never sent
48
+ GONE = (502, 503, 504) # no answer from the server now: a proxy without its server, starting / overloaded, timed out
49
+ STOP_AFTER = 16 # --stop-after: lines in a row the server did not answer, after which the run stops
50
+
51
+
52
+ def to_request(item, early_exit=None, preset=None, lang=None):
53
+ if preset and "questions" not in item and "question" not in item: # --preset: its questions over the state
54
+ from basal_sdk.presets import questions
55
+ item = dict(item, questions=questions(preset, lang, item["state"]))
56
+ if "questions" in item: # a full request: every field but the line's own
57
+ body = {k: v for k, v in item.items() if k not in LOCAL and not k.startswith("_")}
58
+ else:
59
+ t, opts = item.get("type", "choice"), item["options"]
60
+ if t == "noul":
61
+ if len(opts) != 2:
62
+ raise ValueError("a noul item needs exactly two options: [yes-text, no-text]")
63
+ crit = {"true": opts[0], "false": opts[1]}
64
+ else:
65
+ crit = {str(k): o for k, o in enumerate(opts)}
66
+ q = {"type": t, "instructions": item["question"], "criteria": crit}
67
+ if t != "noul":
68
+ q["option_keys"] = "hide" # keys are the placeholders "0", "1", ...; the option texts define the options
69
+ body = {"state": item["state"], "questions": {"q": q}}
70
+ if early_exit and "early_exit" not in body:
71
+ body["early_exit"] = early_exit
72
+ return body
73
+
74
+
75
+ def summarise(item, resp):
76
+ out = {"id": item.get("id"), "answers": resp.get("answers"), "latency_ms": resp.get("usage", {}).get("latency_ms")}
77
+ if "question" in item and "questions" not in item and resp.get("answers"): # a simple line (a --preset line has neither)
78
+ a = resp["answers"]["q"]
79
+ p = a["probabilities"]
80
+ keys = ["true", "false"] if a["type"] == "noul" else [str(k) for k in range(len(item["options"]))]
81
+ pred = max(range(len(keys)), key=lambda k: p[keys[k]])
82
+ out.update(prediction=pred, option=item["options"][pred], confidence=a["confidence"])
83
+ if "gold" in item:
84
+ out["correct"] = pred == item["gold"]
85
+ if "error" in resp:
86
+ out["error"] = resp["error"]
87
+ return out
88
+
89
+
90
+ class KeyRefused(Exception):
91
+ """The server refused the API key (HTTP 401 / 403): every other line would fail the same way."""
92
+
93
+
94
+ class ServerGone(Exception):
95
+ """The server answered none of the last --stop-after lines (a connection error, or HTTP 502 / 503 / 504): it stopped
96
+ or cannot be reached, and every line after them would fail the same way."""
97
+
98
+
99
+ def failed(i, error, answers=None):
100
+ return {"id": i, "answers": answers, "latency_ms": None, "error": str(error)}
101
+
102
+
103
+ def same_file(a, b):
104
+ a, b = Path(a), Path(b)
105
+ try:
106
+ return a.resolve() == b.resolve() or b.exists() and os.path.samefile(a, b)
107
+ except OSError:
108
+ return False
109
+
110
+
111
+ def lines(path):
112
+ """The item of every non-blank line (or the error of a line that is not a JSON object), read as they go and split
113
+ at "\n" only (U+2028 inside a string stays in its line); UTF-8 with or without a BOM, or UTF-16 with its BOM."""
114
+ with open_text(path, newline="\n") as f:
115
+ for n, line in enumerate(f, 1):
116
+ if not line.strip():
117
+ continue
118
+ try:
119
+ item = json.loads(line)
120
+ except ValueError as e:
121
+ yield ValueError(f"line {n}: not JSON ({e})")
122
+ continue
123
+ yield item if isinstance(item, dict) else ValueError(f"line {n}: not a JSON object")
124
+
125
+
126
+ def fingerprint(path):
127
+ """The --input file's size and sha256, or None when it is not a file (a pipe cannot be read again to check it)."""
128
+ p = Path(path)
129
+ if not p.is_file():
130
+ return None
131
+ h = hashlib.sha256()
132
+ with open(p, "rb") as f:
133
+ for chunk in iter(lambda: f.read(1 << 20), b""):
134
+ h.update(chunk)
135
+ return {"bytes": p.stat().st_size, "sha256": h.hexdigest()}
136
+
137
+
138
+ def run_options(a):
139
+ """The options that make the requests: a resumed run must send the same."""
140
+ return {"preset": getattr(a, "preset", None), "lang": getattr(a, "lang", None), "early_exit": a.early_exit}
141
+
142
+
143
+ async def served_models(c, url):
144
+ """GET /v1/models of the server behind --url (the served model, mode, calibration), or None when it does not
145
+ answer it."""
146
+ if "/v1/" not in url:
147
+ return None
148
+ try:
149
+ r = await c.get(url.split("/v1/")[0] + "/v1/models")
150
+ return r.json() if r.status_code == 200 else None
151
+ except Exception: # noqa: BLE001 (not served, not JSON, down)
152
+ return None
153
+
154
+
155
+ def resume_refused(record, want, part):
156
+ """Why <output>.part cannot be continued by this run (its record against this run's), or None."""
157
+ if record is None:
158
+ return f"it has no record of its run ({part}.json, written by basal-run 2.8 and later)"
159
+ if want["input"] is None:
160
+ return "the --input is not a file, so it cannot be checked to be the same"
161
+ if record.get("input") != want["input"]:
162
+ return "another --input (its size or contents differ)"
163
+ other = [k for k in want["options"] if record.get("options", {}).get(k) != want["options"][k]]
164
+ if other:
165
+ return "other options: " + ", ".join(f"--{k.replace('_', '-')}" for k in other)
166
+ if record.get("models") is not None and want["models"] is not None and record["models"] != want["models"]:
167
+ return "another server (its GET /v1/models differs: another model, mode or calibration)"
168
+ return None
169
+
170
+
171
+ def kept(part, items):
172
+ """The answers of <output>.part a resumed run keeps: its complete lines, each the answer of the input line of its
173
+ place (its id), up to the last one without an error -> (bytes kept, [what the summary counts of each]). A line
174
+ cut short by the interruption and the errors after the last answer are sent again."""
175
+ good, end, upto = [], 0, (0, 0) # (bytes, lines) up to the last answer
176
+ with open(part, "rb") as f:
177
+ for i, it in enumerate(items):
178
+ line = f.readline()
179
+ if not line.endswith(b"\n"): # (the end, or a line cut short)
180
+ break
181
+ try:
182
+ r = json.loads(line)
183
+ except ValueError:
184
+ break
185
+ want = it.get("id", i) if isinstance(it, dict) else i
186
+ if not isinstance(r, dict) or r.get("id") != want:
187
+ break
188
+ good.append({k: r[k] for k in ("error", "latency_ms", "correct") if k in r})
189
+ end += len(line)
190
+ if "error" not in r:
191
+ upto = (end, len(good))
192
+ return upto[0], good[: upto[1]]
193
+
194
+
195
+ async def run(a, transport=None):
196
+ if same_file(a.input, a.output):
197
+ raise SystemExit(f"--output {a.output} is the --input file: give another file (the answers would replace "
198
+ "the requests)")
199
+ part = Path(str(a.output) + ".part")
200
+ record_path = Path(str(part) + ".json")
201
+ sem = asyncio.Semaphore(a.concurrency)
202
+ window = collections.deque() # the lines in flight, in input order (a bounded reorder buffer)
203
+ n_items = n_err = 0
204
+ lat, graded = [], []
205
+ key = getattr(a, "api_key", None)
206
+ async with httpx.AsyncClient(timeout=300, transport=transport, headers=headers(key)) as c:
207
+ async def one(i, it):
208
+ if isinstance(it, Exception):
209
+ return failed(i, it)
210
+ it.setdefault("id", i)
211
+ async with sem:
212
+ try:
213
+ body = to_request(it, a.early_exit, getattr(a, "preset", None), getattr(a, "lang", None))
214
+ except (KeyError, TypeError, ValueError, AttributeError) as e: # a malformed line: its own error
215
+ return failed(it["id"], f"not a valid line: {type(e).__name__}: {e}")
216
+ gone = False # the server did not answer this line (ServerGone after a run of them)
217
+ try:
218
+ r = await c.post(a.url, json=body)
219
+ if refused(a.url, r.status_code, key):
220
+ raise KeyRefused(refused(a.url, r.status_code, key))
221
+ gone = r.status_code in GONE
222
+ try:
223
+ resp = r.json()
224
+ except ValueError as e:
225
+ resp = {"error": f"HTTP {r.status_code}" if gone else str(e) or type(e).__name__}
226
+ except httpx.TransportError as e: # (connection refused or reset, a timeout)
227
+ gone, resp = True, {"error": str(e) or type(e).__name__}
228
+ except httpx.HTTPError as e:
229
+ resp = {"error": str(e) or type(e).__name__}
230
+ try:
231
+ out = summarise(it, resp)
232
+ except (KeyError, TypeError, ValueError, AttributeError, IndexError) as e:
233
+ out = failed(it["id"], f"unexpected answer: {type(e).__name__}: {e}",
234
+ resp.get("answers") if isinstance(resp, dict) else None)
235
+ if gone and "error" in out:
236
+ out["_gone"] = True
237
+ return out
238
+
239
+ def count(r):
240
+ nonlocal n_items, n_err
241
+ n_items += 1
242
+ if "error" in r:
243
+ n_err += 1
244
+ return
245
+ if r.get("latency_ms") is not None:
246
+ lat.append(r["latency_ms"])
247
+ if "correct" in r:
248
+ graded.append(r["correct"])
249
+
250
+ def write(f, r):
251
+ try:
252
+ line = dumps(r)
253
+ except ValueError as e: # a NaN or an infinity (another server's answer): no JSON line, so an error line
254
+ r = failed(finite(r.get("id")), f"the answer cannot be written as JSON: {e}")
255
+ line = dumps(r)
256
+ f.write(line + "\n")
257
+ count(r)
258
+
259
+ held = [] # the last lines the server did not answer, not written yet (written when an answer follows)
260
+ stop_after = getattr(a, "stop_after", STOP_AFTER)
261
+
262
+ def put(f, r):
263
+ if r.pop("_gone", False) and stop_after:
264
+ held.append(r)
265
+ if len(held) >= stop_after:
266
+ raise ServerGone(f"the server answered none of the last {len(held)} lines (the last: "
267
+ f"{r['error'][:200]}): it stopped or cannot be reached")
268
+ return
269
+ for h in held:
270
+ write(f, h)
271
+ held.clear()
272
+ write(f, r)
273
+
274
+ want = {"basal_run": 1, "input": fingerprint(a.input), "options": run_options(a),
275
+ "models": await served_models(c, a.url)}
276
+ skip = 0
277
+ if part.exists() and not getattr(a, "restart", False):
278
+ try:
279
+ record = json.loads(record_path.read_text(encoding="utf-8")) if record_path.exists() else None
280
+ except ValueError:
281
+ record = None
282
+ why = resume_refused(record, want, part)
283
+ if why:
284
+ raise SystemExit(f"basal-run: {part} is from another run: {why}. --restart replaces it (its answers "
285
+ "are lost), or give another --output")
286
+ size, old = kept(part, lines(a.input))
287
+ with open(part, "r+b") as f:
288
+ f.truncate(size)
289
+ for r in old:
290
+ count(r)
291
+ skip = len(old)
292
+ unchecked = " (the server not compared: no GET /v1/models)" if want["models"] is None else ""
293
+ print(f"basal-run: resuming {part}: {skip} answers kept, going on from line {skip + 1}{unchecked}",
294
+ file=sys.stderr)
295
+ else:
296
+ tmp = Path(str(record_path) + ".tmp")
297
+ tmp.write_text(json.dumps(want, ensure_ascii=False), encoding="utf-8")
298
+ os.replace(tmp, record_path)
299
+
300
+ done = False
301
+ t0 = time.perf_counter()
302
+ with open(part, "a" if skip else "w", encoding="utf-8") as f:
303
+ try: # (KeyRefused ends the run below, after the answers so far are kept)
304
+ for i, it in enumerate(lines(a.input)):
305
+ if i < skip: # (answered by the run this one resumes)
306
+ continue
307
+ window.append(asyncio.ensure_future(one(i, it)))
308
+ while len(window) >= 4 * a.concurrency or window and window[0].done():
309
+ put(f, await window.popleft())
310
+ while window:
311
+ put(f, await window.popleft())
312
+ for h in held: # (fewer than --stop-after at the end: error lines, as any other)
313
+ write(f, h)
314
+ done = True
315
+ finally:
316
+ for t in window: # the lines in flight are dropped (an exception of a finished one is read)
317
+ if not t.done():
318
+ t.cancel()
319
+ elif not t.cancelled():
320
+ t.exception()
321
+ if not done:
322
+ f.flush()
323
+ print(f"basal-run: stopped; the {n_items} answers so far are in {part}: the same command goes on "
324
+ "from there (--restart starts again)", file=sys.stderr)
325
+ wall = time.perf_counter() - t0
326
+ os.replace(part, a.output)
327
+ record_path.unlink(missing_ok=True)
328
+ s = {"items": n_items, "errors": n_err, "seconds": round(wall, 2),
329
+ "items_per_s": round(n_items / wall, 1) if wall else None,
330
+ "server_latency_p50_ms": round(statistics.median(lat), 2) if lat else None}
331
+ if graded:
332
+ s["accuracy"] = round(sum(graded) / len(graded), 4)
333
+ print(json.dumps(s))
334
+
335
+
336
+ def main():
337
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
338
+ ap.add_argument("--input", help="JSONL file")
339
+ ap.add_argument("--output", help="JSONL file with one answer per input line (an existing file is replaced; not the "
340
+ "--input file)")
341
+ ap.add_argument("--preset", default=None, help="ready questions for lines with a state only (--list-presets)")
342
+ ap.add_argument("--lang", choices=["pl", "en"], default=None, help="--preset wording (default: the state's)")
343
+ ap.add_argument("--list-presets", dest="list_presets", action="store_true")
344
+ ap.add_argument("--url", default="http://127.0.0.1:8000/v1/systemone")
345
+ ap.add_argument("--concurrency", type=positive, default=16, help="requests in flight (the server batches them)")
346
+ ap.add_argument("--early-exit", dest="early_exit", default=None, help="e.g. 0.99 (server mode fast-exit)")
347
+ ap.add_argument("--stop-after", dest="stop_after", type=int, default=STOP_AFTER,
348
+ help="stop the run after this many lines in a row that the server did not answer (a connection "
349
+ "error, HTTP 502 / 503 / 504), keeping <output>.part for the same command to go on from; 0: "
350
+ "never stop (every such line is an error line)")
351
+ ap.add_argument("--restart", action="store_true",
352
+ help="start again: replace an <output>.part of an interrupted run (by default the same command "
353
+ "goes on from it, and a .part of another run is refused)")
354
+ add_api_key(ap)
355
+ a = ap.parse_args()
356
+ if a.list_presets:
357
+ from basal_sdk.presets import names, questions
358
+ for n in names():
359
+ print(n + ": " + ", ".join(questions(n, "en")))
360
+ return
361
+ if not a.input or not a.output:
362
+ ap.error("--input and --output are required")
363
+ if a.preset:
364
+ from basal_sdk.presets import names
365
+ if a.preset not in names():
366
+ ap.error(f"--preset {a.preset}: one of {', '.join(names())}")
367
+ if a.stop_after < 0:
368
+ ap.error("--stop-after: 0 (never) or more lines")
369
+ try:
370
+ asyncio.run(run(a))
371
+ except (KeyRefused, ServerGone) as e:
372
+ raise SystemExit(f"basal-run: {e}") from None
373
+
374
+
375
+ if __name__ == "__main__":
376
+ main()