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/rank.py
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
"""The rank question type (experimental, 2.5): rank thousands of candidates in one request, beyond the 255 options of
|
|
2
|
+
a choice question.
|
|
3
|
+
|
|
4
|
+
{"type": "rank", "instructions": "Does {candidate} contain information needed to answer the user's question?",
|
|
5
|
+
"candidates": {key: text} | [text, ...] | [{"key": ..., "text": ..., "group": ...}, ...], (10,000 per request)
|
|
6
|
+
"label": "Passage", "list_title": "Passages", "chunk": 50, "top": 20, "choice_instructions": "Which passage ...?",
|
|
7
|
+
"choice_context": "auto" | "screen" | "shortlist", "order": "state_first" | "candidates_first",
|
|
8
|
+
"prior": {key: weight}, "limit": 100}
|
|
9
|
+
|
|
10
|
+
Screening: the candidates are numbered in a list ("Passage 7: <text>", under a "[<group>]" line when they have one; a
|
|
11
|
+
text of several lines keeps them, each line after the first indented by two spaces so that it cannot pass for an
|
|
12
|
+
entry, and a group name is put on one line) and packed, in their order, into requests of `chunk` candidates (a group
|
|
13
|
+
stays in one request when it fits). Each request's state is the request's own state and its list; every candidate in
|
|
14
|
+
it is one yes / no question ("{candidate}" in the instructions names it), so the request reads its state once (SOAM)
|
|
15
|
+
and judges its candidates side by side. The requests go through the server's queue together, at most PARALLEL at
|
|
16
|
+
once. A candidate's score is its calibrated P(yes), times its `prior` weight.
|
|
17
|
+
|
|
18
|
+
Final choice (`top` >= 2): one choice question over the top `top` candidates by score, whose options are their names in
|
|
19
|
+
the list; its probabilities reorder them, the others keep their score order. Its context is the screening request's
|
|
20
|
+
state when one request held every candidate (`screen`: with --state-cache-gb that state is cached, so only the question
|
|
21
|
+
is computed), or the request's state with a list of only the shortlisted candidates (`shortlist`); `auto` picks
|
|
22
|
+
`screen` when it can. `candidates_first` puts the list before the request's state, so requests about the same
|
|
23
|
+
candidates share a cached prefix (--state-cache-gb) across different states.
|
|
24
|
+
|
|
25
|
+
Answer: {"type": "rank", "ranking": [{"key", "score", "choice"?, "yes"?}, ...] (best first; "choice" on the shortlisted
|
|
26
|
+
ones, "yes" the P(yes) before the prior), "top": key, "candidates": N, "requests": n, "experimental": true}. Every other
|
|
27
|
+
question of the request is answered as usual over the request's state.
|
|
28
|
+
"""
|
|
29
|
+
import asyncio
|
|
30
|
+
import json
|
|
31
|
+
import math
|
|
32
|
+
import time
|
|
33
|
+
|
|
34
|
+
from .prompt import MAX_OPTIONS, RequestError, lang_of
|
|
35
|
+
|
|
36
|
+
MAX_CANDIDATES = 10_000 # per request, all its rank questions together (basal-serve --rank-max-candidates)
|
|
37
|
+
MAX_CHUNK = 1_000
|
|
38
|
+
TOP = 20 # shortlist of the final choice (at most the model's options per question)
|
|
39
|
+
CHUNK = 50 # candidates per request: the gain of a shared context levels off at about 50 (chunk 0 falls back to it)
|
|
40
|
+
CONTEXTS = ("auto", "screen", "shortlist")
|
|
41
|
+
ORDERS = ("state_first", "candidates_first")
|
|
42
|
+
LABEL = {"en": "Candidate", "pl": "Kandydat"}
|
|
43
|
+
CHOICE = {"en": "Which {label} is the best match?", "pl": "Która pozycja najlepiej pasuje?"}
|
|
44
|
+
MARGIN = 96 # tokens kept free for a question and its options when a whole list must fit one request (chunk 0)
|
|
45
|
+
# chunk 0: one shared context only while the list's state has at most this many tokens. Every question of the request
|
|
46
|
+
# reads the whole state, so past it requests of CHUNK answer the same list faster: a one-way model in --mode fast
|
|
47
|
+
# (RTX PRO 6000, 8 Nov 2026) took 1.08x the time of chunks at 8.7k tokens, 1.36x at 17.7k, 2.7x at 40k, 6.2x at 84k
|
|
48
|
+
SHARED_TOKENS = 16384
|
|
49
|
+
PARALLEL = 256 # a rank request's own requests in flight at once (the default chunk's 200 for 10,000 candidates: all)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def is_rank(q):
|
|
53
|
+
return isinstance(q, dict) and q.get("type") == "rank"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _text(x):
|
|
57
|
+
return x if isinstance(x, str) else json.dumps(x, ensure_ascii=False)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _int(name, q, k, default, lo, hi):
|
|
61
|
+
v = q.get(k, default)
|
|
62
|
+
if isinstance(v, bool) or not isinstance(v, int) or not lo <= v <= hi:
|
|
63
|
+
raise RequestError(f"question {name!r}: {k} must be an integer from {lo} to {hi}")
|
|
64
|
+
return v
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _weight(v):
|
|
68
|
+
"""A prior weight: a finite number >= 0 (an infinite one, 1e999 in JSON or an integer beyond the largest float, made
|
|
69
|
+
the scores inf or NaN and the answer no JSON: HTTP 500)."""
|
|
70
|
+
if isinstance(v, bool) or not isinstance(v, (int, float)):
|
|
71
|
+
return False
|
|
72
|
+
try:
|
|
73
|
+
return math.isfinite(v) and v >= 0
|
|
74
|
+
except OverflowError:
|
|
75
|
+
return False
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def parse(name, q, max_options, lang, max_candidates=MAX_CANDIDATES):
|
|
79
|
+
"""A rank question -> its spec; RequestError (HTTP 422) for an invalid one."""
|
|
80
|
+
for k in ("ask_if", "depends_on", "coverage", "max_error", "evidence"):
|
|
81
|
+
if q.get(k) is not None:
|
|
82
|
+
raise RequestError(f"question {name!r}: {k} is not available on a rank question")
|
|
83
|
+
instr = q.get("instructions")
|
|
84
|
+
if not isinstance(instr, str) or "{candidate}" not in instr:
|
|
85
|
+
raise RequestError(f"question {name!r}: a rank question needs instructions that name the candidate with "
|
|
86
|
+
"{candidate}, e.g. \"Does {candidate} answer the question?\"")
|
|
87
|
+
c = q.get("candidates")
|
|
88
|
+
if isinstance(c, dict):
|
|
89
|
+
cands = [(str(k), _text(v), None) for k, v in c.items()]
|
|
90
|
+
elif isinstance(c, list):
|
|
91
|
+
cands = []
|
|
92
|
+
for i, x in enumerate(c):
|
|
93
|
+
if isinstance(x, dict):
|
|
94
|
+
if "text" not in x:
|
|
95
|
+
raise RequestError(f"question {name!r}: candidate {i} has no text")
|
|
96
|
+
g = x.get("group")
|
|
97
|
+
cands.append((str(x.get("key", i)), _text(x["text"]), None if g is None else _text(g)))
|
|
98
|
+
else:
|
|
99
|
+
cands.append((str(i), _text(x), None))
|
|
100
|
+
else:
|
|
101
|
+
raise RequestError(f"question {name!r}: candidates must be an object {{key: text}} or a list")
|
|
102
|
+
if not cands:
|
|
103
|
+
raise RequestError(f"question {name!r}: no candidates")
|
|
104
|
+
if len(cands) > max_candidates:
|
|
105
|
+
raise RequestError(f"question {name!r}: {len(cands)} candidates, more than the {max_candidates} this server "
|
|
106
|
+
"takes per request (basal-serve --rank-max-candidates)")
|
|
107
|
+
keys = [k for k, _, _ in cands]
|
|
108
|
+
if len(set(keys)) != len(keys):
|
|
109
|
+
raise RequestError(f"question {name!r}: candidate keys must be unique")
|
|
110
|
+
top = _int(name, q, "top", min(TOP, max_options), 0, max_options)
|
|
111
|
+
if top == 1:
|
|
112
|
+
raise RequestError(f"question {name!r}: top must be 0 (no choice) or 2..{max_options}")
|
|
113
|
+
ctx, order = q.get("choice_context", "auto"), q.get("order", "state_first")
|
|
114
|
+
if ctx not in CONTEXTS:
|
|
115
|
+
raise RequestError(f"question {name!r}: choice_context must be one of {', '.join(CONTEXTS)}")
|
|
116
|
+
if order not in ORDERS:
|
|
117
|
+
raise RequestError(f"question {name!r}: order must be one of {', '.join(ORDERS)}")
|
|
118
|
+
prior = q.get("prior") or {}
|
|
119
|
+
if not isinstance(prior, dict) or not all(_weight(v) for v in prior.values()):
|
|
120
|
+
raise RequestError(f"question {name!r}: prior must be an object {{key: finite weight >= 0}}")
|
|
121
|
+
unknown = set(map(str, prior)) - set(keys)
|
|
122
|
+
if unknown:
|
|
123
|
+
raise RequestError(f"question {name!r}: prior names unknown candidates: {sorted(unknown)[:5]}")
|
|
124
|
+
label = q.get("label", LABEL[lang])
|
|
125
|
+
title = q.get("list_title")
|
|
126
|
+
choice = q.get("choice_instructions", CHOICE[lang].format(label=str(label).lower()))
|
|
127
|
+
for k, v in (("label", label), ("list_title", title), ("choice_instructions", choice)):
|
|
128
|
+
if v is not None and (not isinstance(v, str) or not v.strip()):
|
|
129
|
+
raise RequestError(f"question {name!r}: {k} must be a non-empty string")
|
|
130
|
+
return dict(name=name, instructions=instr, cands=cands, label=label, title=title, choice=choice, top=top,
|
|
131
|
+
chunk=_int(name, q, "chunk", CHUNK, 0, MAX_CHUNK), context=ctx, order=order,
|
|
132
|
+
prior={str(k): float(v) for k, v in prior.items()},
|
|
133
|
+
limit=_int(name, q, "limit", len(cands), 1, max_candidates))
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def chunks(cands, size):
|
|
137
|
+
"""Candidate indices packed in order into requests of at most `size`; a group (consecutive candidates with the
|
|
138
|
+
same group) starts a new request rather than being split, unless it is larger than a request itself."""
|
|
139
|
+
out, cur, i = [], [], 0
|
|
140
|
+
while i < len(cands):
|
|
141
|
+
j = i + 1
|
|
142
|
+
while j < len(cands) and cands[i][2] is not None and cands[j][2] == cands[i][2]:
|
|
143
|
+
j += 1
|
|
144
|
+
group = list(range(i, j))
|
|
145
|
+
if cur and len(cur) + len(group) > size:
|
|
146
|
+
out.append(cur)
|
|
147
|
+
cur = []
|
|
148
|
+
while len(group) > size:
|
|
149
|
+
out.append(group[:size])
|
|
150
|
+
group = group[size:]
|
|
151
|
+
cur += group
|
|
152
|
+
i = j
|
|
153
|
+
if cur:
|
|
154
|
+
out.append(cur)
|
|
155
|
+
return out
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _flat(text):
|
|
159
|
+
"""One line: every line break str.splitlines knows becomes a space
|
|
160
|
+
(\\n \\r \\x0b \\x0c \\x1c-\\x1e \\x85 U+2028 U+2029)."""
|
|
161
|
+
return " ".join(text.splitlines())
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def listing(cands, idx, label, title):
|
|
165
|
+
"""The numbered list of the candidates idx (1, 2, ... in this list) under their group lines -> text, {idx: name}.
|
|
166
|
+
A candidate's lines after its first are indented (no line of its text can pass for an entry or a group line)."""
|
|
167
|
+
lines, names, group = ([title + ":"] if title else []), {}, None
|
|
168
|
+
for n, i in enumerate(idx, 1):
|
|
169
|
+
g = cands[i][2]
|
|
170
|
+
g = None if g is None else _flat(g)
|
|
171
|
+
if g is not None and g != group:
|
|
172
|
+
lines.append("[" + g + "]")
|
|
173
|
+
group = g
|
|
174
|
+
names[i] = f"{label} {n}"
|
|
175
|
+
lines.append(f"{names[i]}: " + "\n ".join(cands[i][1].splitlines()))
|
|
176
|
+
return "\n".join(lines), names
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def compose(state, text, order):
|
|
180
|
+
if not state:
|
|
181
|
+
return text
|
|
182
|
+
return f"{text}\n\n{state}" if order == "candidates_first" else f"{state}\n\n{text}"
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def questions(spec, idx, names):
|
|
186
|
+
"""The screening questions of the candidates idx: one yes / no question each."""
|
|
187
|
+
return {str(n): {"type": "noul", "instructions": spec["instructions"].replace("{candidate}", names[i])}
|
|
188
|
+
for n, i in enumerate(idx)}
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def fits(srv, state, spec, fields=None):
|
|
192
|
+
"""Whether the whole list is read as one shared request (chunk 0): its candidates (a question each) within the
|
|
193
|
+
server's --max-branches, its state at most SHARED_TOKENS tokens, within the server's context, and its prompts' text
|
|
194
|
+
within its --max-prompt-mb, counted as Server.check_prompts counts it (every prompt holds the shared state, so a
|
|
195
|
+
long list in one context can pass the context and not the text limit); True for a limit that is unknown."""
|
|
196
|
+
from .server import MAX_BRANCHES, to_items # (basal.server imports this module)
|
|
197
|
+
if len(spec["cands"]) > getattr(srv, "max_branches", MAX_BRANCHES):
|
|
198
|
+
return False
|
|
199
|
+
idx = range(len(spec["cands"]))
|
|
200
|
+
text, names = listing(spec["cands"], idx, spec["label"], spec["title"])
|
|
201
|
+
whole = compose(state, text, spec["order"])
|
|
202
|
+
limit, tok = getattr(srv, "context", None), getattr(srv, "tok", None)
|
|
203
|
+
if tok is not None:
|
|
204
|
+
n = len(tok(whole, add_special_tokens=False).input_ids)
|
|
205
|
+
if n > SHARED_TOKENS: # (every question reads the whole state: chunks of CHUNK are faster past this size)
|
|
206
|
+
return False
|
|
207
|
+
if limit and n + len(tok(spec["instructions"], add_special_tokens=False).input_ids) + MARGIN > limit[0]:
|
|
208
|
+
return False
|
|
209
|
+
check = getattr(srv, "check_prompts", None)
|
|
210
|
+
if check is None:
|
|
211
|
+
return True
|
|
212
|
+
qs = to_items(whole, questions(spec, idx, names), getattr(srv, "max_options", MAX_OPTIONS),
|
|
213
|
+
force_lang=(fields or {}).get("lang"))
|
|
214
|
+
try:
|
|
215
|
+
check(qs)
|
|
216
|
+
except RequestError:
|
|
217
|
+
return False
|
|
218
|
+
return True
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
async def every(aws):
|
|
222
|
+
"""The results of aws (a request's sub-requests), as asyncio.gather; when one fails, the others are cancelled
|
|
223
|
+
before its error is raised: their queued work is dropped (Server.ask) and a preparation not started yet never
|
|
224
|
+
runs, as for a client that disconnects. gather alone left them running for nobody after the client got its error,
|
|
225
|
+
and every later request waited behind them."""
|
|
226
|
+
tasks = [asyncio.ensure_future(a) for a in aws]
|
|
227
|
+
try:
|
|
228
|
+
return await asyncio.gather(*tasks)
|
|
229
|
+
except BaseException:
|
|
230
|
+
for t in tasks:
|
|
231
|
+
t.cancel()
|
|
232
|
+
await asyncio.gather(*tasks, return_exceptions=True)
|
|
233
|
+
raise
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
async def sub(srv, body, review=None, part=None):
|
|
237
|
+
"""A sub-request through Server.decide, counted in flight (GET /health) like a client request; review: the client
|
|
238
|
+
request's audit draw, which its sub-requests take; part: its place in the rank question, on its log line."""
|
|
239
|
+
srv.in_flight += 1
|
|
240
|
+
try:
|
|
241
|
+
out = await srv.decide(body, review=review, part=part)
|
|
242
|
+
finally:
|
|
243
|
+
srv.in_flight -= 1
|
|
244
|
+
if out["usage"].get("truncated"):
|
|
245
|
+
raise RequestError("a rank request is longer than the context (--context-overflow truncate would cut its "
|
|
246
|
+
"list); lower chunk")
|
|
247
|
+
return out
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def parallel(srv):
|
|
251
|
+
"""How many of a rank request's own requests (of all its rank questions together) run at once: PARALLEL, and at
|
|
252
|
+
most half the server's --max-requests, so a list in small chunks (10,000 requests at chunk 1) neither starts them
|
|
253
|
+
all at once nor fills the cap other clients are admitted under."""
|
|
254
|
+
from .server import MAX_REQUESTS # (basal.server imports this module)
|
|
255
|
+
return max(1, min(PARALLEL, getattr(srv, "max_requests", MAX_REQUESTS) // 2))
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
async def screen(srv, state, spec, fields, review=None, gate=None):
|
|
259
|
+
"""Every candidate's P(yes) -> (scores, the requests' bodies and lists, their responses). gate: the semaphore the
|
|
260
|
+
request's rank questions share (parallel); none: one of this question's own."""
|
|
261
|
+
if not spec["chunk"] and getattr(srv, "dual", False):
|
|
262
|
+
# a dual model reads a request of several questions in header groups of at most 4, each reading the whole
|
|
263
|
+
# state again (its trained reading): one shared context of a long list would be read once per 4 candidates,
|
|
264
|
+
# so chunk 0 reads requests of CHUNK there (a chunk the client sets is kept)
|
|
265
|
+
spec = dict(spec, chunk=CHUNK)
|
|
266
|
+
size = spec["chunk"] or (len(spec["cands"]) if fits(srv, state, spec, fields) else CHUNK)
|
|
267
|
+
parts, bodies = [], []
|
|
268
|
+
for idx in chunks(spec["cands"], size):
|
|
269
|
+
text, names = listing(spec["cands"], idx, spec["label"], spec["title"])
|
|
270
|
+
bodies.append(dict(fields, state=compose(state, text, spec["order"]), questions=questions(spec, idx, names)))
|
|
271
|
+
parts.append((idx, names))
|
|
272
|
+
gate = gate or asyncio.Semaphore(parallel(srv))
|
|
273
|
+
|
|
274
|
+
async def one(n, body):
|
|
275
|
+
async with gate:
|
|
276
|
+
return await sub(srv, body, review, {"question": spec["name"], "step": "screen", "chunk": n,
|
|
277
|
+
"chunks": len(bodies)})
|
|
278
|
+
outs = await every(one(n, b) for n, b in enumerate(bodies))
|
|
279
|
+
yes = [0.0] * len(spec["cands"])
|
|
280
|
+
for (idx, _), out in zip(parts, outs):
|
|
281
|
+
for n, i in enumerate(idx):
|
|
282
|
+
yes[i] = float(out["answers"][str(n)]["noul"])
|
|
283
|
+
return yes, bodies, parts, list(outs)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
async def rank_one(srv, state, spec, fields, review=None, gate=None):
|
|
287
|
+
"""One rank question -> (its answer, its sub-responses). gate: as screen's."""
|
|
288
|
+
yes, bodies, parts, outs = await screen(srv, state, spec, fields, review, gate)
|
|
289
|
+
cands, prior = spec["cands"], spec["prior"]
|
|
290
|
+
score = [y * prior.get(k, 1.0) for y, (k, _, _) in zip(yes, cands)]
|
|
291
|
+
order = sorted(range(len(cands)), key=lambda i: -score[i]) # stable: ties keep the candidates' order
|
|
292
|
+
choice = {}
|
|
293
|
+
k = min(spec["top"], len(cands))
|
|
294
|
+
if k >= 2:
|
|
295
|
+
short = sorted(order[:k]) # the list's order
|
|
296
|
+
if spec["context"] == "screen" and len(parts) > 1:
|
|
297
|
+
raise RequestError(f"question {spec['name']!r}: choice_context screen needs every candidate in one request "
|
|
298
|
+
f"(they took {len(parts)}; raise chunk or use shortlist)")
|
|
299
|
+
if spec["context"] != "shortlist" and len(parts) == 1:
|
|
300
|
+
body, names = bodies[0], parts[0][1]
|
|
301
|
+
else:
|
|
302
|
+
text, names = listing(cands, short, spec["label"], spec["title"])
|
|
303
|
+
body = dict(fields, state=compose(state, text, spec["order"]))
|
|
304
|
+
crit = {str(i): names[i] for i in short}
|
|
305
|
+
q = {"type": "choice", "instructions": spec["choice"], "criteria": crit, "option_keys": "hide"}
|
|
306
|
+
out = await sub(srv, dict(body, questions={"choice": q}), review,
|
|
307
|
+
{"question": spec["name"], "step": "choice"})
|
|
308
|
+
outs.append(out)
|
|
309
|
+
probs = out["answers"]["choice"]["probabilities"]
|
|
310
|
+
choice = {i: float(probs[str(i)]) for i in short}
|
|
311
|
+
head = sorted(order[:k], key=lambda i: -choice[i])
|
|
312
|
+
order = head + order[k:]
|
|
313
|
+
ranking = []
|
|
314
|
+
for i in order[: spec["limit"]]:
|
|
315
|
+
e = {"key": cands[i][0], "score": score[i]}
|
|
316
|
+
if i in choice:
|
|
317
|
+
e["choice"] = choice[i]
|
|
318
|
+
if prior:
|
|
319
|
+
e["yes"] = yes[i]
|
|
320
|
+
ranking.append(e)
|
|
321
|
+
return {"type": "rank", "ranking": ranking, "top": cands[order[0]][0], "candidates": len(cands),
|
|
322
|
+
"requests": len(outs), "experimental": True}, outs
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def admit(srv, body):
|
|
326
|
+
"""A request with rank questions, checked before any of its requests starts (Server.admit): no media, the
|
|
327
|
+
language, every rank question, the candidate cap, and the other questions as their own request reads them ->
|
|
328
|
+
(the state's text, the rank specs, the other questions)."""
|
|
329
|
+
if body.get("media") is not None or body.get("images") is not None:
|
|
330
|
+
raise RequestError("rank questions do not take media")
|
|
331
|
+
state = _text(body["state"]) if body["state"] is not None else ""
|
|
332
|
+
lang = body.get("lang") or lang_of(state)
|
|
333
|
+
if lang not in ("pl", "en"):
|
|
334
|
+
raise RequestError('lang must be "pl" or "en"')
|
|
335
|
+
cap = getattr(srv, "rank_max", MAX_CANDIDATES)
|
|
336
|
+
specs = [parse(n, q, srv.option_cap(), lang, cap) for n, q in body["questions"].items() if is_rank(q)]
|
|
337
|
+
total = sum(len(s["cands"]) for s in specs)
|
|
338
|
+
if total > cap: # every 50 candidates are one request through the queue every client shares
|
|
339
|
+
raise RequestError(f"{total} rank candidates in this request, more than the {cap} this server takes per "
|
|
340
|
+
"request (basal-serve --rank-max-candidates)")
|
|
341
|
+
others = {n: q for n, q in body["questions"].items() if not is_rank(q)}
|
|
342
|
+
if others: # (decided alongside the rank requests: an invalid one would fail the request after they ran)
|
|
343
|
+
srv.admit(dict(body, questions=others))
|
|
344
|
+
return state, specs, others
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
async def decide(srv, body, review=None):
|
|
348
|
+
"""A request with rank questions (Server.decide sends it here): the rank questions through their own requests, the
|
|
349
|
+
others as one request over the state; the usage sums them all. review: the client request's audit draw, which every
|
|
350
|
+
request of it takes (its rank answers are marked by Server.decide)."""
|
|
351
|
+
t0 = time.perf_counter()
|
|
352
|
+
state, specs, others = admit(srv, body)
|
|
353
|
+
fields = {k: v for k, v in body.items() if k not in ("state", "questions")}
|
|
354
|
+
gate = asyncio.Semaphore(parallel(srv)) # (one for the request: its rank questions share the bound)
|
|
355
|
+
jobs = [rank_one(srv, state, s, fields, review, gate) for s in specs]
|
|
356
|
+
if others:
|
|
357
|
+
jobs.append(srv.decide(dict(body, questions=others), review=review))
|
|
358
|
+
res = await every(jobs)
|
|
359
|
+
answers, subs = {}, []
|
|
360
|
+
if others:
|
|
361
|
+
rest = res.pop()
|
|
362
|
+
subs.append(rest)
|
|
363
|
+
for s, (a, outs) in zip(specs, res):
|
|
364
|
+
answers[s["name"]] = a
|
|
365
|
+
subs += outs
|
|
366
|
+
if others:
|
|
367
|
+
answers.update(rest["answers"])
|
|
368
|
+
answers = {n: answers[n] for n in body["questions"]} # the request's order
|
|
369
|
+
usage = {"input_tokens": sum(o["usage"]["input_tokens"] for o in subs), "output_tokens": 0,
|
|
370
|
+
"questions": len(body["questions"]), "branches": sum(o["usage"]["branches"] for o in subs),
|
|
371
|
+
"requests": len(subs), "latency_ms": round((time.perf_counter() - t0) * 1000, 2),
|
|
372
|
+
"longest_prompt_tokens": max(o["usage"].get("longest_prompt_tokens", 0) for o in subs)}
|
|
373
|
+
return {"model": srv.name, "answers": answers, "usage": usage}
|
basal/readout.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""The readout of the option codes: one implementation for every torch engine (eager, the CUDA graph engines, Strix,
|
|
2
|
+
fast-exit) and for basal-finetune, so what a model is trained on is what it is served with.
|
|
3
|
+
|
|
4
|
+
A question's answer is the softmax over its option codes of the logits at the answer position. The softmax over the
|
|
5
|
+
code rows of the output head equals the softmax over the codes of the full log-softmax, so only those rows are read:
|
|
6
|
+
in fp32 from the normalised hidden state (bf16 logits of magnitude 16-32 step by 0.125, which clumps the
|
|
7
|
+
probabilities), with the head's bias and the model's final logit soft cap applied once (Gemma). The fp32 rows of each
|
|
8
|
+
set of codes are cached, the most recently used within WROWS_BYTES (MLX keeps its own arrays in the same cache).
|
|
9
|
+
"""
|
|
10
|
+
import threading
|
|
11
|
+
|
|
12
|
+
import torch
|
|
13
|
+
|
|
14
|
+
WROWS_BYTES = 64 << 20 # the fp32 code rows an engine keeps (one entry per option-code set, least recently used out)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _nbytes(x):
|
|
18
|
+
if x is None:
|
|
19
|
+
return 0
|
|
20
|
+
if isinstance(x, tuple):
|
|
21
|
+
return sum(_nbytes(y) for y in x)
|
|
22
|
+
return int(x.nbytes) # (torch and MLX arrays)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# Only host bookkeeping uses this lock. GPU row selection and conversion run outside it.
|
|
26
|
+
_ROWS_LOCK = threading.Lock()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def code_rows(cache, key, make):
|
|
30
|
+
"""cache[key], made by make() when missing: the output-head rows of one set of option codes. The cache keeps the most
|
|
31
|
+
recently used sets within WROWS_BYTES (every option count and code set was kept for good: up to ~0.7 GB); an entry is
|
|
32
|
+
the same rows whenever it is made again."""
|
|
33
|
+
with _ROWS_LOCK:
|
|
34
|
+
if key in cache:
|
|
35
|
+
value = cache.pop(key)
|
|
36
|
+
cache[key] = value
|
|
37
|
+
return value
|
|
38
|
+
value = make()
|
|
39
|
+
with _ROWS_LOCK:
|
|
40
|
+
cache[key] = cache.pop(key, value)
|
|
41
|
+
total = sum(_nbytes(x) for x in cache.values())
|
|
42
|
+
for old in list(cache):
|
|
43
|
+
if total <= WROWS_BYTES or old == key:
|
|
44
|
+
break
|
|
45
|
+
total -= _nbytes(cache.pop(old))
|
|
46
|
+
return cache[key]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def capped(z, softcap):
|
|
50
|
+
"""The model's final logit soft cap (Gemma: softcap x tanh(z / softcap)), applied once; none: z as it is."""
|
|
51
|
+
return torch.tanh(z / softcap) * softcap if softcap else z
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class CodeReadout:
|
|
55
|
+
"""The code readout of one output head (an nn.Linear-like module: weight [vocab, D], optional bias) and soft cap.
|
|
56
|
+
|
|
57
|
+
rows(lids) -> (rows, idx, pad): the fp32 head rows (and bias) of the union of the prompts' code ids, each prompt's
|
|
58
|
+
columns into them and the padding of the shorter ones; logits(h, rows) -> fp32 code logits [n, k] of hidden states
|
|
59
|
+
h [n, D], capped once; probs(h, lids) -> each prompt's probabilities over its codes (one masked softmax, one copy to
|
|
60
|
+
the host)."""
|
|
61
|
+
|
|
62
|
+
def __init__(self, head, softcap=None, cache=None, to_dev=None):
|
|
63
|
+
self.head, self.softcap = head, softcap
|
|
64
|
+
self.cache = {} if cache is None else cache
|
|
65
|
+
self.to_dev = to_dev or (lambda x: x.to(head.weight.device))
|
|
66
|
+
|
|
67
|
+
def cache_key(self, codes):
|
|
68
|
+
device = self.head.weight.device
|
|
69
|
+
if device.type == "cuda":
|
|
70
|
+
# Rows produced on another stream can still be in flight. The LRU budget spans all streams.
|
|
71
|
+
return (torch.cuda.current_stream(device).cuda_stream, codes)
|
|
72
|
+
return codes
|
|
73
|
+
|
|
74
|
+
def rows(self, lids):
|
|
75
|
+
key = tuple(sorted({i for ids in lids for i in ids}))
|
|
76
|
+
|
|
77
|
+
def make():
|
|
78
|
+
sel = self.to_dev(torch.tensor(key))
|
|
79
|
+
b = self.head.bias.index_select(0, sel).float() if getattr(self.head, "bias", None) is not None else None
|
|
80
|
+
return self.head.weight.index_select(0, sel).float(), b
|
|
81
|
+
rows = code_rows(self.cache, self.cache_key(key), make)
|
|
82
|
+
col = {t: j for j, t in enumerate(key)}
|
|
83
|
+
K = max(map(len, lids))
|
|
84
|
+
idx = self.to_dev(torch.tensor([[col[i] for i in ids] + [0] * (K - len(ids)) for ids in lids]))
|
|
85
|
+
pad = self.to_dev(torch.tensor([[False] * len(ids) + [True] * (K - len(ids)) for ids in lids]))
|
|
86
|
+
return rows, idx, pad
|
|
87
|
+
|
|
88
|
+
def logits(self, h, rows):
|
|
89
|
+
W, b = rows
|
|
90
|
+
z = h.float() @ W.T
|
|
91
|
+
return capped(z if b is None else z + b, self.softcap)
|
|
92
|
+
|
|
93
|
+
@staticmethod
|
|
94
|
+
def probs_of(z, idx, pad):
|
|
95
|
+
"""Code logits [n, k] -> each prompt's probabilities over its codes [n, K] (padding 0), as a tensor."""
|
|
96
|
+
return torch.softmax(z.float().gather(1, idx).masked_fill(pad, float("-inf")), -1)
|
|
97
|
+
|
|
98
|
+
def probs(self, h, lids):
|
|
99
|
+
rows, idx, pad = self.rows(lids)
|
|
100
|
+
p = self.probs_of(self.logits(h, rows), idx, pad).tolist() # one device sync
|
|
101
|
+
return [row[: len(ids)] for row, ids in zip(p, lids)]
|
|
102
|
+
|
|
103
|
+
def probs_each(self, h, lids):
|
|
104
|
+
"""probs, each prompt read alone: the product of its hidden state [D] with its own code rows (in its code order)
|
|
105
|
+
and the softmax over its codes, as the eager engine has always read them, so a prompt's numbers do not depend on
|
|
106
|
+
the prompts read with it (a product or softmax of another shape, such as probs' over the union of the codes,
|
|
107
|
+
can differ in the last bits). One copy to the host."""
|
|
108
|
+
out = []
|
|
109
|
+
for b, ids in enumerate(lids):
|
|
110
|
+
key = tuple(ids)
|
|
111
|
+
|
|
112
|
+
def make(key=key):
|
|
113
|
+
sel = self.to_dev(torch.tensor(key))
|
|
114
|
+
bias = self.head.bias.index_select(0, sel).float() if getattr(self.head, "bias", None) is not None else None
|
|
115
|
+
return self.head.weight.index_select(0, sel).float(), bias
|
|
116
|
+
out.append(torch.softmax(self.logits(h[b], code_rows(self.cache, self.cache_key(key), make)), -1))
|
|
117
|
+
p, n, res = torch.cat(out).tolist(), 0, [] # one device sync
|
|
118
|
+
for ids in lids:
|
|
119
|
+
res.append(p[n: n + len(ids)])
|
|
120
|
+
n += len(ids)
|
|
121
|
+
return res
|