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/selfcheck.py ADDED
@@ -0,0 +1,215 @@
1
+ """basal-selfcheck: does this server (this GPU, this build, this quantisation) answer like the reference?
2
+
3
+ basal-selfcheck --url http://127.0.0.1:8000 --reference basal-2.0-mini # a reference file we ship
4
+ basal-selfcheck --url http://127.0.0.1:8000 --reference ref.json --note "GTX 1060 6GB, Vulkan, Q8_0"
5
+
6
+ A reference file holds a few dozen requests (short, medium and long states, Polish and English, choice / noul / score
7
+ questions) and the probabilities that basal's own PyTorch engine (fp32) gave for them. The check sends the same
8
+ requests to your server and prints, over all readouts:
9
+
10
+ top-1 agreement the share of questions whose most probable option is the reference's. A disagreement where the
11
+ server's top option was within 0.02 of the reference's top, in the reference, counts as
12
+ agreeing ("outside near ties"): any change of rounding can flip those
13
+ max |dp| the largest change of any option's probability, and the mean
14
+ seconds wall time per request
15
+
16
+ The exit status is 0 when the agreement outside near ties is at least --gate (default 0.98), 1 otherwise. Start the
17
+ server without calibration (basal-serve ... --no-calibration), as the reference was made: the check compares raw
18
+ probabilities. Requests the server had to cut (usage.truncated: the context is too short) are left out and counted; the check
19
+ fails (exit 1) when fewer than half of the requests were compared, when a request failed or when a question came back
20
+ unanswered.
21
+
22
+ Make a reference file for a model (a maintainer's step; run it against a server of the native engine, fp32):
23
+
24
+ basal-serve --model Remek/basal-2.0-mini --dtype float32 --no-calibration --port 8000
25
+ basal-selfcheck --make-reference basal-2.0-mini.json --url http://127.0.0.1:8000"""
26
+ import argparse
27
+ import json
28
+ import sys
29
+ import time
30
+ import urllib.error
31
+ import urllib.request
32
+ from pathlib import Path
33
+
34
+ from . import __version__, synth
35
+ from .cli import add_api_key, headers, refused
36
+ from .jsonl import JSONLError, write_json
37
+ from .textio import read_text
38
+
39
+ TIE = 0.02
40
+ SHAPES = ((12, 200), (6, 800), (2, 1500)) # (requests, state tokens)
41
+ EXAMPLES = Path(__file__).parent / "examples"
42
+
43
+ QUESTIONS = {
44
+ "pl": {"urgent": ("noul", "Czy klient potrzebuje odpowiedzi jeszcze dziś?", None),
45
+ "tone": ("score", "Jaki jest ton ostatniego zgłoszenia?", ["spokojny", "zniecierpliwiony", "wzburzony"])},
46
+ "en": {"urgent": ("noul", "Does the customer need an answer today?", None),
47
+ "tone": ("score", "What is the tone of the latest ticket?", ["calm", "impatient", "angry"])},
48
+ }
49
+
50
+
51
+ def build_requests():
52
+ """The reference requests: one state with a choice question (the unit that should handle the latest entry, 2..10
53
+ options), a yes/no question and a three-level score question. Deterministic (basal.synth)."""
54
+ reqs = []
55
+ for k, (n, tokens) in enumerate(SHAPES):
56
+ for it in synth.items(n, tokens, seed=100 + k):
57
+ lang = "pl" if any(c in "ąćęłńóśźż" for c in it["state"]) else "en"
58
+ qs = {"unit": {"type": "choice", "instructions": it["question"],
59
+ "criteria": {f"o{i}": o for i, o in enumerate(it["options"])}}}
60
+ for name, (kind, text, levels) in QUESTIONS[lang].items():
61
+ qs[name] = {"type": kind, "instructions": text, **({"criteria": levels} if levels else {})}
62
+ reqs.append({"id": f"{len(reqs):02d}-{tokens}-{lang}", "state": it["state"], "questions": qs})
63
+ return reqs
64
+
65
+
66
+ def call(url, path, body=None, timeout=300, key=None):
67
+ """GET (body None) or POST url + path -> the JSON answer; key: the server's API key (basal.cli.headers)."""
68
+ req = urllib.request.Request(url.rstrip("/") + path, data=None if body is None else json.dumps(body).encode(),
69
+ headers={"content-type": "application/json", **headers(key)},
70
+ method="GET" if body is None else "POST")
71
+ try:
72
+ with urllib.request.urlopen(req, timeout=timeout) as r:
73
+ return json.loads(r.read())
74
+ except urllib.error.HTTPError as e:
75
+ raise SystemExit(refused(f"{url}{path}", e.code, key)
76
+ or f"{url}{path}: HTTP {e.code}: {e.read().decode(errors='replace')[:300]}") from None
77
+ except OSError as e:
78
+ raise SystemExit(f"{url}{path}: {e} (is the server running?)") from None
79
+ except ValueError as e: # a 200 that is not JSON (a proxy's error page)
80
+ raise SystemExit(f"{url}{path}: the reply is not JSON ({e})") from None
81
+
82
+
83
+ def uncalibrated(entry):
84
+ """Whether a GET /v1/models entry serves raw probabilities: every temperature 1.0, the per-type ones and the
85
+ per-option-count ones of a format-2 calibration (as basal-calibrate checks a server)."""
86
+ temps = list((entry.get("temperature_per_prim") or {}).values())
87
+ for per_bucket in (entry.get("temperature_per_bucket") or {}).values():
88
+ temps += list((per_bucket or {}).values())
89
+ return all(float(t) == 1.0 for t in temps)
90
+
91
+
92
+ def server_info(url, key=None):
93
+ m = call(url, "/v1/models", key=key)["models"][0]
94
+ return {"name": m.get("name"), "mode": m.get("mode"), "uncalibrated": uncalibrated(m)}
95
+
96
+
97
+ def find(reference):
98
+ """A reference given by a model name -> the file shipped with basal, else a path."""
99
+ for p in (Path(reference), EXAMPLES / f"selfcheck_{reference}.json", EXAMPLES / reference):
100
+ if p.is_file():
101
+ return p
102
+ shipped = sorted(f.stem.removeprefix("selfcheck_") for f in EXAMPLES.glob("selfcheck_*.json"))
103
+ raise SystemExit(f"reference {reference!r}: not a file; shipped references: {', '.join(shipped) or 'none'}")
104
+
105
+
106
+ def make_reference(url, out, note="", key=None):
107
+ info = server_info(url, key)
108
+ if not info["uncalibrated"]:
109
+ raise SystemExit("the reference needs raw probabilities: start the server with --no-calibration")
110
+ items = []
111
+ for req in build_requests():
112
+ res = call(url, "/v1/systemone", {"state": req["state"], "questions": req["questions"]}, key=key)
113
+ items.append({**req, "answers": {k: {"type": a["type"], "probabilities": a["probabilities"]}
114
+ for k, a in res["answers"].items()}})
115
+ ref = {"format": 1, "model": (info["name"] or "").removesuffix("-GGUF"), "engine": info["mode"], "basal": __version__,
116
+ "note": note or "probabilities of basal's native engine, uncalibrated", "items": items}
117
+ try: # whole or not at all
118
+ write_json(out, ref, separators=(",", ":"))
119
+ except JSONLError as e: # a NaN probability: no reference to compare with
120
+ raise SystemExit(f"basal-selfcheck: no reference written: {e}") from None
121
+ print(f"wrote {out}: {len(items)} requests, {sum(len(i['answers']) for i in items)} readouts", file=sys.stderr)
122
+
123
+
124
+ def compare(ref, got):
125
+ """Probability dicts of one question -> (top-1 agrees, agrees outside near ties, max |dp|, sum |dp|, options)."""
126
+ keys = list(ref)
127
+ r, g = [ref[k] for k in keys], [got.get(k, 0.0) for k in keys]
128
+ if any(x != x or abs(x) == float("inf") for x in g + r): # a NaN or infinite answer or reference is the largest possible change, never an agreement
129
+ return False, False, 1.0, float(len(keys)), len(keys)
130
+ a, b = max(range(len(r)), key=r.__getitem__), max(range(len(g)), key=g.__getitem__)
131
+ dps = [abs(x - y) for x, y in zip(r, g)]
132
+ # near tie: the server's top option is within TIE of the reference's top, in the reference's probabilities (a
133
+ # three-way tie counts), so a flip to an option the reference ranked clearly lower is still a disagreement
134
+ return a == b, a == b or r[a] - r[b] < TIE, max(dps), sum(dps), len(keys)
135
+
136
+
137
+ def check(url, reference, gate, note, key=None):
138
+ ref = json.loads(read_text(find(reference)))
139
+ info = server_info(url, key)
140
+ if info["name"] and ref["model"] and info["name"].removesuffix("-GGUF") != ref["model"].removesuffix("-GGUF"):
141
+ print(f"warning: the server reports model {info['name']!r}, the reference is for {ref['model']!r}", file=sys.stderr)
142
+ if not info["uncalibrated"]:
143
+ print("warning: the server applies a calibration; start it with --no-calibration, or the probabilities are "
144
+ "tempered and the |dp| below is not the engine's", file=sys.stderr)
145
+ rows, cut, errors, missing, times = [], 0, 0, 0, []
146
+ for it in ref["items"]:
147
+ t = time.perf_counter()
148
+ try:
149
+ res = call(url, "/v1/systemone", {"state": it["state"], "questions": it["questions"]}, key=key)
150
+ except SystemExit as e:
151
+ errors += 1
152
+ print(f"{it['id']}: {e}", file=sys.stderr)
153
+ continue
154
+ times.append(time.perf_counter() - t)
155
+ if not isinstance(res, dict) or not isinstance(res.get("answers"), dict):
156
+ # a 200 that is JSON but not an answer ({"error": ...}, null, a list): a failed request
157
+ errors += 1
158
+ print(f"{it['id']}: the reply is not an answer object ({str(res)[:100]})", file=sys.stderr)
159
+ continue
160
+ if (res.get("usage") or {}).get("truncated"):
161
+ cut += 1
162
+ continue
163
+ for name, want in it["answers"].items():
164
+ a = res["answers"].get(name)
165
+ if not isinstance(a, dict) or not isinstance(a.get("probabilities"), dict):
166
+ missing += 1 # unanswered or without probabilities: not a pass
167
+ continue
168
+ rows.append((it["id"], name, want["type"], *compare(want["probabilities"], a["probabilities"])))
169
+ if not rows:
170
+ raise SystemExit("no readouts compared (every request failed, was cut or came back without answers: "
171
+ f"{errors} failed, {cut} cut, {missing} answers missing)")
172
+ n = len(rows)
173
+ top1 = sum(r[3] for r in rows) / n
174
+ agree = sum(r[4] for r in rows) / n
175
+ worst = max(rows, key=lambda r: r[5])
176
+ options = sum(r[7] for r in rows)
177
+ times.sort()
178
+ print(f"basal-selfcheck {__version__} reference {ref['model']} ({ref['engine']}, basal {ref['basal']}): {ref['note']}")
179
+ print(f"server {info['name']} ({info['mode']})" + (f" {note}" if note else ""))
180
+ print(f"requests {len(ref['items'])}: {len(ref['items']) - cut - errors} compared, {cut} cut by the context "
181
+ f"(usage.truncated), {errors} failed, {missing} answers missing")
182
+ print(f"readouts {n}")
183
+ print(f"top-1 {top1:.4f} outside near ties (server's top within {TIE} of the reference's top) {agree:.4f}")
184
+ print(f"|dp| mean {sum(r[6] for r in rows) / options:.4f} max {worst[5]:.4f} ({worst[0]} {worst[1]})")
185
+ print(f"seconds p50 {times[len(times) // 2]:.2f} max {times[-1]:.2f} per request" if times else "")
186
+ for t in ("choice", "noul", "score"):
187
+ sub = [r for r in rows if r[2] == t]
188
+ if sub:
189
+ print(f" {t:<7} {len(sub):>4} readouts top-1 {sum(r[3] for r in sub) / len(sub):.4f} "
190
+ f"max |dp| {max(r[5] for r in sub):.4f}")
191
+ ok = agree >= gate and not errors and not missing and len(ref["items"]) - cut - errors >= len(ref["items"]) / 2
192
+ print(f"{'PASS' if ok else 'FAIL'} (gate: agreement outside near ties >= {gate}, no failed request, no missing answer, "
193
+ "at least half of the requests compared)")
194
+ return 0 if ok else 1
195
+
196
+
197
+ def main(argv=None):
198
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
199
+ ap.add_argument("--url", default="http://127.0.0.1:8000", help="the basal-serve (any --mode) to check")
200
+ ap.add_argument("--reference", help="a reference file, or the name of one shipped with basal")
201
+ ap.add_argument("--gate", type=float, default=0.98)
202
+ ap.add_argument("--note", default="", help="what you test, printed with the result (GPU, driver, quantisation); "
203
+ "with --make-reference: how the reference was made")
204
+ ap.add_argument("--make-reference", dest="make", metavar="FILE", help="write a reference file from this server")
205
+ add_api_key(ap)
206
+ a = ap.parse_args(argv)
207
+ if a.make:
208
+ return make_reference(a.url, a.make, a.note, a.api_key)
209
+ if not a.reference:
210
+ ap.error("--reference is required (or --make-reference FILE)")
211
+ sys.exit(check(a.url, a.reference, a.gate, a.note, a.api_key))
212
+
213
+
214
+ if __name__ == "__main__":
215
+ main()