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/decisions.py ADDED
@@ -0,0 +1,158 @@
1
+ """POST /v1/decisions: OpenAI's Decisions API over basal-serve's own decisions (the OpenAI Python SDK's
2
+ client.decisions.create works against it).
3
+
4
+ A request becomes the System One request it stands for and is decided like POST /v1/systemone, so both endpoints
5
+ give the same probabilities for the same questions:
6
+
7
+ input the state: the text, or the list of messages / items as JSON (images are refused)
8
+ predicate noul: the probability that the statement is true
9
+ choice choice with the options {value: description} (a boolean value is shown as true / false); the answer's
10
+ choice and probabilities carry the typed values back, in the order of the choices
11
+ score score with the levels "label" or "label: description", lowest first; probabilities per level index
12
+ name kept on the answer (null when the question has none); answers come in question order
13
+
14
+ Errors have OpenAI's shape {"error": {"message", "type", "param", "code"}}: HTTP 400 invalid_request_error for a
15
+ request to change, 5xx server_error otherwise.
16
+ """
17
+ import json
18
+
19
+ from .prompt import RequestError
20
+
21
+ MAX_QUESTIONS = 400 # the Decisions API's limit
22
+
23
+
24
+ class DecisionsError(RequestError):
25
+ """An invalid /v1/decisions request; `param` names the field (OpenAI's error "param"); decision_rules_code: a
26
+ decision_rule this endpoint does not take (OpenAI's error "code")."""
27
+
28
+ def __init__(self, message, param=None, decision_rules_code=None):
29
+ super().__init__(message)
30
+ self.param = param
31
+ self.decision_rules_code = decision_rules_code
32
+
33
+
34
+ def _value_key(value):
35
+ """A choice value as a System One key: the string itself, a boolean as "true" / "false"."""
36
+ return json.dumps(value) if isinstance(value, bool) else value
37
+
38
+
39
+ def _has_image(x):
40
+ """An input_image part anywhere in x (a walk, not a recursion: an input nested a few hundred levels deep, valid
41
+ JSON, raised RecursionError, an HTTP 500)."""
42
+ todo = [x]
43
+ while todo:
44
+ x = todo.pop()
45
+ if isinstance(x, dict):
46
+ if x.get("type") == "input_image":
47
+ return True
48
+ todo += x.values()
49
+ elif isinstance(x, list):
50
+ todo += x
51
+ return False
52
+
53
+
54
+ def _parts(x, where):
55
+ """Instructions or input: text, or a list of parts / items; image parts are refused."""
56
+ if isinstance(x, str):
57
+ return x
58
+ if not isinstance(x, list) or not x:
59
+ raise DecisionsError("must be a string or a non-empty array", where)
60
+ if _has_image(x):
61
+ raise DecisionsError("images are not supported by this server", where)
62
+ return x
63
+
64
+
65
+ def to_systemone(body):
66
+ """A /v1/decisions body -> (the System One body, [(question name, kind, typed values or level labels)])."""
67
+ if not isinstance(body, dict):
68
+ raise DecisionsError("the request body must be a JSON object")
69
+ if "input" not in body:
70
+ raise DecisionsError("missing required parameter: 'input'", "input")
71
+ if "model" in body and not isinstance(body["model"], str):
72
+ raise DecisionsError("'model' must be a string", "model")
73
+ state = _parts(body["input"], "input")
74
+ qs = body.get("questions")
75
+ if not isinstance(qs, list) or not 1 <= len(qs) <= MAX_QUESTIONS:
76
+ raise DecisionsError(f"'questions' must be an array of 1 to {MAX_QUESTIONS} questions", "questions")
77
+ questions, specs = {}, []
78
+ for i, q in enumerate(qs):
79
+ where = f"questions[{i}]"
80
+ if not isinstance(q, dict):
81
+ raise DecisionsError("a question must be an object", where)
82
+ name = q.get("name")
83
+ if name is not None and not isinstance(name, str):
84
+ raise DecisionsError("'name' must be a string", f"{where}.name")
85
+ if "instructions" not in q:
86
+ raise DecisionsError("missing required parameter: 'instructions'", f"{where}.instructions")
87
+ if "decision_rule" in q: # (its answers carry no "decision": the selector would be dropped unseen)
88
+ raise DecisionsError("decision rules are not available on /v1/decisions: send the question to "
89
+ "/v1/systemone or /v1/basal", f"{where}.decision_rule", "unsupported_endpoint")
90
+ instr, kind = _parts(q["instructions"], f"{where}.instructions"), q.get("type")
91
+ if kind == "predicate":
92
+ questions[where] = {"type": "noul", "instructions": instr}
93
+ specs.append((name, kind, None))
94
+ elif kind == "choice":
95
+ choices = q.get("choices")
96
+ if not isinstance(choices, list) or not 2 <= len(choices) <= 255:
97
+ raise DecisionsError("'choices' must be an array of 2 to 255 choices", f"{where}.choices")
98
+ crit, values = {}, []
99
+ for j, c in enumerate(choices):
100
+ at = f"{where}.choices[{j}]"
101
+ if not isinstance(c, dict) or not isinstance(c.get("value"), (str, bool)):
102
+ raise DecisionsError("a choice needs a string or boolean 'value'", at)
103
+ if not isinstance(c.get("description", ""), str):
104
+ raise DecisionsError("'description' must be a string", f"{at}.description")
105
+ key = _value_key(c["value"])
106
+ if key in crit:
107
+ raise DecisionsError(f"choice values must be unique (as text): {key!r}", at)
108
+ crit[key] = c.get("description")
109
+ values.append(c["value"])
110
+ questions[where] = {"type": "choice", "instructions": instr, "criteria": crit}
111
+ specs.append((name, kind, values))
112
+ elif kind == "score":
113
+ levels = q.get("levels")
114
+ if not isinstance(levels, list) or not 2 <= len(levels) <= 255:
115
+ raise DecisionsError("'levels' must be an array of 2 to 255 levels", f"{where}.levels")
116
+ for j, lv in enumerate(levels):
117
+ if not isinstance(lv, dict) or not isinstance(lv.get("label"), str) \
118
+ or not isinstance(lv.get("description", ""), str):
119
+ raise DecisionsError("a level needs a string 'label' (and an optional string 'description')",
120
+ f"{where}.levels[{j}]")
121
+ texts = [lv["label"] if lv.get("description") is None else f"{lv['label']}: {lv['description']}"
122
+ for lv in levels]
123
+ questions[where] = {"type": "score", "instructions": instr, "criteria": texts}
124
+ specs.append((name, kind, [lv["label"] for lv in levels]))
125
+ else:
126
+ raise DecisionsError("'type' must be one of: predicate, choice, score", f"{where}.type")
127
+ return {"state": state, "questions": questions}, specs
128
+
129
+
130
+ def to_decision(out, specs):
131
+ """basal-serve's System One response -> the Decision object (answers in question order)."""
132
+ answers = []
133
+ for i, (name, kind, extra) in enumerate(specs):
134
+ a = out["answers"][f"questions[{i}]"]
135
+ if kind == "predicate":
136
+ answers.append({"type": "predicate", "name": name, "probability": a["noul"]})
137
+ elif kind == "choice":
138
+ p = a["probabilities"]
139
+ by_key = {_value_key(v): v for v in extra}
140
+ answers.append({"type": "choice", "name": name, "choice": by_key[a["choice"]],
141
+ "confidence": a["confidence"],
142
+ "probabilities": [{"value": v, "probability": p[_value_key(v)]} for v in extra]})
143
+ else:
144
+ p = a["probabilities"]
145
+ answers.append({"type": "score", "name": name, "score": a["score"], "confidence": a["confidence"],
146
+ "probabilities": [{"label": lab, "probability": p[str(k)], "value": k}
147
+ for k, lab in enumerate(extra)]})
148
+ n = int(out.get("usage", {}).get("input_tokens", 0))
149
+ return {"model": out.get("model"), "answers": answers,
150
+ "usage": {"input_tokens": n, "input_tokens_details": {"cache_write_tokens": 0, "cached_tokens": 0},
151
+ "output_tokens": 0, "output_tokens_details": {"reasoning_tokens": 0}, "total_tokens": n}}
152
+
153
+
154
+ def error_body(e, status):
155
+ """OpenAI's error object for a failed /v1/decisions request with this HTTP status."""
156
+ kind = "invalid_request_error" if status < 500 else "server_error"
157
+ code = getattr(e, "decision_rules_code", None) if status < 500 else None
158
+ return {"error": {"message": str(e), "type": kind, "param": getattr(e, "param", None), "code": code}}
basal/derive.py ADDED
@@ -0,0 +1,98 @@
1
+ """What a model derived from a basal model keeps of its source's folder, and which models a derivation that reads with
2
+ the plain causal forward refuses: one rule set for basal-finetune (a merged LoRA), basal-fuse-adapter (and the merged
3
+ copy --adapter makes for vLLM / SGLang), basal-interpolate and basal-export-gguf --systemone.
4
+
5
+ - FITTED: what was measured or trained on the source weights' activations and hidden states: the NVFP4 activation
6
+ scales, the evidence head, the early-exit heads and the thinking folder (its LoRA adapter was trained on the source
7
+ weights). A model with other weights never takes them over (basal-serve refuses the first three under --adapter for
8
+ the same reason).
9
+ - CALIBRATIONS: fitted to the source's answers. basal-finetune and basal-fuse-adapter drop them (a fused model takes
10
+ the adapter's own, adapter.fused_calibration); basal-interpolate keeps --meta-from's as a starting point
11
+ (docs/INTERPOLATION.md: fit one per merged model).
12
+ - DESCRIBES: the source checkpoint's model card, manifest and checksums.
13
+ - reading_refused: a model read two-way, with its state prefix both ways or with isolated options (basal.json
14
+ "two_way" / "prefix_bidir", a dual model's "dual" / "option_isolation") is served by the engine's own Gemma 4
15
+ forward only; a tool that reads it with the plain causal forward, one prompt per
16
+ question (fine-tuning, llama.cpp's decision template), would train or describe another reading than the served one.
17
+ - modelopt_refused: a ModelOpt checkpoint (the -FP8 and -NVFP4 repositories) keeps its quantised weights' scales
18
+ in tensors of their own, which transformers 5.17 and the safetensors readers of these tools do not apply: a LoRA
19
+ trained on it, an adapter fused into it, a GGUF converted from it or an interpolation of it would take the FP8
20
+ values for the weights. These tools refuse it before any weights are read, naming its bf16 model
21
+ (basal-fold-temperature folds into the final norm, which ModelOpt keeps in bf16, and copies the rest as it is: it
22
+ reads such a checkpoint).
23
+
24
+ The single readers these tools share live beside: adapter.read (LoRA files in any floating dtype, bf16 included) and
25
+ gemma4_graph.load_nvfp4_amax (NVFP4_AMAX.json, wrapped or plain).
26
+ """
27
+ import json
28
+ import re
29
+ from fnmatch import fnmatch
30
+ from pathlib import Path, PurePath
31
+
32
+ from .prompt import model_option_isolation, model_prefix_bidir, model_two_way
33
+
34
+ # names (fnmatch patterns) of the files and folders at the top of a model folder in each group
35
+ FITTED = ("NVFP4_AMAX.json", "evidence_head.pt", "exit_heads", "think")
36
+ CALIBRATIONS = ("CALIBRATION*",)
37
+ DESCRIBES = ("README.md", "MANIFEST.md", "SHA256SUMS")
38
+
39
+
40
+ def stale(rel, calibrations=True):
41
+ """True for a path of the source folder (relative to it) that a model with other weights does not take over: under
42
+ a FITTED or DESCRIBES name, or a CALIBRATIONS one unless calibrations=False (basal-interpolate keeps those)."""
43
+ top = PurePath(rel).parts[0]
44
+ return any(fnmatch(top, p) for p in FITTED + DESCRIBES + (CALIBRATIONS if calibrations else ()))
45
+
46
+
47
+ def reading_refused(model_dir):
48
+ """Why a model cannot be read with the plain causal forward, one prompt per question (None: it can)."""
49
+ if model_two_way(model_dir):
50
+ return "it is read two-way (basal.json \"two_way\")"
51
+ if model_option_isolation(model_dir):
52
+ return "its options are read in isolated blocks (basal.json \"option_isolation\")"
53
+ if model_prefix_bidir(model_dir): # (a dual model's: in "dual".modes.prefix_header)
54
+ return "its state prefix is read both ways (basal.json \"prefix_bidir\")"
55
+ return None
56
+
57
+
58
+ _QUANTISED = re.compile(r"^(.+?)-(FP8|NVFP4)$", re.IGNORECASE)
59
+
60
+
61
+ def bf16_name(given, model_dir=None):
62
+ """The bf16 model a ModelOpt checkpoint holds the weights of, by basal's names (Remek/basal-omni-1.0-mini-FP8 is
63
+ Remek/basal-omni-1.0-mini quantised): the repository as given, else the Hugging Face cache folder the checkpoint
64
+ is in (models--Remek--<name>/snapshots/<revision>), its basal.json "name" or its folder's name, each without its
65
+ -FP8 / -NVFP4; None where none of them has one."""
66
+ names = [] if Path(str(given)).exists() else [str(given)]
67
+ if model_dir is not None:
68
+ p = Path(model_dir).absolute()
69
+ for part in reversed(p.parts):
70
+ if part.startswith("models--") and part.count("--") >= 2:
71
+ names.append("/".join(part.split("--")[1:]))
72
+ break
73
+ try:
74
+ name = json.loads((p / "basal.json").read_text(encoding="utf-8")).get("name")
75
+ except (OSError, ValueError, AttributeError):
76
+ name = None
77
+ if isinstance(name, str):
78
+ names.append(name)
79
+ names.append(p.name)
80
+ for n in names:
81
+ m = _QUANTISED.match(n.rstrip("/"))
82
+ if m:
83
+ return m.group(1)
84
+ return None
85
+
86
+
87
+ def modelopt_refused(model_dir, given, tool, doing):
88
+ """Why `tool` refuses the model at model_dir (given: as it was named) as a ModelOpt checkpoint, read from its
89
+ metadata before any weights load (doing: what the tool would do with its weights, "train a LoRA on", ...); None
90
+ for any other model."""
91
+ from .engine import modelopt_algo
92
+ algo = modelopt_algo(model_dir)
93
+ if algo is None:
94
+ return None
95
+ base = bf16_name(given, model_dir)
96
+ return (f"{tool}: {given} is a ModelOpt {algo} checkpoint: its {algo} weights keep their scales in tensors of their "
97
+ f"own, which {tool} does not apply, so it would {doing} the {algo} values as if they were the weights. "
98
+ f"Use its bf16 model{f' ({base})' if base else ''} instead")
basal/disconnect.py ADDED
@@ -0,0 +1,85 @@
1
+ """A request whose HTTP client disconnects is cancelled (basal-serve, basal-router, /mcp): uvicorn does not cancel a
2
+ handler when its client goes away, so without this its work ran in full for nobody. No torch here: basal-router
3
+ imports this module alone, as it does basal.metrics."""
4
+ import asyncio
5
+ import json
6
+
7
+ CLIENT_GONE = ({"error": "client disconnected", "code": "CLIENT_DISCONNECTED"}, 499) # (nobody reads it)
8
+
9
+
10
+ async def until_disconnect(request, coro):
11
+ """The result of `coro` (the request's serve), or None when the HTTP client disconnects first. The serve task is
12
+ then cancelled, so the request's entries still in the queue are dropped before they reach the engine (ask cancels
13
+ their futures, the workers skip done futures); a batch already on the GPU finishes. Without it a client that timed
14
+ out left its request to run in full: 48 abandoned 6k-token requests kept the GPU busy for 74 s (#129).
15
+ The disconnect is the server's http.disconnect message, awaited by a task of its own (the handler has read the
16
+ body, so nothing else receives): a waiting request costs the event loop nothing and is cancelled at once, where
17
+ polling is_disconnected() every 0.25 s cost 15% of a core with 1,024 requests waiting. A serve that has ended
18
+ answers as it ended (its error raised, not lost); a cancelled handler cancels its serve too."""
19
+ task = asyncio.ensure_future(coro)
20
+ gone = asyncio.ensure_future(_disconnected(request.receive))
21
+ try:
22
+ await asyncio.wait({task, gone}, return_when=asyncio.FIRST_COMPLETED)
23
+ finally:
24
+ gone.cancel()
25
+ task.cancel() # (nothing once it has ended) the client is gone, or this handler was cancelled
26
+ await asyncio.wait({task}) # the serve's own clean-up first: ask drops the request's queued entries
27
+ return None if task.cancelled() else task.result()
28
+
29
+
30
+ async def _disconnected(receive):
31
+ """Returns when the server says the request's client is gone (http.disconnect). A receive that fails says
32
+ nothing: the request is then served to the end, as without the watch."""
33
+ try:
34
+ while (await receive())["type"] != "http.disconnect":
35
+ pass
36
+ except Exception: # noqa: BLE001
37
+ await asyncio.get_running_loop().create_future() # (never set: cancelled when the serve ends)
38
+
39
+
40
+ class CancelOnDisconnect:
41
+ """An ASGI app that reads its own request (the MCP endpoint), cancelled when its client disconnects before its
42
+ response is complete: the server's messages reach it through a task of ours, which sees the http.disconnect.
43
+ A stateless MCP request's session ends with its handler, and the tool call with it. When no response has started,
44
+ the 499 of a request whose client left is sent (nobody reads it)."""
45
+
46
+ def __init__(self, app):
47
+ self.app = app
48
+
49
+ async def __call__(self, scope, receive, send):
50
+ if scope["type"] != "http":
51
+ await self.app(scope, receive, send)
52
+ return
53
+ inbox, state = asyncio.Queue(), {"started": False, "complete": False}
54
+
55
+ async def sent(message):
56
+ if message["type"] == "http.response.start":
57
+ state["started"] = True
58
+ elif message["type"] == "http.response.body" and not message.get("more_body", False):
59
+ state["complete"] = True # (the server's http.disconnect after it says nothing about the client)
60
+ await send(message)
61
+
62
+ task = asyncio.ensure_future(self.app(scope, inbox.get, sent))
63
+
64
+ async def relay():
65
+ while True:
66
+ message = await receive()
67
+ inbox.put_nowait(message)
68
+ if message["type"] == "http.disconnect":
69
+ if not state["complete"]:
70
+ task.cancel()
71
+ return
72
+
73
+ pump = asyncio.ensure_future(relay())
74
+ try:
75
+ await asyncio.wait({task})
76
+ finally:
77
+ pump.cancel()
78
+ task.cancel() # (nothing once it has ended) or this handler was cancelled
79
+ if not task.cancelled():
80
+ task.result()
81
+ elif not state["started"]:
82
+ body, status = CLIENT_GONE
83
+ await send({"type": "http.response.start", "status": status,
84
+ "headers": [(b"content-type", b"application/json")]})
85
+ await send({"type": "http.response.body", "body": json.dumps(body).encode()})