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
@@ -0,0 +1,569 @@
1
+ """Decision rules (experimental): how a plain noul or score answer's probabilities become one decision, fitted per
2
+ answer space by basal-fit-decisions on labelled requests and served by basal-serve to the questions that ask for one.
3
+
4
+ A rule decides from the served probabilities (after option orders and temperature); the answer keeps every field it
5
+ had and gains a "decision" block (apply). Pure Python, no torch: basal-serve, basal-router and basal-fit-decisions all
6
+ read it.
7
+
8
+ rules = load("RULES.json") # DecisionRulesError(code="invalid_file") on any problem
9
+ rules.check_signature(inference_signature(entry)) # entry: the server's GET /v1/models entry
10
+ cond = request_conditions(body, entry.get("early_exit_default")) # the request's facts / early_exit / media
11
+ rule = resolve(rules, "refund-late", item, cond) # item: one server.to_items() item
12
+ decision = apply(rule, item, probs) # probs: {key: probability} of the item's keys
13
+
14
+ Methods (the rule's "method"):
15
+ baseline the answer the model's certificates cover (noul: "true" iff P(true) >= P(false), as answer_id; score: the
16
+ most probable level, the first in key order on a tie): what a fitted rule falls back to when its fit was
17
+ refused. certification "map".
18
+ argmax the same decision, chosen for a score space by its fit (and by builtin:argmax-v1 for both types, which
19
+ needs no file: noul's threshold 0.5 with answer_id's tie rule). certification "map".
20
+ threshold noul: "true" iff P(true) >= t. certification "none" (no certificate covers another threshold).
21
+ round score: the expected level mu = sum(i * p_i) rounded half up, clip(floor(mu + 0.5), 0, K - 1), both in
22
+ exact arithmetic (expected_level, round_level). certification "none".
23
+
24
+ The rules file (format basal.decision_rules/1, written by basal-fit-decisions):
25
+ {"format": "basal.decision_rules/1", "id": "...", "experimental": true, "created": "...", "basal_version": "...",
26
+ "inference_signature": {...}, "metric": "accuracy",
27
+ "rules": {"<rule_id>": {"answer_space": "<rule_id>", "type": "noul" | "score", "schema_hash": "<sha256 hex>",
28
+ "method": "...", "parameters": {"threshold": t} | {},
29
+ "request": {"facts": "off" | "auto", "early_exit": "<policy>" | null, "media": false},
30
+ "fit": {...}}},
31
+ "provenance": {...}}
32
+ A rule applies only to the exact question it was fitted on (schema_hash: type, language, instructions, keys, options
33
+ and option_keys), only to requests like those it was fitted on (request: their facts mode, effective early-exit policy
34
+ and media; request_conditions) and only on a server whose inference signature (inference_signature) is the file's.
35
+ """
36
+ import hashlib
37
+ import json
38
+ import math
39
+ import sys
40
+ from dataclasses import dataclass, field
41
+ from fractions import Fraction
42
+ from pathlib import Path
43
+ from types import MappingProxyType
44
+
45
+ FORMAT = "basal.decision_rules/1"
46
+ BUILTIN_ARGMAX = "builtin:argmax-v1"
47
+ BUILTIN_PREFIX = "builtin:" # rule ids a file may not define
48
+ TYPES = ("noul", "score") # the question types a rule applies to
49
+ METHODS = {"noul": ("baseline", "threshold"), "score": ("baseline", "argmax", "round")}
50
+ MAP_METHODS = ("baseline", "argmax") # the decision answer_id gives, which the calibration's certificates cover
51
+ CODES = ("no_rules", "unknown_rule", "schema_mismatch", "unsupported_type", "request_mismatch", "signature_mismatch",
52
+ "unsupported_backend", "invalid_file")
53
+ # --mode values whose weights run in another server behind an address (--ollama-url / --llamacpp-url): the same
54
+ # address can serve other weights under the same signature, so no rules file applies there (builtin:argmax-v1 does)
55
+ REMOTE_MODES = ("ollama", "llamacpp")
56
+ # signature fields that identify a file by its content: null, or a digest (lowercase hex, 16 to 64 digits), never a
57
+ # path, which can hold other contents
58
+ DIGEST_FIELDS = ("gguf", "nvfp4_amax", "exit_heads")
59
+ SCHEMA_VERSION = 1 # schema_hash's "v"
60
+
61
+ # The fields of a GET /v1/models entry that change the probabilities a server serves a request with (the
62
+ # inference_signature). A field the entry does not have is null in the signature, so the server and
63
+ # basal-fit-decisions --url, reading the same entry, get the same signature. Each holds the value the server runs with
64
+ # (resolved where the server resolves it); a file's identity is a digest of its content
65
+ SIGNATURE_FIELDS = (
66
+ "engine_version", # basal's version
67
+ # the model: its files (model_content, sampled per file; model_weights, every safetensors tensor sampled), adapter,
68
+ # GGUF file, Ollama model
69
+ "model_content", "model_weights", "revision", "model_files", "adapter", "gguf", "ollama_model",
70
+ # the engine and its numerics
71
+ "mode", "quant", "dtype", "device", "vllm_preset", "vllm_fast_prefill",
72
+ "eager_forward", "eager_attn", "mlx_packed", "mlx_forward", "mlx_compute",
73
+ "attn", "gemma_attn", "global_attn", "merge", "lean", "llama_graph", "compile_scope", "tree", "batches", "readout_layer",
74
+ "template_prefix", "prefix_cache", "state_cache_bits", "state_cache_match", "long_lane",
75
+ "fp8_scaling", "fp8_bf16_layers", "fp8_accum", "nvfp4_amax", "nvfp4_scope",
76
+ "varloop_passes", "varloop_exit_tau",
77
+ # how a request is read
78
+ "prompt_format", "layout", "option_isolation", "soam", "dual_reading", "media", "context",
79
+ "orders", "orders_auto", "reread", "early_exit", "early_exit_default", "exit_heads", "think",
80
+ # the calibration
81
+ "temperature_per_prim", "temperature_per_bucket", "calibration_sha256", "prefix_calibration_sha256",
82
+ )
83
+ # Every basal-serve option -> the signature field that carries it (SERVE_OPTIONS), or why it changes no probability
84
+ # a request is served with (NOT_IN_SIGNATURE). Every option of basal-serve is in exactly one of them (a test checks
85
+ # its parser). Load (which requests share a forward, when they run, whether a state is cached from an earlier
86
+ # request) is left out: its noise is the noise of serving under load, which --deterministic removes, and the rules
87
+ # file records whether the fit was collected with it
88
+ SERVE_OPTIONS = {
89
+ "model": "model_content", "revision": "revision", "adapter": "adapter", "gguf": "gguf",
90
+ "ollama_model": "ollama_model", "mode": "mode", "quant": "quant", "dtype": "dtype", "device": "device",
91
+ "vllm_preset": "vllm_preset", "vllm_fast_prefill": "vllm_fast_prefill", "eager_forward": "eager_forward",
92
+ "eager_attn": "eager_attn", "mlx_packed": "mlx_packed", "mlx_forward": "mlx_forward",
93
+ "mlx_compute": "mlx_compute", "attn": "attn", "gemma_attn": "gemma_attn", "global_attn": "global_attn",
94
+ "merge": "merge", "lean": "lean", "llama_graph": "llama_graph", "compile_scope": "compile_scope", "tree": "tree", "batches": "batches",
95
+ "readout_layer": "readout_layer", "template_prefix": "template_prefix", "prefix_cache": "prefix_cache",
96
+ "state_cache_match": "state_cache_match", "state_cache_bits": "state_cache_bits", "long_lane": "long_lane", "long_lane_gdn": "long_lane",
97
+ "long_tokens": "long_lane", "fp8_scaling": "fp8_scaling", "fp8_bf16_layers": "fp8_bf16_layers",
98
+ "fp8_accum": "fp8_accum", "nvfp4_amax": "nvfp4_amax", "nvfp4_scope": "nvfp4_scope", "layout": "layout",
99
+ "soam": "soam", "dual_reading": "dual_reading", "media": "media", "max_len": "context",
100
+ "context_overflow": "context", "truncate_head": "context", "orders": "orders", "order_average": "orders",
101
+ "auto_tau": "orders_auto", "auto_band": "orders_auto", "reread": "reread", "reread_combine": "reread",
102
+ "reread_max_tokens": "reread", "reread_image": "reread", "early_exit": "early_exit_default",
103
+ "exit_heads": "exit_heads", "think": "think", "think_tokens": "think", "think_calibration": "think",
104
+ "think_model": "think", "think_adapter": "think", "think_max_len": "think",
105
+ "calibration": "calibration_sha256", "no_calibration": "calibration_sha256",
106
+ "varloop_passes": "varloop_passes", "varloop_exit_tau": "varloop_exit_tau",
107
+ }
108
+ _LOAD = "load: which requests share a forward or when they run (the noise --deterministic removes)"
109
+ _CACHED = "load: whether a state was cached by an earlier request"
110
+ _ADDRESS = "an address or a process setting of a server it talks to"
111
+ _NOT_COMPUTED = "what the server admits, reports, logs or exposes, not what it computes"
112
+ NOT_IN_SIGNATURE = {
113
+ "require_graph_shapes": "startup guard on the resolved graph set; an accepted execution is unchanged",
114
+ "deterministic": _LOAD, "lanes": _LOAD, "max_batch": _LOAD, "wait_ms": _LOAD, "batch_window_ms": _LOAD,
115
+ "http_parallel": _LOAD, "gpu_memory": _LOAD, "vllm_overlap": _LOAD, "scheduler": _LOAD, "long_share": _LOAD,
116
+ "long_slice_ms": _LOAD,
117
+ "state_cache_gb": _CACHED, "state_cache_lock": _CACHED, "state_cache_dir": _CACHED,
118
+ "state_cache_disk_gb": _CACHED,
119
+ "ple_offload": "the same embedding rows, copied from host memory",
120
+ "quant_load": "the same weights, quantised from host memory",
121
+ "graph_memory_gb": "graph shapes (this value, else resolved from the GPU's free memory), like the GPU model and "
122
+ "batching under load: numeric noise the rules tolerate; the rules file's provenance records the "
123
+ "resolved shapes and the GPU (serving_numerics) and basal-fit-decisions evaluate warns when "
124
+ "they differ",
125
+ "prepared": "the compiled kernels of an earlier start",
126
+ "fp8_experimental": "allows --mode fp8 for a model shape; the computation is the mode's",
127
+ "strict_calibration": "refuses a calibration at start; the temperatures served are in the signature",
128
+ "decision_rules": "the rules a question may select; every probability is served as without them",
129
+ "ollama_url": _ADDRESS, "llamacpp_url": _ADDRESS, "think_url": _ADDRESS, "think_python": _ADDRESS,
130
+ "think_memory": _ADDRESS, "think_log": _ADDRESS,
131
+ "name": _NOT_COMPUTED, "log_decisions": _NOT_COMPUTED, "log_requests": _NOT_COMPUTED,
132
+ "review_sample": _NOT_COMPUTED, "review_secret": _NOT_COMPUTED,
133
+ "response_cache_mb": "returns an earlier response to the same request",
134
+ "response_cache_ttl": "returns an earlier response to the same request",
135
+ "chat_classify": _NOT_COMPUTED, "max_body_mb": _NOT_COMPUTED, "max_branches": _NOT_COMPUTED,
136
+ "max_requests": _NOT_COMPUTED, "max_prompt_mb": _NOT_COMPUTED, "request_timeout": _NOT_COMPUTED,
137
+ "stall_s": _NOT_COMPUTED, "stall_exit": _NOT_COMPUTED, "rank_max_candidates": "rank questions only",
138
+ "api_keys": _NOT_COMPUTED, "cors_origins": _NOT_COMPUTED, "allowed_hosts": _NOT_COMPUTED, "host": _NOT_COMPUTED,
139
+ "port": _NOT_COMPUTED, "error_format": _NOT_COMPUTED, "mcp": _NOT_COMPUTED, "mcp_tree": _NOT_COMPUTED,
140
+ "mcp_navigate": _NOT_COMPUTED, "ui": _NOT_COMPUTED,
141
+ }
142
+ FILE_KEYS = ("format", "id", "experimental", "created", "basal_version", "inference_signature", "metric", "rules",
143
+ "provenance")
144
+ RULE_KEYS = ("answer_space", "type", "schema_hash", "method", "parameters", "request", "fit")
145
+ REQUEST_FIELDS = ("facts", "early_exit", "media") # a rule's request conditions (request_conditions)
146
+ FACTS = ("off", "auto")
147
+ MAX_ID = 200 # characters of a file id or a rule id
148
+
149
+
150
+ class DecisionRulesError(ValueError):
151
+ """A decision rule that cannot be loaded or applied; .code names why (CODES): basal-serve answers a request's
152
+ no_rules / unknown_rule / schema_mismatch / unsupported_type / request_mismatch with HTTP 422 and refuses a file
153
+ with invalid_file, signature_mismatch or unsupported_backend (a server whose weights it cannot identify) at
154
+ start. .fields: the fields that differ (signature_mismatch: of the signature; request_mismatch: of the request
155
+ conditions), else ()."""
156
+
157
+ def __init__(self, code, message, fields=()):
158
+ if code not in CODES:
159
+ raise ValueError(f"unknown decision rules error code {code!r}")
160
+ super().__init__(message)
161
+ self.code, self.fields = code, tuple(fields)
162
+
163
+
164
+ def _canonical(obj):
165
+ """The canonical JSON of obj: sorted keys, ensure_ascii=False, separators (",", ":"); no NaN or infinity."""
166
+ return json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
167
+
168
+
169
+ def schema_hash(item):
170
+ """The sha256 hex of a question's schema: one server.to_items() item's type, effective language, instructions (its
171
+ text as read), keys, option texts and option_keys. The state, the question's name and its gold do not enter it."""
172
+ payload = {"v": SCHEMA_VERSION, "type": item["type"], "lang": item["lang"], "instructions": item["question"],
173
+ "keys": list(item["keys"]), "options": list(item["options"]), "option_keys": item.get("option_keys")}
174
+ return hashlib.sha256(_canonical(payload).encode("utf-8")).hexdigest()
175
+
176
+
177
+ def inference_signature(model_entry):
178
+ """The fields of one GET /v1/models entry that change the probabilities it serves (SIGNATURE_FIELDS) -> {field:
179
+ value}, a field the entry lacks as null; the values as JSON reads them back (tuples as lists)."""
180
+ if not isinstance(model_entry, dict):
181
+ raise ValueError(f"a GET /v1/models entry is a JSON object, not {type(model_entry).__name__}")
182
+ return {k: json.loads(_canonical(model_entry.get(k))) for k in SIGNATURE_FIELDS}
183
+
184
+
185
+ def request_conditions(body, early_exit_default=None):
186
+ """What a decision request (its body) sets that changes its probabilities beyond the server's signature -> {"facts":
187
+ "off" | "auto", "early_exit": its effective early-exit policy (its "early_exit" as text, else the server's default
188
+ early_exit_default, the GET /v1/models entry's) or null, "media": whether it has media ("media" or "images")}. A
189
+ rule applies only to requests whose conditions are the ones it was fitted on (Rule.request)."""
190
+ ee = body.get("early_exit")
191
+ return {"facts": "auto" if body.get("facts") == "auto" else "off",
192
+ "early_exit": early_exit_default if ee is None else str(ee),
193
+ "media": body.get("media") is not None or body.get("images") is not None}
194
+
195
+
196
+ def _conditions_ok(c):
197
+ return isinstance(c, dict) and set(c) == set(REQUEST_FIELDS) and c["facts"] in FACTS \
198
+ and (c["early_exit"] is None or isinstance(c["early_exit"], str)) and isinstance(c["media"], bool)
199
+
200
+
201
+ def _short(v, n=80):
202
+ s = json.dumps(v, ensure_ascii=False, sort_keys=True)
203
+ return s if len(s) <= n else s[:n - 3] + "..."
204
+
205
+
206
+ def _is_digest(v):
207
+ return isinstance(v, str) and 16 <= len(v) <= 64 and all(c in "0123456789abcdef" for c in v)
208
+
209
+
210
+ def check_backend(sig):
211
+ """A signature whose weights are identified, else DecisionRulesError unsupported_backend: --mode ollama /
212
+ llamacpp (REMOTE_MODES: the weights of another server), --mode gguf without its file's content digest, or a file
213
+ field (DIGEST_FIELDS) that holds no content digest. builtin:argmax-v1 needs no file and so no such check."""
214
+ mode = sig.get("mode")
215
+ if mode in REMOTE_MODES:
216
+ raise DecisionRulesError("unsupported_backend", f"decision rules need weights the server identifies: --mode "
217
+ f"{mode} reads them from another server, whose address can "
218
+ "serve other weights under the same settings (the built-in "
219
+ f"{BUILTIN_ARGMAX!r} needs no rules file)")
220
+ if mode == "gguf" and sig.get("gguf") is None:
221
+ raise DecisionRulesError("unsupported_backend", "decision rules need the GGUF file identified by its content: "
222
+ "--mode gguf without a gguf content digest")
223
+ bad = [k for k in DIGEST_FIELDS if sig.get(k) is not None and not _is_digest(sig[k])]
224
+ if bad:
225
+ raise DecisionRulesError("unsupported_backend", "decision rules need files identified by their content: "
226
+ + ", ".join(f"{k} {_short(sig[k])}" for k in bad) + " is no content digest (a path "
227
+ "can hold other contents)")
228
+
229
+
230
+ def signature_diff(fitted, served):
231
+ """The fields whose values differ between two signatures (a field one of them lacks counts as null), sorted."""
232
+ keys = set(fitted) | set(served)
233
+ return sorted(k for k in keys if _canonical(fitted.get(k)) != _canonical(served.get(k)))
234
+
235
+
236
+ @dataclass(frozen=True)
237
+ class Rule:
238
+ """One rule: its id (the answer space it was fitted on; BUILTIN_ARGMAX for the builtin), the question type and
239
+ schema it applies to (None for the builtin: any noul or score question), its method and threshold (noul
240
+ "threshold" only), and the file it came from (None for the builtin)."""
241
+ rule_id: str
242
+ type: str | None
243
+ method: str
244
+ threshold: float | None = None
245
+ schema_hash: str | None = None
246
+ rules_id: str | None = None
247
+ rules_sha256: str | None = None
248
+ _request: str | None = field(default=None, repr=False) # (canonical JSON, as _fit; None: any request)
249
+ _fit: str = field(default="{}", repr=False) # (the fit block as canonical JSON: the rule stays immutable)
250
+
251
+ @property
252
+ def answer_space(self):
253
+ return None if self.rule_id == BUILTIN_ARGMAX else self.rule_id
254
+
255
+ @property
256
+ def parameters(self):
257
+ return {"threshold": self.threshold} if self.method == "threshold" else {}
258
+
259
+ @property
260
+ def fit(self):
261
+ """The rule's fit block (a copy)."""
262
+ return json.loads(self._fit)
263
+
264
+ @property
265
+ def request(self):
266
+ """The request conditions the rule was fitted under ({facts, early_exit, media}, a copy); None for the
267
+ builtin, which applies to any request."""
268
+ return None if self._request is None else json.loads(self._request)
269
+
270
+ @property
271
+ def certification(self):
272
+ """"map": the decision answer_id gives, which the calibration's certificates cover; "none": another one."""
273
+ return "map" if self.method in MAP_METHODS else "none"
274
+
275
+
276
+ BUILTIN = Rule(BUILTIN_ARGMAX, None, "argmax")
277
+
278
+
279
+ @dataclass(frozen=True)
280
+ class DecisionRules:
281
+ """A loaded rules file (load): its id, the sha256 of its bytes, the inference signature it was fitted with (a
282
+ copy per read) and its rules {rule_id: Rule} (read-only)."""
283
+ id: str
284
+ sha256: str
285
+ rules: MappingProxyType
286
+ _signature: str = field(repr=False)
287
+ _data: str = field(repr=False)
288
+
289
+ @property
290
+ def signature(self):
291
+ """The file's inference_signature (a copy)."""
292
+ return json.loads(self._signature)
293
+
294
+ @property
295
+ def data(self):
296
+ """The whole file as read (a copy)."""
297
+ return json.loads(self._data)
298
+
299
+ def describe(self):
300
+ """What GET /v1/models can show of the file: its id, sha256, format, created, basal_version, metric and per
301
+ rule the type, method, parameters and request conditions."""
302
+ d = self.data
303
+ return {"id": self.id, "sha256": self.sha256, "format": FORMAT, "experimental": True, "created": d["created"],
304
+ "basal_version": d["basal_version"], "metric": d["metric"],
305
+ "rules": {k: {"type": r.type, "method": r.method, "parameters": r.parameters, "request": r.request}
306
+ for k, r in self.rules.items()}}
307
+
308
+ def check_signature(self, sig):
309
+ """The server's inference signature (inference_signature of its GET /v1/models entry) against the file's:
310
+ DecisionRulesError unsupported_backend for a server whose weights it cannot identify (check_backend), else
311
+ signature_mismatch naming every field that differs."""
312
+ check_backend(sig)
313
+ fitted = self.signature
314
+ diff = signature_diff(fitted, sig)
315
+ if diff:
316
+ what = "; ".join(f"{k}: fitted {_short(fitted.get(k))}, served {_short(sig.get(k))}" for k in diff)
317
+ raise DecisionRulesError("signature_mismatch", f"decision rules {self.id!r} were fitted with another "
318
+ f"inference setup ({what}); fit them again on this server", fields=diff)
319
+
320
+
321
+ def _invalid(where, why):
322
+ return DecisionRulesError("invalid_file", f"{where}: {why}")
323
+
324
+
325
+ def _no_duplicates(pairs):
326
+ keys = [k for k, _ in pairs]
327
+ if len(set(keys)) != len(keys):
328
+ dup = next(k for k in keys if keys.count(k) > 1)
329
+ raise ValueError(f"duplicate key {dup!r}")
330
+ return dict(pairs)
331
+
332
+
333
+ def _no_constant(name):
334
+ raise ValueError(f"{name} is not JSON")
335
+
336
+
337
+ def _finite_float(text):
338
+ v = float(text)
339
+ if not math.isfinite(v):
340
+ raise ValueError(f"the number {text} is out of range (beyond a float's)")
341
+ return v
342
+
343
+
344
+ def _finite_int(text):
345
+ v = int(text)
346
+ if abs(v) > sys.float_info.max:
347
+ raise ValueError(f"the number {text[:20]}{'...' if len(text) > 20 else ''} is out of range (beyond a float's)")
348
+ return v
349
+
350
+
351
+ def _id_ok(v):
352
+ return isinstance(v, str) and 0 < len(v) <= MAX_ID and v == v.strip() and v.isprintable()
353
+
354
+
355
+ def _is_sha256(v):
356
+ return isinstance(v, str) and len(v) == 64 and all(c in "0123456789abcdef" for c in v)
357
+
358
+
359
+ def _rule(where, rule_id, entry, rules_id, rules_sha256):
360
+ """One entry of a file's "rules" -> Rule; invalid_file naming the problem."""
361
+ at = f"{where}: rule {rule_id!r}"
362
+ if not _id_ok(rule_id):
363
+ raise _invalid(where, f"rule id {rule_id!r}: a non-empty printable string of at most {MAX_ID} characters, "
364
+ "without spaces at its ends")
365
+ if rule_id.startswith(BUILTIN_PREFIX):
366
+ raise _invalid(where, f"rule id {rule_id!r}: ids starting with {BUILTIN_PREFIX!r} are the engine's own")
367
+ if not isinstance(entry, dict):
368
+ raise _invalid(at, "not an object")
369
+ keys = set(entry)
370
+ if keys != set(RULE_KEYS):
371
+ missing, extra = sorted(set(RULE_KEYS) - keys), sorted(keys - set(RULE_KEYS))
372
+ raise _invalid(at, "; ".join(x for x in (f"missing {', '.join(missing)}" if missing else "",
373
+ f"unknown {', '.join(extra)}" if extra else "") if x))
374
+ if entry["answer_space"] != rule_id:
375
+ raise _invalid(at, f"answer_space {entry['answer_space']!r} must be its rule id")
376
+ t = entry["type"]
377
+ if t not in TYPES:
378
+ raise _invalid(at, f"type {t!r} (decision rules apply to {' and '.join(TYPES)})")
379
+ if not _is_sha256(entry["schema_hash"]):
380
+ raise _invalid(at, "schema_hash must be a lowercase sha256 hex")
381
+ method, params = entry["method"], entry["parameters"]
382
+ if method not in METHODS[t]:
383
+ raise _invalid(at, f"method {method!r} (a {t} rule: {', '.join(METHODS[t])})")
384
+ if not isinstance(params, dict):
385
+ raise _invalid(at, "parameters must be an object")
386
+ threshold = None
387
+ if method == "threshold":
388
+ t_ = params.get("threshold")
389
+ if set(params) != {"threshold"} or isinstance(t_, bool) or not isinstance(t_, (int, float)) \
390
+ or not math.isfinite(t_) or not 0.0 <= t_ <= 1.0:
391
+ raise _invalid(at, 'parameters must be {"threshold": t} with 0 <= t <= 1')
392
+ threshold = float(t_)
393
+ elif params:
394
+ raise _invalid(at, f"parameters must be {{}} for method {method!r}")
395
+ req = entry["request"]
396
+ if not _conditions_ok(req) or req["media"] is not False:
397
+ raise _invalid(at, 'request must be {"facts": "off" | "auto", "early_exit": a policy name or null, "media": '
398
+ 'false} (rules for requests with media are not supported)')
399
+ if not isinstance(entry["fit"], dict):
400
+ raise _invalid(at, "fit must be an object")
401
+ return Rule(rule_id, t, method, threshold, entry["schema_hash"], rules_id, rules_sha256, _canonical(req),
402
+ _canonical(entry["fit"]))
403
+
404
+
405
+ def parse(raw, where="decision rules"):
406
+ """The bytes of a rules file -> DecisionRules, every field validated (invalid_file naming the first problem). A
407
+ number anywhere in the file must be one a float holds (no NaN, infinity or integer beyond a float's range)."""
408
+ digest = hashlib.sha256(raw).hexdigest()
409
+ try:
410
+ data = json.loads(raw.decode("utf-8"), object_pairs_hook=_no_duplicates, parse_constant=_no_constant,
411
+ parse_float=_finite_float, parse_int=_finite_int)
412
+ except (UnicodeDecodeError, ValueError, RecursionError) as e:
413
+ raise _invalid(where, f"not a JSON file ({e})") from None
414
+ try:
415
+ return _validated(data, digest, where)
416
+ except (ValueError, OverflowError, TypeError) as e: # (DecisionRulesError is a ValueError: kept as it is)
417
+ if isinstance(e, DecisionRulesError):
418
+ raise
419
+ raise _invalid(where, f"an invalid value ({e})") from None
420
+
421
+
422
+ def _validated(data, digest, where):
423
+ """A parsed rules file -> DecisionRules (parse's checks of its fields)."""
424
+ if not isinstance(data, dict):
425
+ raise _invalid(where, "not a JSON object")
426
+ if data.get("format") != FORMAT:
427
+ raise _invalid(where, f"format {data.get('format')!r}, expected {FORMAT!r}")
428
+ keys = set(data)
429
+ if keys != set(FILE_KEYS):
430
+ missing, extra = sorted(set(FILE_KEYS) - keys), sorted(keys - set(FILE_KEYS))
431
+ raise _invalid(where, "; ".join(x for x in (f"missing {', '.join(missing)}" if missing else "",
432
+ f"unknown {', '.join(extra)}" if extra else "") if x))
433
+ if not _id_ok(data["id"]):
434
+ raise _invalid(where, f"id {data['id']!r}: a non-empty printable string of at most {MAX_ID} characters, "
435
+ "without spaces at its ends")
436
+ if data["experimental"] is not True:
437
+ raise _invalid(where, "experimental must be true (decision rules are an experimental feature)")
438
+ for k in ("created", "basal_version", "metric"):
439
+ if not isinstance(data[k], str) or not data[k]:
440
+ raise _invalid(where, f"{k} must be a non-empty string")
441
+ sig = data["inference_signature"]
442
+ if not isinstance(sig, dict):
443
+ raise _invalid(where, "inference_signature must be an object")
444
+ sig = {"state_cache_match": None, **sig} # older files used incremental state matching
445
+ missing = [k for k in SIGNATURE_FIELDS if k not in sig]
446
+ if missing:
447
+ raise _invalid(where, f"inference_signature lacks {', '.join(missing)}")
448
+ try:
449
+ check_backend(sig)
450
+ except DecisionRulesError as e:
451
+ raise _invalid(where, f"fitted on {e}") from None
452
+ if not isinstance(data["provenance"], dict):
453
+ raise _invalid(where, "provenance must be an object")
454
+ if not isinstance(data["rules"], dict) or not data["rules"]:
455
+ raise _invalid(where, "rules must be a non-empty object {rule_id: rule}")
456
+ rules = {k: _rule(where, k, v, data["id"], digest) for k, v in data["rules"].items()}
457
+ return DecisionRules(data["id"], digest, MappingProxyType(rules), _canonical(sig), _canonical(data))
458
+
459
+
460
+ def load(path):
461
+ """A rules file -> DecisionRules (frozen): .id, .sha256 (of the file's bytes), .signature, .rules {rule_id: Rule}.
462
+ Everything is validated; any problem (an unreadable file too) is DecisionRulesError invalid_file."""
463
+ try:
464
+ raw = Path(path).read_bytes()
465
+ except OSError as e:
466
+ raise _invalid(str(path), f"cannot read it ({e.strerror or e})") from None
467
+ return parse(raw, str(path))
468
+
469
+
470
+ def _where(item):
471
+ return f"question {item['name']!r}: " if item.get("name") is not None else ""
472
+
473
+
474
+ def check_request(rule, conditions, item=None):
475
+ """A request's conditions (request_conditions) against the ones a rule was fitted under: DecisionRulesError
476
+ request_mismatch naming the fields that differ (.fields). The builtin applies to any request."""
477
+ fitted = rule.request
478
+ if fitted is None:
479
+ return
480
+ if not _conditions_ok(conditions):
481
+ raise ValueError(f"request conditions must be request_conditions(body, ...), got {_short(conditions)}")
482
+ diff = [k for k in REQUEST_FIELDS if _canonical(fitted[k]) != _canonical(conditions[k])]
483
+ if diff:
484
+ what = ", ".join(f"{k} {_short(fitted[k])}" for k in diff)
485
+ has = ", ".join(f"{k} {_short(conditions[k])}" for k in diff)
486
+ raise DecisionRulesError("request_mismatch", f"{_where(item or {})}decision_rule {rule.rule_id!r} was fitted "
487
+ f"on requests with {what}; this request has {has}", fields=diff)
488
+
489
+
490
+ def resolve(rules, rule_id, item, request):
491
+ """The rule a question asks for ("decision_rule": rule_id) on a request with the conditions `request`
492
+ (request_conditions of its body) -> Rule. builtin:argmax-v1 needs no file and applies to any request. Refusals
493
+ (DecisionRulesError): unsupported_type (not a noul or score question), no_rules (no file loaded), unknown_rule
494
+ (not in the file), schema_mismatch (the rule was fitted on another question schema), request_mismatch (on requests
495
+ with another facts mode, early-exit policy or media)."""
496
+ at = _where(item)
497
+ if item.get("type") not in TYPES:
498
+ raise DecisionRulesError("unsupported_type", f"{at}decision rules apply to noul and score questions, not "
499
+ f"{item.get('type')!r}")
500
+ if rule_id == BUILTIN_ARGMAX:
501
+ return BUILTIN
502
+ if not isinstance(rule_id, str) or not rule_id:
503
+ raise DecisionRulesError("unknown_rule", f"{at}decision_rule must be a rule id (a non-empty string), got "
504
+ f"{_short(rule_id)}")
505
+ if rules is None:
506
+ raise DecisionRulesError("no_rules", f"{at}decision_rule {rule_id!r}: this server has no decision rules "
507
+ f"loaded (only {BUILTIN_ARGMAX!r} needs none)")
508
+ rule = rules.rules.get(rule_id)
509
+ if rule is None:
510
+ known = sorted(rules.rules)
511
+ listed = ", ".join(map(repr, known[:10])) + (f" and {len(known) - 10} more" if len(known) > 10 else "")
512
+ raise DecisionRulesError("unknown_rule", f"{at}decision_rule {rule_id!r} is not in the decision rules "
513
+ f"{rules.id!r} (their rules: {listed}; {BUILTIN_ARGMAX!r} is built in)")
514
+ if schema_hash(item) != rule.schema_hash:
515
+ raise DecisionRulesError("schema_mismatch", f"{at}decision_rule {rule_id!r} was fitted on another question: "
516
+ "its type, language, instructions, options or option_keys differ "
517
+ "(a rule applies only to the exact question it was fitted on)")
518
+ check_request(rule, request, item)
519
+ return rule
520
+
521
+
522
+ def _first_max(keys, probs):
523
+ """The key of the highest probability, the first in key order on a tie (as max() over the answer's probabilities,
524
+ and noul's answer_id: true on a tie)."""
525
+ best = keys[0]
526
+ for k in keys[1:]:
527
+ if probs[k] > probs[best]:
528
+ best = k
529
+ return best
530
+
531
+
532
+ def decide(rule, keys, probs):
533
+ """The key a rule decides for the probabilities {key: p} of a question's keys (in order) -> (key, method)."""
534
+ if rule.method == "threshold":
535
+ return ("true" if probs["true"] >= rule.threshold else "false"), "threshold"
536
+ if rule.method == "round":
537
+ return keys[round_level(expected_level(keys, probs), len(keys))], "round"
538
+ return _first_max(keys, probs), rule.method
539
+
540
+
541
+ def expected_level(keys, probs):
542
+ """mu = sum(i * p_i) over the keys in order, exactly (a Fraction of the probabilities as given): summed in floats
543
+ it can cross a half, 0.75 * 0 + 2**-55 * 1 + nextafter(0.25, 0) * 2 giving 0.5 for 0.5 - 2**-55."""
544
+ return sum((i * Fraction(probs[k]) for i, k in enumerate(keys)), Fraction(0))
545
+
546
+
547
+ def round_level(mu, k):
548
+ """The expected level mu rounded half up and clipped to 0..k-1: floor(mu + 0.5), compared exactly (mu a Fraction
549
+ from expected_level, or a float: in floats mu + 0.5 can round up to the next integer, 0.49999999999999994 + 0.5 ==
550
+ 1.0, while mu - floor(mu) is exact)."""
551
+ lo = math.floor(mu)
552
+ return min(max(lo + (1 if mu - lo >= Fraction(1, 2) else 0), 0), k - 1)
553
+
554
+
555
+ def apply(rule, item, probs):
556
+ """A resolved rule on a plain answer's probabilities -> the answer's "decision" block {key, index, method, rule_id,
557
+ rules_id, rules_sha256, probability (probs[key]), certification, experimental: true}. probs must give a finite
558
+ probability for every key of the item (a ValueError otherwise: the engine's fault, not the request's)."""
559
+ keys = [str(k) for k in item["keys"]]
560
+ bad = [k for k in keys if isinstance(probs.get(k), bool) or not isinstance(probs.get(k), (int, float))
561
+ or not math.isfinite(probs[k])]
562
+ if bad:
563
+ raise ValueError(f"{_where(item)}no finite probability for {', '.join(map(repr, bad[:5]))}")
564
+ if rule.type is not None and rule.type != item["type"]:
565
+ raise ValueError(f"{_where(item)}a {rule.type} rule on a {item['type']} question (resolve checks this)")
566
+ key, method = decide(rule, keys, probs)
567
+ return {"key": key, "index": keys.index(key), "method": method, "rule_id": rule.rule_id,
568
+ "rules_id": rule.rules_id, "rules_sha256": rule.rules_sha256, "probability": probs[key],
569
+ "certification": rule.certification, "experimental": True}