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/agree.py
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
"""basal-agree: every backend against the native engine, on the same prompts.
|
|
2
|
+
|
|
3
|
+
basal-agree --model Remek/basal-2.0-mini --backends mps mlx mlx=Remek/basal-2.0-mini-MLX-8bit
|
|
4
|
+
basal-agree --model Remek/basal-omni-1.0-mini --reference eager --backends fast vllm --questions items.jsonl
|
|
5
|
+
basal-agree --identity --model Remek/basal-1.5-4.5B # the identity gate of the CUDA fast path (basal/identity.py)
|
|
6
|
+
|
|
7
|
+
Items are synthetic (basal.synth, no real data): single questions over ~1.5k-token states, five-question requests over
|
|
8
|
+
one state and long states, every question in both option orders; --questions adds your own simple items (a "gold"
|
|
9
|
+
index adds accuracy). The reference is the native engine (--reference, default eager-fp32: basal's PyTorch forward in
|
|
10
|
+
fp32 on this machine's device) with every prompt alone, one per call. Its rows are cached (--cache) under a key of the
|
|
11
|
+
model revision, the basal version, the reference and the prompts, so further runs against other backends reuse them.
|
|
12
|
+
|
|
13
|
+
A backend is a basal-bench mode (eager, mps, mlx, mlx-q8, fast, vllm, gguf@FILE, ollama, ...), or MODE=WEIGHTS for the
|
|
14
|
+
same model in other weights with the same tokenizer (mlx=Remek/basal-2.0-mini-MLX-8bit). Backends are built, run and
|
|
15
|
+
freed one at a time; each answers the requests as served: both orders of a question in one call, the five questions of
|
|
16
|
+
a request in one call. Per backend:
|
|
17
|
+
|
|
18
|
+
readouts top-1 agreement with the reference, with a 95% bootstrap interval over requests; near ties among the
|
|
19
|
+
disagreements (top two within 0.02 in the reference); mean / p99 / max |dp| (per readout: the largest
|
|
20
|
+
change of an option's probability)
|
|
21
|
+
decisions the single questions as the server answers them by default: both orders averaged for prompt-format-1
|
|
22
|
+
models, the given order for format-2 models (basal-serve's default orders): top-1 agreement
|
|
23
|
+
accuracy items with gold: accuracy and the paired bootstrap difference to the reference (95% interval)
|
|
24
|
+
independent question independence: every prompt of the five-question requests alone through the same backend
|
|
25
|
+
against its readout in the request (top-1 agreement, max |dp|); a backend whose answer moves with the
|
|
26
|
+
other questions of the request shows it here, whatever the reference says
|
|
27
|
+
|
|
28
|
+
Gate: the readout agreement outside near ties (a disagreement whose reference top two are within 0.02 counts as
|
|
29
|
+
agreeing: any change of rounding can flip those) >= --gate (default 0.99), and the same for question independence.
|
|
30
|
+
The exit status is 0 when every backend passes, 1 otherwise.
|
|
31
|
+
"""
|
|
32
|
+
import argparse
|
|
33
|
+
import gc
|
|
34
|
+
import hashlib
|
|
35
|
+
import json
|
|
36
|
+
import os
|
|
37
|
+
import random
|
|
38
|
+
import sys
|
|
39
|
+
import time
|
|
40
|
+
from pathlib import Path
|
|
41
|
+
|
|
42
|
+
from . import synth
|
|
43
|
+
from .cli import positive
|
|
44
|
+
from .jsonl import JSONLError, finite, records, write_json
|
|
45
|
+
from .prompt import letter_ids, model_format, render
|
|
46
|
+
|
|
47
|
+
GATE = 0.99
|
|
48
|
+
OLLAMA_URL, LLAMACPP_URL = "http://127.0.0.1:11434", "http://127.0.0.1:8080"
|
|
49
|
+
BOOT = 2000
|
|
50
|
+
|
|
51
|
+
QUESTIONS = {
|
|
52
|
+
"pl": [("Który dział powinien obsłużyć ostatnie zgłoszenie?", ["Reklamacje", "Płatności", "Logistyka", "Sprzedaż"]),
|
|
53
|
+
("Czy klient zgłosił uszkodzenie przesyłki?", ["Tak", "Nie"]),
|
|
54
|
+
("Jak pilne jest ostatnie zgłoszenie?", ["niska pilność", "średnia pilność", "wysoka pilność"]),
|
|
55
|
+
("Jaki status ma ostatnie zgłoszenie?", ["przyjęte", "w toku", "czeka na klienta", "przekazane", "zamknięte",
|
|
56
|
+
"nie wiadomo"]),
|
|
57
|
+
("Czy w historii są co najmniej trzy zgłoszenia tej samej osoby?", ["Tak", "Nie"])],
|
|
58
|
+
"en": [("Which department should handle the latest ticket?", ["Complaints", "Payments", "Logistics", "Sales"]),
|
|
59
|
+
("Did the customer report a damaged parcel?", ["Yes", "No"]),
|
|
60
|
+
("How urgent is the latest ticket?", ["low urgency", "medium urgency", "high urgency"]),
|
|
61
|
+
("What is the status of the latest ticket?", ["received", "in progress", "waiting for customer", "forwarded",
|
|
62
|
+
"closed", "unknown"]),
|
|
63
|
+
("Are there at least three tickets from the same person in the history?", ["Yes", "No"])],
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def orders(tok, fmt, state, question, options):
|
|
68
|
+
"""Both option orders of one question -> (token lists, code ids)."""
|
|
69
|
+
k = len(options)
|
|
70
|
+
prompts = [render(tok, state, question, [options[c] for c in perm], fmt=fmt)
|
|
71
|
+
for perm in (list(range(k)), list(range(k))[::-1])]
|
|
72
|
+
ids = letter_ids(tok, prompts[0], k, fmt)
|
|
73
|
+
if ids is None:
|
|
74
|
+
raise ValueError("option codes are not single tokens for this tokenizer")
|
|
75
|
+
return tok(prompts, add_special_tokens=False).input_ids, [ids, ids]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def build(tok, fmt, n_single, n_multi, n_long, seed=0, questions=None):
|
|
79
|
+
"""Synthetic single questions (plus the simple items of `questions`, a list of dicts with state / question /
|
|
80
|
+
options), five-question requests over one state, long states."""
|
|
81
|
+
items = synth.items(n_single, 1500, seed=seed) + list(questions or [])
|
|
82
|
+
single = [orders(tok, fmt, it["state"], it["question"], it["options"]) for it in items]
|
|
83
|
+
multi = []
|
|
84
|
+
for i, it in enumerate(synth.items(n_multi, 1500, seed=seed + 1)):
|
|
85
|
+
lang = "pl" if i % 2 == 0 else "en"
|
|
86
|
+
req = [orders(tok, fmt, it["state"], q, o) for q, o in QUESTIONS[lang]]
|
|
87
|
+
multi.append(([t for r in req for t in r[0]], [x for r in req for x in r[1]]))
|
|
88
|
+
long = [orders(tok, fmt, it["state"], it["question"], it["options"])
|
|
89
|
+
for it in synth.items(n_long, 5600, seed=seed + 2, spread=0.4)]
|
|
90
|
+
return single, multi, long
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def top(p):
|
|
94
|
+
return max(range(len(p)), key=p.__getitem__)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def compare(ref, got):
|
|
98
|
+
"""Lists of probability vectors -> agreement, |dp| statistics (per readout: the largest change of an option's
|
|
99
|
+
probability), near-tie disagreements."""
|
|
100
|
+
agree, dps, ties = 0, [], 0
|
|
101
|
+
for r, g in zip(ref, got):
|
|
102
|
+
if any(x != x or abs(x) == float("inf") for x in (*g, *r)): # a NaN or infinite readout or reference disagrees, with the largest change
|
|
103
|
+
dps.append(1.0)
|
|
104
|
+
continue
|
|
105
|
+
a, b = top(r), top(g)
|
|
106
|
+
agree += a == b
|
|
107
|
+
if a != b:
|
|
108
|
+
hi = sorted(r, reverse=True)
|
|
109
|
+
ties += hi[0] - hi[1] < 0.02
|
|
110
|
+
dps.append(max(abs(x - y) for x, y in zip(r, g)))
|
|
111
|
+
mean = sum(dps) / len(dps)
|
|
112
|
+
dps.sort()
|
|
113
|
+
return dict(readouts=len(ref), agreement=agree / len(ref), mean_dp=mean, max_dp=dps[-1],
|
|
114
|
+
p99_dp=dps[int(0.99 * (len(dps) - 1))], disagreements=len(ref) - agree, near_ties=ties)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def decisions(readouts, orders=2):
|
|
118
|
+
"""Readouts of the single questions (order 1, reversed order, per item) -> the canonical probabilities as the
|
|
119
|
+
server answers with `orders` (server.default_orders: 2 for prompt-format-1 models, the two averaged; 1 for
|
|
120
|
+
format-2 models, the given order alone)."""
|
|
121
|
+
if orders == 1:
|
|
122
|
+
return [list(o1) for o1 in readouts[0::2]]
|
|
123
|
+
out = []
|
|
124
|
+
for o1, o2 in zip(readouts[0::2], readouts[1::2]):
|
|
125
|
+
out.append([(x + y) / 2 for x, y in zip(o1, o2[::-1])])
|
|
126
|
+
return out
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def bootstrap(units, stat, n=BOOT, seed=0):
|
|
130
|
+
"""95% percentile interval of stat(sample) over n resamples (with replacement) of the units."""
|
|
131
|
+
rnd = random.Random(seed)
|
|
132
|
+
vals = sorted(stat([units[rnd.randrange(len(units))] for _ in units]) for _ in range(n))
|
|
133
|
+
return [vals[int(0.025 * (n - 1))], vals[int(0.975 * (n - 1))]]
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def flat(groups):
|
|
137
|
+
return [p for g in groups for p in g]
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def run_groups(be, groups, per_call):
|
|
141
|
+
if per_call < 1:
|
|
142
|
+
raise SystemExit("--per-call must be at least 1")
|
|
143
|
+
out = []
|
|
144
|
+
for i in range(0, len(groups), per_call):
|
|
145
|
+
out += be.run_shared(groups[i: i + per_call])
|
|
146
|
+
return out
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def alone(groups):
|
|
150
|
+
"""Every prompt of the groups as its own group."""
|
|
151
|
+
return [([t], [x]) for toks, ids in groups for t, x in zip(toks, ids)]
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def regroup(rows, groups):
|
|
155
|
+
"""Flat readouts -> one list per group."""
|
|
156
|
+
out, k = [], 0
|
|
157
|
+
for toks, _ in groups:
|
|
158
|
+
out.append(rows[k: k + len(toks)])
|
|
159
|
+
k += len(toks)
|
|
160
|
+
return out
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def score(sets, ref, got, ind, gold, seed=0, orders=2):
|
|
164
|
+
"""One backend's row: readouts per set and overall (with the bootstrap interval over requests), decisions,
|
|
165
|
+
accuracy against gold, question independence. ref / got: per set, per group, the readouts."""
|
|
166
|
+
row = {"sets": {k: compare(flat(ref[k]), flat(got[k])) for k in sets if ref[k]}}
|
|
167
|
+
units = [(r, g) for k in sets for r, g in zip(ref[k], got[k])]
|
|
168
|
+
row.update(compare([p for r, _ in units for p in r], [p for _, g in units for p in g]))
|
|
169
|
+
row["agreement_ci"] = bootstrap(units, lambda s: sum(top(a) == top(b) for r, g in s for a, b in zip(r, g))
|
|
170
|
+
/ sum(len(r) for r, _ in s), seed=seed)
|
|
171
|
+
rd, gd = decisions(flat(ref["single"]), orders), decisions(flat(got["single"]), orders)
|
|
172
|
+
if rd: # no single questions (--n-single 0): no decision agreement
|
|
173
|
+
row["decision_agreement"] = compare(rd, gd)["agreement"]
|
|
174
|
+
if gold: # (decision index, gold index) of the items with gold
|
|
175
|
+
pairs = [(top(rd[i]) == y, top(gd[i]) == y) for i, y in gold]
|
|
176
|
+
row["accuracy"] = sum(b for _, b in pairs) / len(pairs)
|
|
177
|
+
row["reference_accuracy"] = sum(a for a, _ in pairs) / len(pairs)
|
|
178
|
+
row["accuracy_diff_ci"] = bootstrap(pairs, lambda s: (sum(b for _, b in s) - sum(a for a, _ in s)) / len(s),
|
|
179
|
+
seed=seed)
|
|
180
|
+
if ind: # no multi readouts (--n-multi 0): no independence figure
|
|
181
|
+
c = compare(flat(got["multi"]), ind)
|
|
182
|
+
row["independence"] = c["agreement"]
|
|
183
|
+
row["independence_ties"] = c["near_ties"]
|
|
184
|
+
row["independence_max_dp"] = c["max_dp"]
|
|
185
|
+
return row
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def gate(row, g=GATE):
|
|
189
|
+
"""Agreement outside near ties >= g, for the readouts and for question independence."""
|
|
190
|
+
ok = row["agreement"] + row["near_ties"] / row["readouts"] >= g
|
|
191
|
+
if "independence" in row:
|
|
192
|
+
ok = ok and row["independence"] + row["independence_ties"] / (row["readouts_multi"]) >= g
|
|
193
|
+
return "pass" if ok else "FAIL"
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def cache_key(model, revision, version, reference, sets, weights=None):
|
|
197
|
+
"""`weights` holds only what the reference reads and what differs from the default; with none, the key is the
|
|
198
|
+
one of earlier versions, so the cached rows of the default reference stay valid."""
|
|
199
|
+
parts = dict(model=model, revision=revision, version=version, reference=reference, sets=sets)
|
|
200
|
+
if weights:
|
|
201
|
+
parts["weights"] = weights
|
|
202
|
+
return hashlib.sha256(json.dumps(parts).encode()).hexdigest()[:24]
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def file_id(path):
|
|
206
|
+
"""A weights file as the cache key sees it: its resolved path, size and modification time, so ./m.gguf and its
|
|
207
|
+
absolute path are one entry and another file written at the same path is another. A path that is no file stays as
|
|
208
|
+
typed (the run then fails on it)."""
|
|
209
|
+
p = Path(path).expanduser()
|
|
210
|
+
if not p.is_file():
|
|
211
|
+
return path
|
|
212
|
+
st = p.stat()
|
|
213
|
+
return [str(p.resolve()), st.st_size, st.st_mtime_ns]
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def reference_weights(a):
|
|
217
|
+
"""The options that choose the weights of the reference engine (gguf, ollama, llamacpp), if not at the default;
|
|
218
|
+
a GGUF file by file_id."""
|
|
219
|
+
mode = a.reference.partition("=")[0]
|
|
220
|
+
if mode == "gguf":
|
|
221
|
+
fields = dict(gguf=(a.gguf, None))
|
|
222
|
+
elif mode.startswith("gguf@"): # gguf@<file.gguf>: the file is in the reference itself
|
|
223
|
+
fields = dict(gguf=(mode.split("@", 1)[1], None))
|
|
224
|
+
elif mode == "ollama":
|
|
225
|
+
fields = dict(ollama_model=(a.ollama_model, None), ollama_url=(a.ollama_url, OLLAMA_URL))
|
|
226
|
+
elif mode == "llamacpp":
|
|
227
|
+
fields = dict(llamacpp_url=(a.llamacpp_url, LLAMACPP_URL))
|
|
228
|
+
else:
|
|
229
|
+
fields = {}
|
|
230
|
+
out = {k: v for k, (v, default) in fields.items() if v != default}
|
|
231
|
+
if "gguf" in out:
|
|
232
|
+
out["gguf"] = file_id(out["gguf"])
|
|
233
|
+
return out
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def cached_reference(path, make, sets):
|
|
237
|
+
"""The reference rows: from the cache file if it is there, else computed (every prompt alone) and stored."""
|
|
238
|
+
if path is not None and path.exists():
|
|
239
|
+
return json.loads(path.read_text(encoding="utf-8")), True
|
|
240
|
+
be = make()
|
|
241
|
+
ref = {k: regroup(flat(run_groups(be, alone(v), 1)), v) for k, v in sets.items()}
|
|
242
|
+
free(be)
|
|
243
|
+
if path is not None:
|
|
244
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
245
|
+
tmp = path.with_name(path.name + f".{os.getpid()}.tmp") # a kill mid-write must not leave a truncated cache
|
|
246
|
+
tmp.write_text(json.dumps(ref), encoding="utf-8")
|
|
247
|
+
os.replace(tmp, path)
|
|
248
|
+
return ref, False
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def free(be):
|
|
252
|
+
from .bench import reset_memory
|
|
253
|
+
if hasattr(be, "llm"):
|
|
254
|
+
del be.llm
|
|
255
|
+
del be
|
|
256
|
+
gc.collect()
|
|
257
|
+
reset_memory()
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def backend_factory(spec, md, a, fmt):
|
|
261
|
+
"""basal-bench mode, or MODE=WEIGHTS (the same model in other weights; the tokenizer must match)."""
|
|
262
|
+
from .bench import build as build_mode
|
|
263
|
+
from .engine import resolve
|
|
264
|
+
mode, _, weights = spec.partition("=")
|
|
265
|
+
wd = resolve(weights) if weights else md
|
|
266
|
+
return lambda: build_mode(mode, wd, gguf=a.gguf, ollama_model=a.ollama_model, ollama_url=a.ollama_url,
|
|
267
|
+
llamacpp_url=a.llamacpp_url, fmt=fmt)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
PROBE = "Stan: zażalenie złożono 3 marca 2026 r. State: 12.50 EUR"
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def own_questions(path, fmt, n):
|
|
274
|
+
"""The --questions items (basal-agree, basal-identity): the lines that are JSON objects with 2 to 10 options (255
|
|
275
|
+
in prompt format 2), the first n. A line that is not JSON stops the tool with its file and line."""
|
|
276
|
+
try:
|
|
277
|
+
qs = [q for _, q in records(path) if isinstance(q, dict)]
|
|
278
|
+
except JSONLError as e:
|
|
279
|
+
raise SystemExit(f"--questions {e}") from None
|
|
280
|
+
return [q for q in qs if "options" in q and 2 <= len(q["options"]) <= (255 if fmt == 2 else 10)][:n]
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def gold_items(qs, offset):
|
|
284
|
+
"""(item index, gold) of the questions whose gold is an option index; the others are left out, and said."""
|
|
285
|
+
gold = [(offset + i, q["gold"]) for i, q in enumerate(qs)
|
|
286
|
+
if isinstance(q.get("gold"), int) and not isinstance(q["gold"], bool) and 0 <= q["gold"] < len(q["options"])]
|
|
287
|
+
if sum("gold" in q for q in qs) != len(gold):
|
|
288
|
+
print(f"warning: {sum('gold' in q for q in qs) - len(gold)} item(s) with a gold that is not an option index "
|
|
289
|
+
"are left out of the accuracy", file=sys.stderr)
|
|
290
|
+
return gold
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def cache_home():
|
|
294
|
+
"""$XDG_CACHE_HOME, else ~/.cache; the XDG rule: an empty or relative value is ignored (it would put the cache in
|
|
295
|
+
whatever directory the command runs from)."""
|
|
296
|
+
x = os.environ.get("XDG_CACHE_HOME", "")
|
|
297
|
+
return Path(x) if x and os.path.isabs(x) else Path.home() / ".cache"
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def main(argv=None):
|
|
301
|
+
import sys
|
|
302
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
303
|
+
if "--identity" in argv: # the identity gate of the CUDA fast path
|
|
304
|
+
from .identity import main as identity
|
|
305
|
+
rows = identity([x for x in argv if x != "--identity"])
|
|
306
|
+
return 0 if all(r["gate"] == "pass" for r in rows) else 1
|
|
307
|
+
ap = argparse.ArgumentParser(prog="basal-agree", description=__doc__,
|
|
308
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
309
|
+
ap.add_argument("--model", required=True)
|
|
310
|
+
ap.add_argument("--backends", nargs="+", required=True, help="basal-bench modes, or MODE=WEIGHTS")
|
|
311
|
+
ap.add_argument("--reference", default="eager-fp32", help="the native engine's mode (default eager-fp32)")
|
|
312
|
+
ap.add_argument("--n-single", dest="n_single", type=int, default=100)
|
|
313
|
+
ap.add_argument("--n-multi", dest="n_multi", type=int, default=20)
|
|
314
|
+
ap.add_argument("--n-long", dest="n_long", type=int, default=10)
|
|
315
|
+
ap.add_argument("--seed", type=int, default=0)
|
|
316
|
+
ap.add_argument("--questions", default=None, help="JSONL of simple items {state, question, options, gold?}")
|
|
317
|
+
ap.add_argument("--n-questions", dest="n_questions", type=int, default=500)
|
|
318
|
+
ap.add_argument("--per-call", dest="per_call", type=positive, default=8, help="requests per call of a backend")
|
|
319
|
+
ap.add_argument("--independence", choices=["on", "off"], default="on")
|
|
320
|
+
ap.add_argument("--gate", type=float, default=GATE)
|
|
321
|
+
ap.add_argument("--cache", default=str(cache_home() / "basal" / "agree"),
|
|
322
|
+
help="directory of the cached reference rows ('' = none)")
|
|
323
|
+
ap.add_argument("--gguf", default=None)
|
|
324
|
+
ap.add_argument("--ollama-model", dest="ollama_model", default=None)
|
|
325
|
+
ap.add_argument("--ollama-url", dest="ollama_url", default=OLLAMA_URL)
|
|
326
|
+
ap.add_argument("--llamacpp-url", dest="llamacpp_url", default=LLAMACPP_URL)
|
|
327
|
+
ap.add_argument("--out", default=None)
|
|
328
|
+
a = ap.parse_args(argv)
|
|
329
|
+
from transformers import AutoTokenizer
|
|
330
|
+
|
|
331
|
+
from . import __version__
|
|
332
|
+
from .engine import resolve
|
|
333
|
+
from .server import default_orders, model_identity
|
|
334
|
+
md = resolve(a.model)
|
|
335
|
+
fmt = model_format(md)
|
|
336
|
+
tok = AutoTokenizer.from_pretrained(md)
|
|
337
|
+
for spec in a.backends:
|
|
338
|
+
w = spec.partition("=")[2]
|
|
339
|
+
if w and AutoTokenizer.from_pretrained(resolve(w))(PROBE).input_ids != tok(PROBE).input_ids:
|
|
340
|
+
raise SystemExit(f"{spec}: the weights {w} have a different tokenizer from {a.model}")
|
|
341
|
+
qs = []
|
|
342
|
+
if a.questions:
|
|
343
|
+
qs = own_questions(a.questions, fmt, a.n_questions)
|
|
344
|
+
single, multi, long = build(tok, fmt, a.n_single, a.n_multi, a.n_long, a.seed, qs)
|
|
345
|
+
sets = {"single": single, "multi": multi, "long": long}
|
|
346
|
+
gold = gold_items(qs, a.n_single)
|
|
347
|
+
model, revision = model_identity(a.model, md)
|
|
348
|
+
key = cache_key(model, revision, __version__, a.reference, sets, reference_weights(a))
|
|
349
|
+
path = Path(a.cache) / f"{key}.json" if a.cache else None
|
|
350
|
+
t0 = time.time()
|
|
351
|
+
ref, hit = cached_reference(path, backend_factory(a.reference, md, a, fmt), sets)
|
|
352
|
+
print(json.dumps(dict(model=model, revision=revision, reference=a.reference, cache=str(path) if path else None,
|
|
353
|
+
cached=hit, reference_s=round(time.time() - t0, 1),
|
|
354
|
+
readouts={k: sum(len(g[0]) for g in v) for k, v in sets.items()})), flush=True)
|
|
355
|
+
rows = []
|
|
356
|
+
for spec in a.backends:
|
|
357
|
+
t0 = time.time()
|
|
358
|
+
be = backend_factory(spec, md, a, fmt)()
|
|
359
|
+
load_s = time.time() - t0
|
|
360
|
+
t0 = time.time()
|
|
361
|
+
got = {k: run_groups(be, v, a.per_call) for k, v in sets.items()} # per set, per group, readouts
|
|
362
|
+
run_s = time.time() - t0
|
|
363
|
+
ind = flat(run_groups(be, alone(multi), 1)) if a.independence == "on" else None
|
|
364
|
+
free(be)
|
|
365
|
+
row = dict(backend=spec, load_s=round(load_s, 1), run_s=round(run_s, 1), **score(sets, ref, got, ind, gold,
|
|
366
|
+
orders=default_orders(None, fmt)))
|
|
367
|
+
row["readouts_multi"] = len(flat(got["multi"]))
|
|
368
|
+
row["gate"] = gate(row, a.gate)
|
|
369
|
+
rows.append(row)
|
|
370
|
+
print(json.dumps({k: round(v, 7) if isinstance(v, float) else v for k, v in row.items() if k != "sets"}),
|
|
371
|
+
flush=True)
|
|
372
|
+
w = max([28] + [len(r["backend"]) + 2 for r in rows])
|
|
373
|
+
print(f"\n{'backend':<{w}}{'readouts':>9}{'top-1':>8}{'95% CI':>16}{'ties':>7}{'mean|dp|':>10}{'max|dp|':>10}"
|
|
374
|
+
f"{'decisions':>10}{'indep.':>8} gate (reference {a.reference})")
|
|
375
|
+
for r in rows:
|
|
376
|
+
ci = f"[{r['agreement_ci'][0]:.3f}, {r['agreement_ci'][1]:.3f}]"
|
|
377
|
+
ind = f"{r['independence']:.3f}" if "independence" in r else "-"
|
|
378
|
+
print(f"{r['backend']:<{w}}{r['readouts']:>9}{r['agreement']:>8.4f}{ci:>16}"
|
|
379
|
+
f"{str(r['near_ties']) + '/' + str(r['disagreements']):>7}{r['mean_dp']:>10.2e}{r['max_dp']:>10.2e}"
|
|
380
|
+
f"{r.get('decision_agreement', float('nan')):>10.4f}{ind:>8} {r['gate']}")
|
|
381
|
+
if "accuracy" in r:
|
|
382
|
+
lo, hi = r["accuracy_diff_ci"]
|
|
383
|
+
print(f"{'':<{w}}accuracy {r['accuracy']:.4f} vs {r['reference_accuracy']:.4f} "
|
|
384
|
+
f"(paired 95% CI of the difference [{lo:+.4f}, {hi:+.4f}], {len(gold)} items)")
|
|
385
|
+
if a.out:
|
|
386
|
+
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
|
|
387
|
+
write_json(a.out, finite(dict(model=model, revision=revision, reference=a.reference, version=__version__,
|
|
388
|
+
questions=len(qs), rows=rows)), indent=1) # a metric without a value: null
|
|
389
|
+
return 0 if all(r["gate"] == "pass" for r in rows) else 1
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
if __name__ == "__main__":
|
|
393
|
+
raise SystemExit(main())
|
basal/attach.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Attach a base model: serve a chat model that was never trained on basal decisions (a Gemma 4 or Qwen model, for
|
|
2
|
+
example) as a decision model, without retraining, and fit its calibration on your own labelled requests.
|
|
3
|
+
|
|
4
|
+
basal-attach Qwen/Qwen3-4B --out qwen3-4b-basal # the model directory basal-serve reads
|
|
5
|
+
basal-serve --model qwen3-4b-basal --mode eager
|
|
6
|
+
basal-calibrate labelled.jsonl --model qwen3-4b-basal --mode eager --out CALIBRATION.custom.json
|
|
7
|
+
basal-serve --model qwen3-4b-basal --mode eager --calibration CALIBRATION.custom.json
|
|
8
|
+
|
|
9
|
+
The output directory links (symlinks) every file of the base model and adds:
|
|
10
|
+
basal.json "prompt": the prompt format (1 by default: options A-J and an answer instruction, which a model
|
|
11
|
+
not trained on basal follows best; 2 with --format 2: up to 255 option codes, when every code is
|
|
12
|
+
one token), "layout": "canonical", "attached": the base model and its revision, "readout": the
|
|
13
|
+
option codes and their token ids at the answer position;
|
|
14
|
+
CALIBRATION.json uncalibrated defaults: no temperatures (1.0) and no certified thresholds, so max_error defers
|
|
15
|
+
every automatic action and act answers say "calibration": "unvalidated" until you serve a file
|
|
16
|
+
fitted with basal-calibrate;
|
|
17
|
+
chat_template.jinja only for a tokenizer without a chat template: --chat-template FILE, else a plain one
|
|
18
|
+
("System: ...", "User: ...", "Assistant: ").
|
|
19
|
+
The readout of every type is the next-token distribution over the option codes after the chat template and the
|
|
20
|
+
{"answer": " prefill (a noul question reads two codes, a score question one per level), so every code of the format
|
|
21
|
+
must be one token there. basal-attach checks that on a Polish and an English prompt and refuses a format whose codes
|
|
22
|
+
the tokenizer splits.
|
|
23
|
+
"""
|
|
24
|
+
import argparse
|
|
25
|
+
import datetime
|
|
26
|
+
import json
|
|
27
|
+
import os
|
|
28
|
+
import shutil
|
|
29
|
+
import sys
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
|
|
32
|
+
from . import __version__
|
|
33
|
+
from .prompt import FORMATS, letter_ids, max_options, render
|
|
34
|
+
|
|
35
|
+
PLAIN_TEMPLATE = ("{% for m in messages %}{{ m['role'] | capitalize }}: {{ m['content'] }}\n\n{% endfor %}"
|
|
36
|
+
"{% if add_generation_prompt %}Assistant: {% endif %}")
|
|
37
|
+
SAMPLE = {"en": ("Order 1240 arrived damaged; the customer asks for a refund.", "What should we do?"),
|
|
38
|
+
"pl": ("Zamówienie 1240 dotarło uszkodzone; klient prosi o zwrot.", "Co robimy?")}
|
|
39
|
+
OWN = ("basal.json", "CALIBRATION.json") # written here, never linked from the base
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def split_codes(tok, prompt, fmt):
|
|
43
|
+
"""The option codes of a format that are not one token at the answer position of `prompt`."""
|
|
44
|
+
base = tok(prompt, add_special_tokens=False).input_ids
|
|
45
|
+
bad = []
|
|
46
|
+
for c in FORMATS[fmt]["codes"]:
|
|
47
|
+
full = tok(prompt + c, add_special_tokens=False).input_ids
|
|
48
|
+
if full[: len(base)] != base or len(full) != len(base) + 1:
|
|
49
|
+
bad.append(c)
|
|
50
|
+
return bad
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def readout(tok, fmt):
|
|
54
|
+
"""{lang: the token id of every option code of the format at the answer position}, on one prompt per language
|
|
55
|
+
with the most options of the format; SystemExit naming the codes the tokenizer splits (or that share an id)."""
|
|
56
|
+
out = {}
|
|
57
|
+
for lang, (state, question) in SAMPLE.items():
|
|
58
|
+
prompt = render(tok, state, question, [f"option {i}" for i in range(max_options(fmt))], lang, fmt)
|
|
59
|
+
ids = letter_ids(tok, prompt, max_options(fmt), fmt)
|
|
60
|
+
if ids is None:
|
|
61
|
+
bad = split_codes(tok, prompt, fmt)
|
|
62
|
+
why = (f"{len(bad)} of its {max_options(fmt)} option codes are not one token at the answer position "
|
|
63
|
+
f"({', '.join(bad[:12])}{' ...' if len(bad) > 12 else ''})" if bad
|
|
64
|
+
else "two option codes share a token id")
|
|
65
|
+
raise SystemExit(f"prompt format {fmt}: {why} for this tokenizer ({lang} prompt)"
|
|
66
|
+
+ ("; use --format 1 (options A-J)" if fmt == 2 else ""))
|
|
67
|
+
out[lang] = ids
|
|
68
|
+
return out
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def check_out(src, out):
|
|
72
|
+
"""SystemExit before anything is written when the output directory is the base's own directory (also through a
|
|
73
|
+
symlink), lies inside it or contains it: the links would replace the base's files with links to themselves."""
|
|
74
|
+
s, o = Path(src).resolve(), Path(out).resolve()
|
|
75
|
+
if o == s:
|
|
76
|
+
raise SystemExit(f"--out {out}: the base model's own directory; give a new directory")
|
|
77
|
+
if o.is_relative_to(s) or s.is_relative_to(o):
|
|
78
|
+
raise SystemExit(f"--out {out}: {'inside' if o.is_relative_to(s) else 'contains'} the base model's directory "
|
|
79
|
+
f"{src}; give a directory outside it")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def attach(base, out, fmt=1, chat_template=None, revision=None, force=False):
|
|
83
|
+
"""Write the basal model directory `out` for the base model `base` (a directory or a Hugging Face repo id) ->
|
|
84
|
+
the basal.json written."""
|
|
85
|
+
from transformers import AutoTokenizer
|
|
86
|
+
|
|
87
|
+
from .engine import resolve
|
|
88
|
+
from .server import model_identity
|
|
89
|
+
src = resolve(base, revision)
|
|
90
|
+
if (src / "basal.json").exists():
|
|
91
|
+
raise SystemExit(f"{base} is already a basal model (it has basal.json): serve it as it is")
|
|
92
|
+
out = Path(out)
|
|
93
|
+
check_out(src, out)
|
|
94
|
+
if out.exists() and any(out.iterdir()) and not force:
|
|
95
|
+
raise SystemExit(f"--out {out}: not empty (--force replaces the links and files basal-attach writes)")
|
|
96
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
97
|
+
for f in sorted(src.iterdir()):
|
|
98
|
+
if f.name in OWN or f.name == "chat_template.jinja" and chat_template:
|
|
99
|
+
continue
|
|
100
|
+
link = out / f.name
|
|
101
|
+
if link.is_symlink() or link.exists():
|
|
102
|
+
shutil.rmtree(link) if link.is_dir() and not link.is_symlink() else link.unlink()
|
|
103
|
+
target = f.resolve() if f.is_symlink() else f.absolute()
|
|
104
|
+
try:
|
|
105
|
+
link.symlink_to(target, target_is_directory=target.is_dir())
|
|
106
|
+
except OSError:
|
|
107
|
+
if target.is_dir():
|
|
108
|
+
shutil.copytree(target, link)
|
|
109
|
+
else:
|
|
110
|
+
try:
|
|
111
|
+
os.link(target, link)
|
|
112
|
+
except OSError:
|
|
113
|
+
shutil.copy2(target, link)
|
|
114
|
+
tok = AutoTokenizer.from_pretrained(out)
|
|
115
|
+
template = None
|
|
116
|
+
if chat_template or not getattr(tok, "chat_template", None):
|
|
117
|
+
template = Path(chat_template).read_text(encoding="utf-8") if chat_template else PLAIN_TEMPLATE
|
|
118
|
+
(out / "chat_template.jinja").unlink(missing_ok=True)
|
|
119
|
+
(out / "chat_template.jinja").write_text(template, encoding="utf-8")
|
|
120
|
+
tok = AutoTokenizer.from_pretrained(out)
|
|
121
|
+
if tok.chat_template != template:
|
|
122
|
+
raise SystemExit(f"{out}: the tokenizer does not use chat_template.jinja (its tokenizer_config.json has a "
|
|
123
|
+
"chat template of its own)")
|
|
124
|
+
ids = readout(tok, fmt)
|
|
125
|
+
config = json.loads((src / "config.json").read_text(encoding="utf-8")) if (src / "config.json").exists() else {}
|
|
126
|
+
name, rev = model_identity(base, src)
|
|
127
|
+
meta = {"prompt": fmt, "layout": "canonical",
|
|
128
|
+
"attached": {"base": name, "revision": rev, "model_type": config.get("model_type"),
|
|
129
|
+
"chat_template": "chat_template.jinja (plain)" if template == PLAIN_TEMPLATE
|
|
130
|
+
else "chat_template.jinja (--chat-template)" if template else "the base's",
|
|
131
|
+
"date": datetime.date.today().isoformat(), "tool": f"basal-attach {__version__}"},
|
|
132
|
+
"readout": {"codes": "".join(FORMATS[fmt]["codes"]) if fmt == 1 else list(FORMATS[fmt]["codes"]),
|
|
133
|
+
"ids": ids["en"] if ids["en"] == ids["pl"] else ids}}
|
|
134
|
+
(out / "basal.json").write_text(json.dumps(meta, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
135
|
+
cal = {"prompt": fmt, "temperature_per_prim": {}, "thresholds": {},
|
|
136
|
+
"source_tag": "basal-attach defaults, uncalibrated: fit with basal-calibrate"}
|
|
137
|
+
(out / "CALIBRATION.json").write_text(json.dumps(cal, indent=1) + "\n", encoding="utf-8")
|
|
138
|
+
return meta
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def main(argv=None):
|
|
142
|
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
143
|
+
ap.add_argument("base", help="the base model: a local directory or a Hugging Face repo id")
|
|
144
|
+
ap.add_argument("--out", required=True, help="the basal model directory to write (links to the base's files)")
|
|
145
|
+
ap.add_argument("--format", type=int, choices=sorted(FORMATS), default=1,
|
|
146
|
+
help="prompt format: 1 (options A-J with an answer instruction, the default) or 2 (up to 255 codes)")
|
|
147
|
+
ap.add_argument("--chat-template", dest="chat_template", default=None,
|
|
148
|
+
help="a Jinja chat template for a tokenizer without one (default: a plain one)")
|
|
149
|
+
ap.add_argument("--revision", default=None, help="the base's Hugging Face revision")
|
|
150
|
+
ap.add_argument("--force", action="store_true", help="write into a directory that is not empty")
|
|
151
|
+
a = ap.parse_args(argv)
|
|
152
|
+
meta = attach(a.base, a.out, a.format, a.chat_template, a.revision, a.force)
|
|
153
|
+
print(f"wrote {a.out}: prompt format {meta['prompt']}, {max_options(meta['prompt'])} options at most, readout "
|
|
154
|
+
f"checked on the base's tokenizer ({meta['attached']['chat_template']} chat template); uncalibrated until "
|
|
155
|
+
f"basal-calibrate:\n basal-serve --model {a.out} --mode eager\n"
|
|
156
|
+
f" basal-calibrate labelled.jsonl --model {a.out} --mode eager --out CALIBRATION.custom.json", file=sys.stderr)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
if __name__ == "__main__":
|
|
160
|
+
main()
|