sr-zero 0.9.0__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.
@@ -0,0 +1,52 @@
1
+ """System Zero as a Decision Index engine.
2
+
3
+ python -m decision_index run --engine system_zero.decision_index:SystemZeroEngine \
4
+ --rows sample.jsonl.gz --out runs/zero
5
+
6
+ The kit calls engine(state, questions) and expects (response, raw). When the kit is installed this class extends its
7
+ Engine and raises its Unsupported for a question System Zero cannot answer; without the kit it works on its own.
8
+ """
9
+ import platform
10
+
11
+ from . import __version__
12
+ from .model import SystemZero
13
+ from .systemone import Unsupported
14
+
15
+ try:
16
+ from decision_index.engines import Engine as _Base
17
+ from decision_index.engines import Unsupported as _KitUnsupported
18
+ except ImportError: # the kit is optional
19
+ _Base, _KitUnsupported = object, Unsupported
20
+
21
+
22
+ class SystemZeroEngine(_Base):
23
+ name = "system-zero"
24
+ latency = "In-process wall time of SystemZero.decide on one CPU core, rules already loaded; no GPU."
25
+
26
+ def __init__(self, rules=None, **options):
27
+ self.options = dict(options, rules=rules)
28
+ self.model = SystemZero(rules)
29
+ stats = self.model.stats()
30
+ self.provenance = {"kind": "rules", "package": f"system-zero {__version__}", "parameters": 0,
31
+ "rules": stats["rules"], "learned_from_questions": stats["train_questions"]}
32
+
33
+ def __call__(self, state, questions, **inputs):
34
+ try:
35
+ response = self.model.decide(state, questions)
36
+ except Unsupported as error:
37
+ raise _KitUnsupported(str(error)) from error
38
+ return response, None
39
+
40
+ def warmup(self):
41
+ self({"text": "The color is red."}, {"warmup": {"type": "choice", "instructions": "Which color is named?",
42
+ "criteria": {"red": "red", "blue": "blue"}}})
43
+
44
+ def runtime(self):
45
+ return {"device": "cpu", "parameters": 0, "python": platform.python_version(),
46
+ "load_seconds": round(self.model.load_seconds, 3)}
47
+
48
+ def synchronize(self):
49
+ pass
50
+
51
+ def close(self):
52
+ pass
@@ -0,0 +1,42 @@
1
+ """Evidence sums: for option sets with many answers and evidence spread over many words (intents, topics), every cue
2
+ of the request that comes with an answer significantly often in training adds the log of how much more often. The
3
+ learner and the runtime both use this file, so a sum means the same thing when it is chosen and when it answers.
4
+
5
+ Everything here is a count or a closed-form function of counts: the answer counts of the scope, and for each cue its
6
+ sightings and the answers it comes with more than two standard deviations above their share. M is a fixed constant.
7
+ """
8
+ import math
9
+
10
+ M = 5
11
+ SEEN = 2
12
+ BINS = (0.5, 0.8, 1.0)
13
+
14
+
15
+ def scores(cues, keys, prior, total, table, m=M):
16
+ """({answer: log P(answer) + the sum of log lifts of its present cues}, the cue/answer pairs that counted)."""
17
+ base = {y: (prior.get(y, 0) + 1) / (total + len(keys)) for y in keys}
18
+ out = {y: math.log(p) for y, p in base.items()}
19
+ used = []
20
+ for f in cues:
21
+ found = table.get(f)
22
+ if not found:
23
+ continue
24
+ n, kept = found
25
+ for y, c in kept.items():
26
+ if y in out:
27
+ lift = math.log((c + m * base[y]) / ((n + m) * base[y]))
28
+ out[y] += lift
29
+ used.append((lift, f, y))
30
+ return out, used
31
+
32
+
33
+ def shares(values):
34
+ """The scores as shares that sum to 1 (a softmax); the reported probability comes from the held-out records."""
35
+ top = max(values.values())
36
+ weights = {y: math.exp(s - top) for y, s in values.items()}
37
+ total = sum(weights.values())
38
+ return {y: w / total for y, w in weights.items()}
39
+
40
+
41
+ def bin_of(share):
42
+ return next(i for i, edge in enumerate(BINS) if share <= edge)
system_zero/marks.py ADDED
@@ -0,0 +1,27 @@
1
+ """The code points that continue a word: the combining marks of Unicode 16.0 (general categories Mn, Mc and Me) in
2
+ the Basic Multilingual Plane, such as accents written as separate code points, the vowel signs and viramas of Indic
3
+ scripts and the tone marks of Thai. Python's \\w leaves them out, so without them Hindi "नहीं" would be read as "नह".
4
+ Kept to one plane so that a character class holding them is still matched by table lookup."""
5
+
6
+ MARKS = (
7
+ "\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05c7\u0610-\u061a\u064b-\u065f\u0670"
8
+ "\u06d6-\u06dc\u06df-\u06e4\u06e7-\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u07fd"
9
+ "\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903"
10
+ "\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962-\u0963\u0981-\u0983\u09bc\u09be-\u09c4\u09c7-\u09c8\u09cb-\u09cd"
11
+ "\u09d7\u09e2-\u09e3\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47-\u0a48\u0a4b-\u0a4d\u0a51\u0a70-\u0a71\u0a75"
12
+ "\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2-\u0ae3\u0afa-\u0aff\u0b01-\u0b03\u0b3c"
13
+ "\u0b3e-\u0b44\u0b47-\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62-\u0b63\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd"
14
+ "\u0bd7\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56\u0c62-\u0c63\u0c81-\u0c83\u0cbc"
15
+ "\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5-\u0cd6\u0ce2-\u0ce3\u0cf3\u0d00-\u0d03\u0d3b-\u0d3c\u0d3e-\u0d44"
16
+ "\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62-\u0d63\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2-\u0df3"
17
+ "\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0f18-\u0f19\u0f35\u0f37\u0f39\u0f3e-\u0f3f"
18
+ "\u0f71-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1056-\u1059\u105e-\u1060\u1062-\u1064"
19
+ "\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f\u109a-\u109d\u135d-\u135f\u1712-\u1715\u1732-\u1734\u1752-\u1753"
20
+ "\u1772-\u1773\u17b4-\u17d3\u17dd\u180b-\u180d\u180f\u1885-\u1886\u18a9\u1920-\u192b\u1930-\u193b\u1a17-\u1a1b"
21
+ "\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f\u1ab0-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad"
22
+ "\u1be6-\u1bf3\u1c24-\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u20d0-\u20f0"
23
+ "\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099-\u309a\ua66f-\ua672\ua674-\ua67d\ua69e-\ua69f\ua6f0-\ua6f1"
24
+ "\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880-\ua881\ua8b4-\ua8c5\ua8e0-\ua8f1\ua8ff\ua926-\ua92d\ua947-\ua953"
25
+ "\ua980-\ua983\ua9b3-\ua9c0\ua9e5\uaa29-\uaa36\uaa43\uaa4c-\uaa4d\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7-\uaab8"
26
+ "\uaabe-\uaabf\uaac1\uaaeb-\uaaef\uaaf5-\uaaf6\uabe3-\uabea\uabec-\uabed\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f"
27
+ )
system_zero/model.py ADDED
@@ -0,0 +1,489 @@
1
+ """System Zero's runtime: it reads the rule files and answers decision requests.
2
+
3
+ A request is a state and typed questions (the Decision Index and SystemOne shape). For every question, three kinds
4
+ of rules may propose an answer, and the one most trusted by its training record (the lower end of its 95%
5
+ interval, Wilson) is taken:
6
+
7
+ 1. decision lists (rules/frames.py, rules/options.py) for questions whose options are a known set;
8
+ 2. context cues (rules/cues.py) for questions whose options are not;
9
+ 3. hand-written modules (system_zero/modules/), trusted by their counts in rules/modules.py.
10
+
11
+ The rule files are Python literals, read with ast.literal_eval: loading rules never runs code from them. Requests and
12
+ answers follow the System One API exactly (system_zero/systemone.py).
13
+ """
14
+ import ast
15
+ import gc
16
+ import hashlib
17
+ import math
18
+ import os
19
+ import time
20
+ import zlib
21
+
22
+ from . import cues as cue_lib
23
+ from . import evidence, systemone, text
24
+ from .modules import MODULES
25
+ from .request import Request
26
+ from .systemone import MODEL, Problem, QuestionError
27
+
28
+ HERE = os.path.dirname(os.path.abspath(__file__))
29
+ RULES = os.path.join(HERE, "rules")
30
+ RULE_FILES = ("option_sets.py", "frames.py", "options.py", "cues.py", "modules.py")
31
+ Z = 1.96
32
+ SUPPORTED = systemone.ANSWERED
33
+
34
+
35
+ def lower(right, fired, z=Z):
36
+ """Wilson lower bound of right / fired."""
37
+ if fired <= 0:
38
+ return 0.0
39
+ p = right / fired
40
+ d = 1 + z * z / fired
41
+ c = p + z * z / (2 * fired)
42
+ return (c - z * math.sqrt(p * (1 - p) / fired + z * z / (4 * fired * fired))) / d
43
+
44
+
45
+ def _load(path, name):
46
+ """(value of `name = ...` in a rule file, its AST node, the file's lines), without running the file."""
47
+ with open(path, encoding="utf-8") as f:
48
+ source = f.read()
49
+ tree = ast.parse(source, filename=path)
50
+ for node in tree.body:
51
+ if isinstance(node, ast.Assign) and any(getattr(t, "id", None) == name for t in node.targets):
52
+ return ast.literal_eval(node.value), node.value, source.splitlines()
53
+ raise ValueError(f"{path} has no {name}")
54
+
55
+
56
+ def _rule_lines(dict_node, name="rules"):
57
+ """{scope key: [line of each entry of `name`]} from the AST of a FRAMES or OPTIONS literal."""
58
+ out = {}
59
+ for key, value in zip(dict_node.keys, dict_node.values):
60
+ k = ast.literal_eval(key)
61
+ for field, items in zip(value.keys, value.values):
62
+ if ast.literal_eval(field) == name:
63
+ out[k] = [item.lineno for item in items.elts]
64
+ return out
65
+
66
+
67
+ class Scope:
68
+ """One decision list: its prior and its rules, indexed by cue; for a scope answered by evidence sums, its table
69
+ and the held-out records of its answers."""
70
+ __slots__ = ("key", "prior", "rules", "lines", "index", "mode", "bins", "evidence", "evidence_lines", "total")
71
+
72
+ def __init__(self, key, prior, rules, lines, spec=None, evidence_lines=()):
73
+ self.key, self.prior, self.rules, self.lines = key, prior, rules, lines
74
+ self.index = {}
75
+ for rank, rule in enumerate(rules):
76
+ self.index.setdefault(rule[0], rank)
77
+ spec = spec or {}
78
+ self.mode = spec.get("mode", "list")
79
+ self.bins = spec.get("bins", [])
80
+ self.evidence = {cue: (seen, kept) for cue, seen, kept in spec.get("evidence", [])}
81
+ self.evidence_lines = {entry[0]: line for entry, line in zip(spec.get("evidence", []), evidence_lines)}
82
+ self.total = sum(prior.values())
83
+
84
+ def first(self, found):
85
+ """Rank of the first rule whose cue is among `found`, else None."""
86
+ best = None
87
+ index = self.index
88
+ for cue in found:
89
+ rank = index.get(cue)
90
+ if rank is not None and (best is None or rank < best):
91
+ best = rank
92
+ return best
93
+
94
+
95
+ class SystemZero:
96
+ """The model. `SystemZero()` loads the packaged rules; `SystemZero(path)` loads rule files from a directory,
97
+ such as a download of the model repository on the Hugging Face Hub."""
98
+
99
+ def __init__(self, path=None):
100
+ self.path = path or RULES
101
+ started = time.perf_counter()
102
+ sets, _, _ = _load(os.path.join(self.path, "option_sets.py"), "OPTION_SETS")
103
+ self.option_sets = sets
104
+ self.set_of = {signature: sid for sid, signature in sets.items()}
105
+ frames, node, self.frame_source = _load(os.path.join(self.path, "frames.py"), "FRAMES")
106
+ lines, more = _rule_lines(node), _rule_lines(node, "evidence")
107
+ self.frames = {k: Scope(k, v["prior"], v["rules"], lines[k], v, more.get(k, ())) for k, v in frames.items()}
108
+ self.subframes = any(len(k) == 3 for k in self.frames)
109
+ options, node, self.option_source = _load(os.path.join(self.path, "options.py"), "OPTIONS")
110
+ lines, more = _rule_lines(node), _rule_lines(node, "evidence")
111
+ self.options = {k: Scope(k, v["prior"], v["rules"], lines[k], v, more.get(k, ())) for k, v in options.items()}
112
+ free, node, self.cue_source = _load(os.path.join(self.path, "cues.py"), "CUES")
113
+ self.cues = {}
114
+ for key, value in zip(node.keys, node.values):
115
+ template = ast.literal_eval(key)
116
+ rules = [(c, None, r, f) for c, r, f in free[template]]
117
+ self.cues[template] = Scope(template, {}, rules, [item.lineno for item in value.elts])
118
+ self.module_cases, _, _ = _load(os.path.join(self.path, "modules.py"), "MODULE_CASES")
119
+ self.learned, _, _ = _load(os.path.join(self.path, "modules.py"), "LEARNED")
120
+ self.module_source, self.case_lines = {}, {}
121
+ for module in MODULES:
122
+ with open(module.__file__, encoding="utf-8") as f:
123
+ lines = f.read().splitlines()
124
+ self.module_source[module.NAME] = lines
125
+ for number, line in enumerate(lines, 1):
126
+ for case in getattr(module, "CASES", {}):
127
+ if line.strip().startswith("return") and f'"{case}"' in line:
128
+ self.case_lines.setdefault(f"{module.NAME}.{case}", number)
129
+ for number, line in enumerate(lines, 1):
130
+ for case in getattr(module, "CASES", {}):
131
+ if f'"{case}"' in line and f'"{case}":' not in line:
132
+ self.case_lines.setdefault(f"{module.NAME}.{case}", number)
133
+ digest = hashlib.sha256()
134
+ for name in RULE_FILES:
135
+ with open(os.path.join(self.path, name), "rb") as f:
136
+ digest.update(name.encode() + b"\0" + f.read())
137
+ self.sha256 = digest.hexdigest()
138
+ self.revision = _source_commit()
139
+ self.release_date = str(self.learned.get("date", ""))
140
+ # The rules are millions of small containers that never become garbage: left to the collector, every full
141
+ # collection walks all of them and stalls whichever request triggered it.
142
+ gc.collect()
143
+ gc.freeze()
144
+ self.load_seconds = time.perf_counter() - started
145
+
146
+ # ---- the public interface -------------------------------------------------------------------------------------
147
+
148
+ def decide(self, state, questions, explain=False):
149
+ """Answer every question of one request, in the System One format: {"model", "answers", "usage"}, a
150
+ probability for every option. A question that cannot be answered fails the request, as POST /v1/systemone
151
+ fails it: Unsupported names the question, its error and the reason. With explain=True each answer also
152
+ carries the rule behind it."""
153
+ if not isinstance(questions, dict) or not questions:
154
+ raise Problem("invalid_request", "questions must be a nonempty object of named questions")
155
+ systemone.check_state(state, empty_ok=True)
156
+ response = self.respond(state, questions, explain)
157
+ invalid = systemone.no_valid_question([(None, response)])
158
+ if invalid is not None:
159
+ raise systemone.as_failed(invalid)
160
+ failed = systemone.first_failure([(None, response)])
161
+ if failed is not None:
162
+ raise failed
163
+ return response
164
+
165
+ def __call__(self, state, questions, explain=False):
166
+ return self.decide(state, questions, explain)
167
+
168
+ def respond(self, state, questions, explain=False, deadline=None, name=MODEL):
169
+ """Every question's answer, in request order, as POST /v1/decisions answers them: a question that cannot be
170
+ answered carries its error, reason and message in its own answer."""
171
+ systemone.check_questions(questions)
172
+ valid, failed = {}, {}
173
+ for key, question in questions.items():
174
+ kind = question.get("type") if isinstance(question, dict) else None
175
+ try:
176
+ valid[key] = systemone.read_question(question)
177
+ except QuestionError as error:
178
+ failed[key] = error.answer(kind)
179
+ request = Request(state, valid, {key: self._known(q) for key, q in valid.items()})
180
+ used = systemone.tokens(state)
181
+ answers = {}
182
+ for key in questions:
183
+ if key in failed:
184
+ answers[key] = failed[key]
185
+ continue
186
+ question = valid[key]
187
+ if deadline is not None and time.perf_counter() > deadline:
188
+ answers[key] = QuestionError("deadline_exceeded", "the question was not answered before the "
189
+ "deadline").answer(question["type"])
190
+ continue
191
+ if question["require_full_input"] and not self._reads_whole(request, question):
192
+ answers[key] = QuestionError("max_length_exceeded", "the question cannot read its whole input: System "
193
+ f"Zero's word rules read the first {text.STATE_WORDS} words of the state "
194
+ f"and {text.INSTRUCTION_WORDS} of the instructions",
195
+ "require_full_input").answer(question["type"])
196
+ continue
197
+ used += systemone.tokens(question["instructions"]) + systemone.tokens(question["criteria"])
198
+ started = time.perf_counter()
199
+ keys, dist, why = self._answer(request, key, question)
200
+ answer = systemone.answer(question, {k: dist[k] for k in keys})
201
+ if question["require_full_input"]:
202
+ answer["input_coverage"] = "complete"
203
+ if explain:
204
+ why["microseconds"] = round((time.perf_counter() - started) * 1e6, 1)
205
+ answer["explanation"] = why
206
+ answers[key] = answer
207
+ return {"model": name, "answers": answers, "usage": {"input_tokens": used, "output_tokens": 0}}
208
+
209
+ def meta(self, compute_ms=0.0):
210
+ """What options.return_meta adds to a response: which rules answered, and how long they took."""
211
+ return {"model_id": MODEL, "revision": self.revision, "model_sha256": self.sha256, "numerics": "exact",
212
+ "engine": "system-zero", "device": "cpu", "queue_ms": 0.0, "compute_ms": round(compute_ms, 3),
213
+ "parameters": 0, "rules": self.learned.get("rules")}
214
+
215
+ def stats(self):
216
+ """How many rules the model holds, and what it learned from."""
217
+ return dict(self.learned)
218
+
219
+ def layout(self):
220
+ """Rules and lines per rule file, in the order the files are read: for drawing every rule at once."""
221
+ modules = sum(len(lines) for lines in self.module_source.values())
222
+ return [
223
+ {"file": "system_zero/rules/frames.py",
224
+ "rules": sum(len(s.rules) + len(s.evidence) for s in self.frames.values()),
225
+ "lines": len(self.frame_source)},
226
+ {"file": "system_zero/rules/options.py",
227
+ "rules": sum(len(s.rules) + len(s.evidence) for s in self.options.values()),
228
+ "lines": len(self.option_source)},
229
+ {"file": "system_zero/rules/cues.py", "rules": sum(len(s.rules) for s in self.cues.values()),
230
+ "lines": len(self.cue_source)},
231
+ {"file": "system_zero/modules/", "rules": len(self.module_cases), "lines": modules},
232
+ ]
233
+
234
+ # ---- one question --------------------------------------------------------------------------------------------
235
+
236
+ def _answer(self, request, key, question):
237
+ question = dict(question)
238
+ if question.get("type") == "score":
239
+ question["type"] = "choice"
240
+ options = text.options(question)
241
+ keys = [k for k, _ in options]
242
+ label = self._label(request, question, keys)
243
+ best = label if label is not None else self._free(request, question, options)
244
+ module = self._module(request, key)
245
+ if module and (module[3] or module[0] > best[0]):
246
+ best = module
247
+ return keys, best[1], best[2]
248
+
249
+ def _label(self, request, question, keys):
250
+ """(trust, probabilities, explanation) from the decision lists, or None if the option set is unknown."""
251
+ sid = self.set_of.get(text.signature(question))
252
+ if sid is None:
253
+ return None
254
+ meanings = text.names(question)
255
+ key_of = dict(zip(meanings, keys))
256
+ template = text.template(question.get("instructions"))
257
+ frame = self.frames.get((template, sid))
258
+ scopes = ([("frame", frame)] if frame else []) + [("options", self.options[sid])]
259
+ if self.subframes:
260
+ full = text.full_question(question.get("instructions"))
261
+ sub = self.frames.get((template, sid, full)) if full else None
262
+ if sub:
263
+ scopes.insert(0, ("subframe", sub))
264
+ found = self._label_cues(request, question)
265
+ for kind, scope in scopes:
266
+ if scope.mode == "sum":
267
+ summed = self._summed(kind, scope, found, meanings, key_of, template, sid)
268
+ if summed is not None:
269
+ return summed
270
+ rank = scope.first(found)
271
+ if rank is not None:
272
+ cue, answer, right, fired = scope.rules[rank]
273
+ dist = _spread(meanings, scope.prior, answer, right, fired)
274
+ why = self._why(kind, scope, rank, template, sid)
275
+ why["answer"], why["meaning"] = key_of.get(answer, answer), answer
276
+ return lower(right, fired), {key_of[m]: p for m, p in dist.items()}, why
277
+ kind, scope = scopes[0]
278
+ dist = _spread(meanings, scope.prior)
279
+ top = max(meanings, key=lambda m: (dist[m], m))
280
+ why = {"by": "prior", "scope": self._scope_name(kind, template, sid),
281
+ "rule": f"no rule fired, so the answer most often right in training for this {self._noun(kind)}",
282
+ "answer": key_of[top], "meaning": top, "right": scope.prior.get(top, 0),
283
+ "fired": sum(scope.prior.values()),
284
+ "file": f"system_zero/rules/{'options' if kind == 'options' else 'frames'}.py"}
285
+ return 0.0, {key_of[m]: p for m, p in dist.items()}, why
286
+
287
+ def _summed(self, kind, scope, found, meanings, key_of, template, sid):
288
+ """(trust, probabilities, explanation) from a scope's evidence sums, or None when no cue of it is present."""
289
+ values, used = evidence.scores(found, meanings, scope.prior, scope.total, scope.evidence)
290
+ if not used:
291
+ return None
292
+ shares = evidence.shares(values)
293
+ pick = max(meanings, key=lambda m: (shares[m], m))
294
+ _, right, asked = scope.bins[evidence.bin_of(shares[pick])]
295
+ rest = sum(v for m, v in shares.items() if m != pick) or 1
296
+ others = len(meanings) - 1
297
+ weight = {m: (shares[m] / rest + 1 / others) / 2 for m in meanings if m != pick}
298
+ most = max(weight.values())
299
+ top = _trusted(right, asked, max(1 / len(meanings), most / (1 + most)))
300
+ dist = {m: top if m == pick else (1 - top) * weight[m] for m in meanings}
301
+ mine = sorted((u for u in used if u[2] == pick), reverse=True)
302
+ named = ", ".join(f"\"{cue.split(' ', 1)[1]}\"" for _, cue, _ in mine[:3])
303
+ source = self.option_source if kind == "options" else self.frame_source
304
+ line = scope.evidence_lines.get(mine[0][1]) if mine else None
305
+ why = {"by": "evidence", "scope": self._scope_name(kind, template, sid),
306
+ "rule": f"the answer the request's words count for most ({len(mine)} of its cues: {named})"
307
+ if mine else "the answer the request's words count for most",
308
+ "answer": key_of.get(pick, pick), "meaning": pick, "right": right, "fired": asked,
309
+ "cue": mine[0][1] if mine else "",
310
+ "file": f"system_zero/rules/{'options' if kind == 'options' else 'frames'}.py"}
311
+ if line:
312
+ why["line"], why["code"] = line, source[line - 1].strip()
313
+ return lower(right, asked), {key_of[m]: p for m, p in dist.items()}, why
314
+
315
+ def _label_cues(self, request, question):
316
+ found = text.label_cues(request.once("state_cues", lambda r: text.cues(r.state_text, "s ", text.STATE_WORDS)),
317
+ question.get("instructions"))
318
+ cache = request.once("relations", lambda r: {})
319
+ for relation in text.relations(request.data, request.state_text, question.get("instructions"), cache):
320
+ found[relation] = None
321
+ return found
322
+
323
+ def _free(self, request, question, options):
324
+ texts = [d or k for k, d in options]
325
+ keys = [k for k, _ in options]
326
+ instructions = text.flatten(question.get("instructions"))
327
+ state = request.once("cue_view", lambda r: cue_lib.view(r.state_text))
328
+ pointed = {name: i for name, i in cue_lib.read(request.state_text, instructions, texts, state).items()
329
+ if i >= 0}
330
+ pointed.update(("only " + w, i) for w, i in cue_lib.only_words(texts).items())
331
+ template = text.template(question.get("instructions"))
332
+ own = template if template in self.cues else "*"
333
+ for scope_key in (own, "*"):
334
+ scope = self.cues.get(scope_key)
335
+ if scope is None:
336
+ continue
337
+ rank = scope.first(pointed)
338
+ if rank is not None:
339
+ cue, _, right, fired = scope.rules[rank]
340
+ index = pointed[cue]
341
+ n = len(keys)
342
+ p = _trusted(right, fired, 1 / n)
343
+ dist = {k: p if j == index else (1 - p) / (n - 1) for j, k in enumerate(keys)}
344
+ line = scope.lines[rank]
345
+ why = {"by": "cue", "scope": "every question" if scope_key == "*" else f"template \"{template}\"",
346
+ "rule": _say_cue(cue), "cue": cue, "answer": keys[index], "right": right, "fired": fired,
347
+ "file": "system_zero/rules/cues.py", "line": line,
348
+ "code": self.cue_source[line - 1].strip()}
349
+ return lower(right, fired), dist, why
350
+ n = len(keys)
351
+ pick = keys[zlib.crc32("\x00".join([instructions] + texts).encode()) % n]
352
+ dist = {k: (1 + (1e-9 if k == pick else 0.0)) / n for k in keys}
353
+ return 0.0, dist, {"by": "chance", "rule": "no rule applies, so every option is equally likely; the pick is "
354
+ "a hash of the question's text, so no position is favoured",
355
+ "answer": pick}
356
+
357
+ def _module(self, request, key):
358
+ """(trust, probabilities, explanation, sole) of the most trusted module proposal, or None. A proposal of a case
359
+ its module lists as SOLE (one scorer for every question of its kind) is taken before any other."""
360
+ best = None
361
+ for module in MODULES:
362
+ try:
363
+ found = module.propose(request, key)
364
+ except Exception: # noqa: BLE001 - a module that fails passes, as a rule that does not fire
365
+ continue
366
+ if not found:
367
+ continue
368
+ pick, case = found[0], found[1]
369
+ nudge = found[2] if len(found) > 2 else 0.0
370
+ name = f"{module.NAME}.{case}"
371
+ if name not in self.module_cases:
372
+ continue
373
+ right, fired = self.module_cases[name]
374
+ trust = lower(right, fired)
375
+ sole = case in getattr(module, "SOLE", ())
376
+ if best is None or (sole, trust) > (best[3], best[0]):
377
+ keys = [k for k, _ in text.options(request.questions[key])]
378
+ p = min(1 - 1e-9, _trusted(right, fired, 1 / len(keys)) + nudge)
379
+ dist = {k: p if k == pick else (1 - p) / (len(keys) - 1) for k in keys}
380
+ why = {"by": "module", "module": module.NAME, "case": case, "rule": module.describe(case),
381
+ "answer": pick, "right": right, "fired": fired,
382
+ "file": f"system_zero/modules/{module.NAME}.py"}
383
+ line = self.case_lines.get(name)
384
+ if line:
385
+ why["line"], why["code"] = line, self.module_source[module.NAME][line - 1].strip()
386
+ best = (trust, dist, why, sole)
387
+ return best
388
+
389
+ def _known(self, question):
390
+ """Whether a question's option set is one the decision lists know."""
391
+ if question["type"] == "score":
392
+ question = dict(question, type="choice")
393
+ return text.signature(question) in self.set_of
394
+
395
+ # ---- explanations ---------------------------------------------------------------------------------------------
396
+
397
+ def _reads_whole(self, request, question):
398
+ """Whether the word rules read every word of the state and the instructions (require_full_input)."""
399
+ state = request.once("state_words", lambda r: len(text.words(r.state_text)))
400
+ return state <= text.STATE_WORDS and len(text.words(text.flatten(question["instructions"]))) <= \
401
+ text.INSTRUCTION_WORDS
402
+
403
+ def _noun(self, kind):
404
+ return {"frame": "question frame", "subframe": "question"}.get(kind, "option set")
405
+
406
+ def _scope_name(self, kind, template, sid):
407
+ if kind == "subframe":
408
+ return f"this whole question (template \"{template}\") with option set {sid}"
409
+ if kind == "frame":
410
+ return f"frame \"{template}\" with option set {sid}"
411
+ return f"option set {sid}"
412
+
413
+ def _why(self, kind, scope, rank, template, sid):
414
+ cue, answer, right, fired = scope.rules[rank]
415
+ line = scope.lines[rank]
416
+ source = self.option_source if kind == "options" else self.frame_source
417
+ return {"by": kind, "scope": self._scope_name(kind, template, sid), "rule": _say_rule(cue, answer),
418
+ "cue": cue, "answer": answer, "right": right, "fired": fired, "rank": rank + 1,
419
+ "of": len(scope.rules), "file": f"system_zero/rules/{'options' if kind == 'options' else 'frames'}.py",
420
+ "line": line, "code": source[line - 1].strip()}
421
+
422
+
423
+ def _source_commit():
424
+ """The GitHub commit a copy of the package was taken from (a Space or the model repository), if recorded."""
425
+ try:
426
+ with open(os.path.join(HERE, "SOURCE_COMMIT"), encoding="utf-8") as f:
427
+ return f.read().strip()[:40] or None
428
+ except OSError:
429
+ return None
430
+
431
+
432
+ def _trusted(right, fired, floor):
433
+ """The probability a rule's pick is given: the lower end of its record's 95% interval (Wilson), which rules picked
434
+ for a high record on few questions do reach on new ones; never at or below `floor`, so the pick stays the
435
+ answer."""
436
+ return max(lower(right, fired), floor + 1e-9)
437
+
438
+
439
+ def _spread(keys, prior, pick=None, right=0, fired=0):
440
+ weights = {k: prior.get(k, 0) + 1 for k in keys}
441
+ total = sum(weights.values())
442
+ base = {k: w / total for k, w in weights.items()}
443
+ if pick is None or pick not in base:
444
+ return base
445
+ rest = sum(v for k, v in base.items() if k != pick) or 1
446
+ most = max((v / rest for k, v in base.items() if k != pick), default=0)
447
+ p = _trusted(right, fired, most / (1 + most))
448
+ return {k: p if k == pick else (1 - p) * base[k] / rest for k in keys}
449
+
450
+
451
+ def _say_rule(cue, answer):
452
+ kind, _, what = cue.partition(" ")
453
+ if kind == "s":
454
+ return f"if the state contains \"{what}\", answer {answer}"
455
+ if kind == "q":
456
+ return f"if the question contains \"{what}\", answer {answer}"
457
+ if kind == "r":
458
+ if what.endswith(" negated"):
459
+ return f"if {what[:-8]} is negated (not, no, never, ...), answer {answer}"
460
+ for unit in ("names", "numbers"):
461
+ field, found, missing = what.partition(f" {unit} missing ")
462
+ if found:
463
+ if missing == "0":
464
+ return f"if every one of the {unit} in {field} appears in the rest of the request, answer {answer}"
465
+ many = {"1": f"one of the {unit} in {field} is", "1+": f"one or more of the {unit} in {field} are",
466
+ "2+": f"two or more of the {unit} in {field} are"}.get(missing,
467
+ f"{missing} {unit} of {field} are")
468
+ return f"if {many} missing from the rest of the request, answer {answer}"
469
+ field, _, rest = what.partition(" cover ")
470
+ share = {"0": "none", "100": "all"}.get(rest, rest.rstrip("+") + "% or more")
471
+ return f"if {share} of the words of {field} appear in the rest of the request, answer {answer}"
472
+ return f"if {cue}, answer {answer}"
473
+
474
+
475
+ def _say_cue(cue):
476
+ if cue.startswith("only "):
477
+ return f"pick the only option containing \"{cue[5:]}\""
478
+ return "pick " + cue_lib.WHAT.get(cue, cue)
479
+
480
+
481
+ _DEFAULT = None
482
+
483
+
484
+ def decide(state, questions, explain=False):
485
+ """Answer one request with the packaged rules (loaded on first use)."""
486
+ global _DEFAULT
487
+ if _DEFAULT is None:
488
+ _DEFAULT = SystemZero()
489
+ return _DEFAULT.decide(state, questions, explain)
@@ -0,0 +1,5 @@
1
+ """Hand-written rule modules. Each one reads a request and may propose an answer to a question, naming the case
2
+ of its own rules that fired; how often each case was right in training decides how far it is trusted."""
3
+ from . import match, music, puzzles, run, scenes, tools, verse
4
+
5
+ MODULES = [run, music, puzzles, scenes, verse, tools, match]