Release 10.3 (full): coverage by the store assembled (the search over learned program structures), one judge over every answer, the opening table on the first interrogative, names written another way learned; full: no organ answers over a terminal refusal; release test pre-registration v39, run once; hashes anchored on Solana (part 22)
ad19be1 verified Download workbench/swarm/o7spine_v1.py from psiloceyeben/oracle7: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/psiloceyeben/oracle7/resolve/main/workbench/swarm/o7spine_v1.py
- Command line
-
hf download hf://psiloceyeben/oracle7/workbench/swarm/o7spine_v1.py
-
curl -L -o o7spine_v1.py https://huggingface.co/psiloceyeben/oracle7/resolve/main/workbench/swarm/o7spine_v1.py
15.2 kB
| """o7spine_v1 - shared specialist memory on the Tree of Life spine (Oracle7 4.2). No language model; numpy only. | |
| Design as in pre-registration v7, amendment 1 (development evidence in oracle7-release/spine/m1_*_dev.py). | |
| A memory is ten holographic vectors named for the Sephirot (D = 1024 unit phasors from osub_seed, the codebook of 3.2's path | |
| memory and 4.0's law), bound in the Fourier form (element-wise multiplication: exact unbinding, no FFT). | |
| An ENTRY binds a KEY to a VALUE: | |
| key exact (a string: a question's hash, an id) - filed in one of the ten vectors by its hash, so they fill evenly; | |
| or associative (weighted content terms) - filed under the node where its operation lives (Hod computes, Binah | |
| relates, Chesed gathers facts, Geburah checks), and recalled from a differently worded request to the degree | |
| the terms overlap | |
| value the route as its own spelled walk on the 22 paths, scaled to unit power (so a route costs what one symbol | |
| costs); status and the route's length share one symbol; every other field (specialist, node, outcome, ...) is | |
| one symbol | |
| Recall unbinds the key; each field is read by cleanup over the values that vector has held; the route is read by cleanup | |
| over the walks that vector has held, and when no walk is clearly matched (or the vector has never held it) the Tree's | |
| WHOLE-WALK decoder reads it at the length the status symbol carries - the best walk the Tree allows, by dynamic programming | |
| over its 10 nodes and 22 paths - and the reply says the route was decoded, not recognised. A recall whose fields are not | |
| clearly above the noise returns nothing. | |
| Groups: a group's memory is the sum of its members' vectors (with their codebooks); the commons is the sum of groups. | |
| Only verified outcomes are written; every entry is hash-chained to the one before and carries a share flag; export writes | |
| the shareable entries with their chain hashes, and import checks every hash before any entry is accepted. | |
| Metabolism (bridge.py's substrate, bounded): weights decay unless recalled, recalled entries are reinforced, and the vectors | |
| are rebuilt from the index on consolidation, so a memory's size stays fixed whatever its age.""" | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import re | |
| import numpy as np | |
| D = 1024 | |
| SEPH = ["keter", "chokmah", "binah", "chesed", "geburah", "tiferet", "netzach", "hod", "yesod", "malkuth"] | |
| SIDE = {"chokmah", "binah", "chesed", "geburah", "netzach", "hod"} | |
| EDGES = [("keter", "chokmah"), ("keter", "binah"), ("keter", "tiferet"), ("chokmah", "binah"), ("chokmah", "tiferet"), | |
| ("chokmah", "chesed"), ("binah", "tiferet"), ("binah", "geburah"), ("chesed", "geburah"), | |
| ("chesed", "tiferet"), ("chesed", "netzach"), ("geburah", "tiferet"), ("geburah", "hod"), | |
| ("tiferet", "netzach"), ("tiferet", "yesod"), ("tiferet", "hod"), ("netzach", "hod"), ("netzach", "yesod"), | |
| ("netzach", "malkuth"), ("hod", "yesod"), ("hod", "malkuth"), ("yesod", "malkuth")] | |
| ADJ = {s: [] for s in SEPH} | |
| for _i, (_a, _b) in enumerate(EDGES): | |
| ADJ[_a].append((_i, _b)) | |
| ADJ[_b].append((_i, _a)) | |
| OP_NODE = {"formula": "hod", "new_type": "hod", "table": "binah", "relation": "binah", "facts": "chesed", "refuse": "geburah", | |
| "sensor": "netzach"} | |
| MAX_LEN = 32 | |
| _CACHE: dict = {} | |
| def osub_seed(text, dim=D): | |
| k = (text, dim) | |
| v = _CACHE.get(k) | |
| if v is None: | |
| h = int(hashlib.sha256(text.lower().strip().encode()).hexdigest(), 16) | |
| rng = np.random.RandomState(h % (2 ** 31)) | |
| v = np.exp(1j * rng.uniform(0, 2 * np.pi, dim)).astype(np.complex64) | |
| if len(_CACHE) < 200000: | |
| _CACHE[k] = v | |
| return v | |
| def bind(a, b): | |
| return (a * b).astype(np.complex64) | |
| def unbind(c, b): | |
| return (c * np.conj(b)).astype(np.complex64) | |
| def sim(a, b): | |
| """cosine of a against a unit-phasor vector b (|b|^2 = D)""" | |
| return float(np.real(np.vdot(b, a))) / len(b) | |
| _K: dict = {} | |
| def _codes(dim): | |
| if dim not in _K: | |
| _K[dim] = (np.stack([osub_seed("o7lam:%d" % e, dim) for e in range(len(EDGES))]), | |
| [osub_seed("o7pos:%d" % p, dim) for p in range(MAX_LEN)]) | |
| return _K[dim] | |
| def walk_vec(word, dim=D): | |
| """the route as its spelled walk, at unit power""" | |
| if not word: | |
| return osub_seed("o7walk:empty", dim) | |
| Kc, Rc = _codes(dim) | |
| return (np.sum([bind(Kc[e], Rc[p]) for p, e in enumerate(word)], axis=0) / len(word) ** 0.5).astype(np.complex64) | |
| def decode_walk(v, n, start="malkuth", dim=D): | |
| """the best whole walk of n steps from start that the Tree allows, and its mean per-step similarity""" | |
| if n <= 0: | |
| return [], 0.0 | |
| Kc, Rc = _codes(dim) | |
| S = np.stack([np.real(Kc.conj() @ unbind(v, Rc[p])) / dim for p in range(n)]) | |
| best = {start: (0.0, [])} | |
| for p in range(n): | |
| nb = {} | |
| for node, (sc, path) in best.items(): | |
| for e, nxt in ADJ[node]: | |
| s2 = sc + S[p, e] | |
| if nxt not in nb or s2 > nb[nxt][0]: | |
| nb[nxt] = (s2, path + [e]) | |
| best = nb | |
| sc, path = max(best.values(), key=lambda x: x[0]) | |
| return path, sc / n | |
| def nodes_of(word, start="malkuth"): | |
| cur, out = start, [start] | |
| for e in word: | |
| a, b = EDGES[e] | |
| cur = b if cur == a else a | |
| out.append(cur) | |
| return out | |
| def operation_node(word): | |
| ns = nodes_of(word) | |
| side = [x for x in ns if x in SIDE] | |
| return side[-1] if side else ns[-1] | |
| STOP = set("a an the of to in on at for from by with and or is are was were be been what which who whom whose how when where why " | |
| "do does did can could would will should may might tell me give find work out please i my me our your it its this that " | |
| "these those there their then than as into about many much long get got".split()) | |
| def stem(w): | |
| w = w.lower().strip("'") | |
| for suf in ("ies", "es", "s", "ing", "ed"): | |
| if len(w) > len(suf) + 3 and w.endswith(suf): | |
| return w[: -len(suf)] + ("y" if suf == "ies" else "") | |
| return w | |
| def terms(text): | |
| return [stem(w) for w in re.findall(r"[A-Za-z][A-Za-z\-']+", str(text)) if w.lower() not in STOP and len(w) > 2] | |
| def key_vec(key, dim=D): | |
| """an exact key (a string) or an associative key ({term: weight}); unit total power either way""" | |
| if isinstance(key, str): | |
| return osub_seed("o7key:" + key, dim) | |
| tot = sum(w * w for w in key.values()) ** 0.5 or 1.0 | |
| return np.sum([(w / tot) * osub_seed("o7term:" + t, dim) for t, w in sorted(key.items())], axis=0).astype(np.complex64) | |
| def address(key): | |
| """the vector an exact key is filed in: its hash over the ten (they fill evenly)""" | |
| return SEPH[int(hashlib.sha256(("o7addr:" + key).encode()).hexdigest(), 16) % 10] | |
| def wkey(word): | |
| return "-".join(map(str, word)) if word else "empty" | |
| def _chain(prev, entry): | |
| """an entry's chain hash: its content (not its weight or recall count, which the metabolism changes) and the hash before""" | |
| body = json.dumps({k: entry[k] for k in sorted(entry) if k not in ("h", "prev", "w", "recalled")}, sort_keys=True, ensure_ascii=False) | |
| return hashlib.sha256((prev + body).encode()).hexdigest() | |
| class SpineMemory: | |
| """one memory (a specialist's, a group's or the commons'): ten vectors over an index of entries""" | |
| def __init__(self, name="memory", dim=D, max_entries=4096): | |
| self.name, self.dim, self.max_entries = name, dim, max_entries | |
| self.vec = {s: np.zeros(dim, np.complex64) for s in SEPH} | |
| self.vals = {s: {} for s in SEPH} # per vector: field -> values it has held (the cleanup codebook) | |
| self.walks = {s: {} for s in SEPH} # per vector: the walks it has held | |
| self.index = [] | |
| self.head = "0" * 64 | |
| # ---- encoding ------------------------------------------------------------------------------------------------------ | |
| def _fields(self, word, fields): | |
| f = {k: str(v) for k, v in (fields or {}).items()} | |
| f["status"] = "%s|%d" % (f.get("status", ""), len(word or [])) # status and length share one symbol | |
| return f | |
| def _value(self, word, fields): | |
| v = walk_vec(word, self.dim) | |
| for f, x in sorted(fields.items()): | |
| v = v + bind(osub_seed("o7role:" + f, self.dim), osub_seed("o7val:%s:%s" % (f, x), self.dim)) | |
| return v | |
| def _file(self, e): | |
| a = e["addr"] | |
| f = self._fields(e["word"], e["fields"]) | |
| for k, x in f.items(): | |
| vals = self.vals[a].setdefault(k, []) | |
| if x not in vals: | |
| vals.append(x) | |
| self.walks[a][wkey(e["word"])] = list(e["word"]) | |
| self.vec[a] = self.vec[a] + e["w"] * bind(key_vec(e["key"], self.dim), self._value(e["word"], f)) | |
| # ---- writing ------------------------------------------------------------------------------------------------------- | |
| def write(self, key, word=None, fields=None, node=None, weight=1.0, share=True, source=""): | |
| """file one VERIFIED outcome. An exact key is filed by its hash (node, if given, is kept as a field); an associative | |
| key is filed under node (required).""" | |
| fields = {k: str(v) for k, v in (fields or {}).items()} | |
| if isinstance(key, str): | |
| addr = address(key) | |
| if node: | |
| fields.setdefault("node", node) | |
| else: | |
| assert node in self.vec, "an associative key needs the node its operation lives at" | |
| addr = node | |
| e = {"key": key, "addr": addr, "word": list(word or []), "fields": fields, "w": float(weight), "share": bool(share), | |
| "source": source, "recalled": 0, "prev": self.head} | |
| e["h"] = _chain(self.head, e) | |
| self.head = e["h"] | |
| self.index.append(e) | |
| self._file(e) | |
| if len(self.index) > self.max_entries: | |
| self.consolidate(keep=self.max_entries) | |
| return e | |
| # ---- reading ------------------------------------------------------------------------------------------------------- | |
| def _clean(self, est, field, vals): | |
| sc = sorted(((x, sim(est, osub_seed("o7val:%s:%s" % (field, x), self.dim))) for x in vals), key=lambda t: -t[1]) | |
| return sc[0][0], sc[0][1], sc[0][1] - (sc[1][1] if len(sc) > 1 else 0.0) | |
| def _read(self, a, kv, route_margin=0.08, use_codebook=True): | |
| v = unbind(self.vec[a], kv) | |
| got, conf = {}, [] | |
| for f, vals in self.vals[a].items(): | |
| x, s, m = self._clean(unbind(v, osub_seed("o7role:" + f, self.dim)), f, vals) | |
| got[f] = x | |
| conf.append(min(s, m + (s if len(vals) == 1 else 0.0))) | |
| status, n = got.get("status", "|0").rsplit("|", 1) | |
| got["status"], n = status, int(n) | |
| sc = sorted(((w, float(np.real(np.vdot(walk_vec(w, self.dim), v))) / self.dim) for w in self.walks[a].values()), | |
| key=lambda t: -t[1]) if use_codebook else [] | |
| if sc and len(sc[0][0]) == n and (len(sc) == 1 or sc[0][1] - sc[1][1] >= route_margin): | |
| word, source = sc[0][0], "recognised" | |
| conf.append(sc[0][1]) | |
| else: | |
| word, _ = decode_walk(v, n, dim=self.dim) | |
| source = "decoded on the Tree" | |
| return {"word": word, "route": source, "fields": got, "confidence": round(min(conf) if conf else 0.0, 4), "vector": a} | |
| def recall(self, key, node=None, threshold=0.25, all_vectors=False, use_codebook=True): | |
| """the value filed under key, or None when nothing is clearly there. Exact keys read their own vector (all ten when | |
| all_vectors); associative keys read node's vector, or all ten and take the most confident.""" | |
| kv = key_vec(key, self.dim) | |
| if isinstance(key, str) and not all_vectors: | |
| cands = [address(key)] | |
| else: | |
| cands = [node] if (node and not all_vectors) else SEPH | |
| best = None | |
| for a in cands: | |
| if not self.vals[a]: | |
| continue | |
| r = self._read(a, kv, use_codebook=use_codebook) | |
| if best is None or r["confidence"] > best["confidence"]: | |
| best = r | |
| if best is None or best["confidence"] < threshold: | |
| return None | |
| return best | |
| def mark_recalled(self, key): | |
| for e in self.index: | |
| if e["key"] == key: | |
| e["recalled"] += 1 | |
| # ---- metabolism, groups, sharing ---------------------------------------------------------------------------------- | |
| def consolidate(self, keep=None, decay=0.98, boost=1.02): | |
| """weights decay unless recalled; keep the heaviest `keep`; rebuild the vectors from the index""" | |
| for e in self.index: | |
| e["w"] = round(e["w"] * (boost if e["recalled"] else decay), 6) | |
| e["recalled"] = 0 | |
| if keep and len(self.index) > keep: | |
| self.index = sorted(self.index, key=lambda e: -e["w"])[:keep] | |
| self.vec = {s: np.zeros(self.dim, np.complex64) for s in SEPH} | |
| self.vals = {s: {} for s in SEPH} | |
| self.walks = {s: {} for s in SEPH} | |
| for e in self.index: | |
| self._file(e) | |
| def group(name, members): | |
| """a group's memory: the sum of its members' vectors and codebooks (entries stay with their owners)""" | |
| g = SpineMemory(name, dim=members[0].dim) | |
| for m in members: | |
| for s in SEPH: | |
| g.vec[s] = g.vec[s] + m.vec[s] | |
| g.walks[s].update(m.walks[s]) | |
| for f, vals in m.vals[s].items(): | |
| for x in vals: | |
| if x not in g.vals[s].setdefault(f, []): | |
| g.vals[s][f].append(x) | |
| return g | |
| def export(self): | |
| """the shareable entries, each with its chain hash""" | |
| return {"name": self.name, "dim": self.dim, "head": self.head, | |
| "entries": [{k: e[k] for k in ("key", "addr", "word", "fields", "w", "share", "source", "prev", "h")} | |
| for e in self.index if e["share"]]} | |
| def verify(entries): | |
| """the entries whose content does not match their chain hash""" | |
| return [e["h"][:12] for e in entries if _chain(e["prev"], dict(e, recalled=0)) != e["h"]] | |
| def import_shared(self, export): | |
| bad = self.verify(export["entries"]) | |
| if bad: | |
| raise ValueError("entries fail their chain hash: %s" % ", ".join(bad)) | |
| for e in export["entries"]: | |
| node = e["addr"] if not isinstance(e["key"], str) else e["fields"].get("node") | |
| self.write(e["key"], e["word"], {k: v for k, v in e["fields"].items() if k != "node"} if isinstance(e["key"], str) else e["fields"], | |
| node=node, weight=e["w"], share=e["share"], source=export["name"]) | |
| return len(export["entries"]) | |