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/sets.py ADDED
@@ -0,0 +1,214 @@
1
+ """Set selection for `multi`: which labels to return, from one independent probability per label.
2
+
3
+ threshold labels with p >= threshold (default 0.5), at most `max`, at least `min` (the 1.5 behaviour)
4
+ exact labels with p >= 0.5: the most probable set, i.e. the highest chance that the selected set is exactly right
5
+ iou the set with the highest expected IoU (Jaccard index) with the true set
6
+ f1 the set with the highest expected F1 with the true set
7
+
8
+ Under independence the best set of a given size is the top-k labels by probability (swapping a less probable label in
9
+ for a more probable one never raises the expected score), so the engine scores every prefix k = min..max of the labels
10
+ sorted by probability and returns the best one with its expected score. Both empty (nothing selected, nothing applies)
11
+ counts as a perfect match.
12
+
13
+ The expectations are exact. With A ~ the positives inside the prefix and B ~ the positives outside it (independent
14
+ Poisson-binomial variables), IoU = A / (k + B) and F1 = 2A / (k + A + B), and their expectations are integrals of the
15
+ Poisson-binomial generating functions, G_B(t) = prod_j (1 - p_j + p_j t):
16
+
17
+ E[IoU_k] = E[A] * E[1 / (k + B)] = E[A] * int_0^1 t^(k-1) G_B(t) dt
18
+ E[F1_k] = 2 sum_{i <= k} p_i E[1 / (k + 1 + N_-i)] = 2 int_0^1 t^k sum_{i <= k} p_i prod_{j != i} (1 - p_j + p_j t) dt
19
+
20
+ (N_-i: the positives among all labels except i). The integrands are polynomials of degree < 2n, so Gauss-Legendre
21
+ quadrature with M >= n nodes integrates them exactly up to rounding; all prefixes together cost O(n M) in log space
22
+ (255 labels: about 0.1 ms on a CPU).
23
+ """
24
+ import builtins
25
+ import hashlib
26
+ import json
27
+ import math
28
+ from functools import lru_cache
29
+
30
+ import numpy as np
31
+
32
+ OBJECTIVES = ("threshold", "exact", "iou", "f1")
33
+
34
+
35
+ @lru_cache(maxsize=None)
36
+ def _nodes(m):
37
+ """Gauss-Legendre quadrature on [0, 1] with m nodes (exact for polynomials of degree <= 2m - 1): the weighted
38
+ powers w_m t_m^j, j = 0..256, as a [257, m] table."""
39
+ x, w = np.polynomial.legendre.leggauss(m)
40
+ t = (x + 1) / 2
41
+ return t, w / 2 * t[None, :] ** np.arange(257)[:, None]
42
+
43
+
44
+ def _running(x, op, reverse=False):
45
+ """Running product / sum over the labels (axis 0), one row of nodes per step: much faster than numpy's
46
+ accumulate along an axis for these shapes."""
47
+ out = np.empty_like(x)
48
+ rows = range(len(x) - 1, -1, -1) if reverse else range(len(x))
49
+ prev = None
50
+ for i in rows:
51
+ out[i] = x[i] if prev is None else op(out[prev], x[i])
52
+ prev = i
53
+ return out
54
+
55
+
56
+ def expected_scores(p, objective):
57
+ """p: probabilities sorted in descending order -> expected score of every prefix k = 0..n (array of n + 1)."""
58
+ p = np.clip(np.asarray(p, dtype=np.float64), 0.0, 1.0)
59
+ n = len(p)
60
+ if objective == "exact":
61
+ with np.errstate(divide="ignore"):
62
+ lp, lq = np.log(p), np.log1p(-p)
63
+ return np.exp(np.concatenate([[0.0], np.cumsum(lp)]) + np.concatenate([np.cumsum(lq[::-1])[::-1], [0.0]]))
64
+ if objective not in ("iou", "f1"):
65
+ raise ValueError(f"unknown objective {objective!r}")
66
+ if n == 0:
67
+ return np.array([1.0])
68
+ if n > 256:
69
+ raise ValueError(f"{n} labels (at most 256)")
70
+ # nodes: IoU's integrands have degree n - 1, F1's at most 2n - 1; m is rounded up to a power of two (cached)
71
+ m = 8
72
+ while 2 * m - 1 < (n - 1 if objective == "iou" else 2 * n - 1):
73
+ m *= 2
74
+ t, wt = _nodes(m)
75
+ # factors 1 - p_j + p_j t lie in [t, 1]: products in linear space can only underflow, where the integrand is
76
+ # negligible next to its values near t = 1 (every term is positive)
77
+ f = 1 + np.multiply.outer(p, t - 1) # [n, m]
78
+ if objective == "iou":
79
+ suf = _running(f, np.multiply, reverse=True) # prod_{j >= k}, k = 0..n-1
80
+ inv = np.einsum("km,km->k", wt[:n], np.vstack([suf[1:], np.ones((1, m))])) # E[1 / (k + B_k)], k = 1..n
81
+ out = np.cumsum(p) * inv
82
+ else:
83
+ loo = p[:, None] / f * np.prod(f, 0) # p_i prod_{j != i} (f_i >= t > 0)
84
+ out = 2 * np.einsum("km,km->k", wt[1: n + 1], _running(loo, np.add)) # k = 1..n
85
+ return np.concatenate([[np.prod(1 - p)], np.minimum(out, 1.0)]) # k = 0: right only if no label applies
86
+
87
+
88
+ def _alone(probs, key, objective):
89
+ """Expected score of selecting exactly {key} (every other label outside the set)."""
90
+ rest = [v for k, v in probs.items() if k != key]
91
+ return float(expected_scores([probs[key]] + rest, objective)[1])
92
+
93
+
94
+ def select(probs, objective="threshold", threshold=0.5, min=None, max=None, exclusive=(), fallback=None,
95
+ fallback_threshold=None):
96
+ """probs: {key: P(label applies)} -> (selected keys, expected score or None for threshold, constraints applied or
97
+ None).
98
+
99
+ Label constraints (keys of probs):
100
+ exclusive labels that can only be selected alone (a "general / no narrowing" category): the best set of the
101
+ other labels competes with each of them alone, under the objective (threshold: an exclusive label
102
+ with p >= threshold wins when it is more probable than every label of the thresholded set)
103
+ fallback a label selected only when nothing else is (implicitly exclusive): under threshold when its p >=
104
+ fallback_threshold (default: threshold), under iou / f1 / exact when it scores higher alone than the
105
+ empty set; an explicit fallback_threshold decides under every objective
106
+ The empty set stays a candidate unless min >= 1 (both empty counts as a perfect match)."""
107
+ excl = list(dict.fromkeys(list(exclusive or ()) + ([fallback] if fallback is not None else [])))
108
+ alone = [e for e in excl if e != fallback]
109
+ normal = {k: v for k, v in probs.items() if k not in excl}
110
+ order = sorted(normal, key=normal.get, reverse=True)
111
+ n = len(order)
112
+ one_ok = int(min or 0) <= 1 and (max is None or int(max) >= 1) # may a single label be the whole set?
113
+ chosen = "labels"
114
+ if objective == "threshold":
115
+ sel = [k for k in order if probs[k] >= threshold]
116
+ if max is not None:
117
+ sel = sel[: int(max)]
118
+ if min is not None and len(sel) < int(min):
119
+ sel = order[: int(min)]
120
+ score = None
121
+ cand = [e for e in alone if probs[e] >= threshold]
122
+ if cand and one_ok:
123
+ e = builtins.max(cand, key=probs.get)
124
+ if not sel or probs[e] > builtins.max(probs[k] for k in sel):
125
+ sel, chosen = [e], "exclusive"
126
+ if fallback is not None and not sel and one_ok:
127
+ if probs[fallback] >= (threshold if fallback_threshold is None else fallback_threshold):
128
+ sel, chosen = [fallback], "fallback"
129
+ else:
130
+ lo = builtins.min(int(min or 0), n)
131
+ hi = n if max is None else int(builtins.min(max, n))
132
+ p = [probs[k] for k in order]
133
+ # the constrained labels sit outside every prefix: the scores of k = 0..n are those of the normal sets
134
+ scores = expected_scores(p + [probs[e] for e in excl], objective)
135
+ if objective == "exact":
136
+ best = int(np.clip(sum(x >= 0.5 for x in p), lo, hi))
137
+ else:
138
+ best = lo + int(np.argmax(scores[lo: hi + 1]))
139
+ sel, score = order[:best], float(scores[best])
140
+ if one_ok:
141
+ for e in alone:
142
+ s = _alone(probs, e, objective)
143
+ if s > score:
144
+ sel, score, chosen = [e], s, "exclusive"
145
+ if fallback is not None and not sel:
146
+ s = _alone(probs, fallback, objective)
147
+ if (s > score) if fallback_threshold is None else probs[fallback] >= fallback_threshold:
148
+ sel, score, chosen = [fallback], s, "fallback"
149
+ if not excl:
150
+ return sel, score, None
151
+ applied = dict(exclusive=alone, fallback=fallback, chosen=chosen if sel else "empty")
152
+ if fallback is not None:
153
+ applied["fallback_threshold"] = threshold if fallback_threshold is None and objective == "threshold" \
154
+ else fallback_threshold
155
+ return sel, score, applied
156
+
157
+
158
+ def validate(name, objective, keys, threshold=None, min=None, max=None, exclusive=None, fallback=None,
159
+ fallback_threshold=None):
160
+ """Request checks (the threshold objective keeps the 1.5 handling of min / max)."""
161
+ n = len(keys)
162
+ if objective not in OBJECTIVES:
163
+ raise ValueError(f"question {name!r}: objective must be one of {list(OBJECTIVES)}, got {objective!r}")
164
+ if objective in ("iou", "f1") and n > 256: # (expected_scores; refused after the engine's run before)
165
+ raise ValueError(f"question {name!r}: objective {objective!r} takes at most 256 labels, got {n}")
166
+ if exclusive is not None:
167
+ if not isinstance(exclusive, list) or not all(isinstance(e, str) for e in exclusive):
168
+ raise ValueError(f"question {name!r}: exclusive must be a list of label keys")
169
+ bad = [e for e in exclusive if e not in keys]
170
+ if bad:
171
+ raise ValueError(f"question {name!r}: exclusive labels {bad} are not among the criteria")
172
+ if fallback is not None and fallback not in keys:
173
+ raise ValueError(f"question {name!r}: fallback {fallback!r} is not among the criteria")
174
+ if fallback_threshold is not None:
175
+ if fallback is None:
176
+ raise ValueError(f"question {name!r}: fallback_threshold needs a fallback label")
177
+ if isinstance(fallback_threshold, bool) or not isinstance(fallback_threshold, (int, float)) \
178
+ or not 0 <= fallback_threshold <= 1:
179
+ raise ValueError(f"question {name!r}: fallback_threshold must be a number in 0..1")
180
+ if objective == "threshold":
181
+ if threshold is not None:
182
+ try:
183
+ finite = math.isfinite(float(threshold)) # the legacy coercion ("0.25") stays; NaN and inf are refused
184
+ except OverflowError:
185
+ finite = False # an integer beyond the largest float (10**400) is as infinite as inf
186
+ except (TypeError, ValueError):
187
+ finite = True # not a number at all: refused below with "could not convert", as before
188
+ if not finite:
189
+ raise ValueError(f"question {name!r}: threshold must be a finite number, got {threshold!r}")
190
+ for k, v in (("min", min), ("max", max)):
191
+ if v is not None:
192
+ try:
193
+ int(v) # keep the legacy coercion, but reject bad bounds before inference
194
+ except (TypeError, ValueError, OverflowError):
195
+ raise ValueError(f"question {name!r}: {k} must convert to an integer, got {v!r}") from None
196
+ return
197
+ if threshold is not None:
198
+ raise ValueError(f"question {name!r}: threshold applies only to objective \"threshold\"")
199
+ for k, v in (("min", min), ("max", max)):
200
+ if v is not None and (isinstance(v, bool) or not isinstance(v, int) or v < 0):
201
+ raise ValueError(f"question {name!r}: {k} must be a non-negative integer, got {v!r}")
202
+ if min is not None and min > n:
203
+ raise ValueError(f"question {name!r}: min {min} is more than the {n} labels")
204
+ if min is not None and max is not None and min > max:
205
+ raise ValueError(f"question {name!r}: min {min} > max {max}")
206
+
207
+
208
+ def label_set_id(keys, labels, fallback):
209
+ """Stable id of a label set with its fallback (the key of calibration file 2's `multi` section): a hash of the
210
+ sorted (key, label text) pairs and the fallback key, so a fitted fallback_threshold applies only to the same
211
+ labels."""
212
+ pairs = sorted([str(k), str(t)] for k, t in zip(keys, labels))
213
+ blob = json.dumps([pairs, fallback], ensure_ascii=False, separators=(",", ":"))
214
+ return hashlib.sha256(blob.encode()).hexdigest()[:16]
basal/signals.py ADDED
@@ -0,0 +1,28 @@
1
+ """SIGTERM that runs the exit handlers and still ends the process as a SIGTERM: for the entry point of a command."""
2
+ import atexit
3
+ import os
4
+ import signal
5
+ import threading
6
+
7
+
8
+ def _terminate(signum, frame):
9
+ """The exit handlers (a child process started with atexit.register(close), a temporary directory removed by atexit)
10
+ get their turn; then the default action returns and the signal is sent again, so the process ends the way an
11
+ unhandled SIGTERM ends it: status -15 for its parent, which is what systemd, docker and a shell wait for."""
12
+ try:
13
+ atexit._run_exitfuncs()
14
+ finally:
15
+ signal.signal(signum, signal.SIG_DFL)
16
+ os.kill(os.getpid(), signum)
17
+
18
+
19
+ def exit_on_sigterm():
20
+ """Python's default SIGTERM ends the process at once: no atexit handler runs, so a child process started with
21
+ atexit.register(close) or a temporary directory removed by atexit outlives a `kill` / `docker stop` / `systemctl
22
+ stop`. Called from the entry point of a command (basal-serve), never from a function of the library: a program
23
+ that uses basal as a library keeps its own signal handling. A handler somebody installed already stays; only the
24
+ main thread can install one."""
25
+ if threading.current_thread() is not threading.main_thread() or not hasattr(signal, "SIGTERM"):
26
+ return
27
+ if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
28
+ signal.signal(signal.SIGTERM, _terminate)