oracle7 / workbench /converse /squircle_reply_v6.py
psiloceyeben's picture
Release 12.0 (full): one browser harness that converses, writes from held sources and builds what you describe, keeping each request through corrections and restarts. No language model. (part 4)
04e89f2 verified
Raw History Blame Contribute Delete
12.5 kB
#!/usr/bin/env python3
"""SQUIRCLE ROUTER v6 (round 7): THE TRANSFORMER MADE OF ORACLE7'S PARTS, applied to conversation. Built to the table set
down on 2026-11-06 (Ben: "modularize everything, including transformers"; "the oracle7 parts that make up a transformer"):
transformer step Oracle7 part, here
query the turn's demand: the reader's frame (head noun weighted, wanted object, topic), as an HRR vector
key each element's declared face: a record sentence's or an earlier turn's own words, as an HRR vector
score the fit (cosine of query and key), with Oracle7's graph as the mask: only elements reached through
the store's index from the demand's words or their glosses are eligible
softmax the selector, w = softmax(beta * fit)
value a record from the store (cited), or an earlier turn of this conversation
weighted sum HRR superposition of the selected values into the state; a value that does not agree with the
superposed state is not carried (coherence)
multi-head typed relations, one head each: REF (what it/this/that points at in the conversation), ABOUT-HEAD
(the frame's head noun), ABOUT-TURN (the whole demand)
feed-forward the store's tables: a word's gloss in the head's own dictionary, the work ledger, the commands
residual stream common ground: the state of the conversation, written back after every layer
positional encoding HRR position roles: earlier turns are bound to their distance, M = sum bind(P_d, v_d), and read back
by unbinding
layers hops: L1 resolves reference (REF head over M) and writes the referent into the residual; L2 attends
the store with the two ABOUT heads; L3 is the act: the squircle (v4) ports compete with the attended
values, and the inverted squircle reads every candidate back.
Word vectors are not trained: a word is its own seeded atom plus half the superposed atoms of its first gloss in the head's
own dictionary, so words that define each other meet. Nothing is written about any turn or topic.
usage: module (SquircleRouterV6(..., reader=Reader))"""
from __future__ import annotations
import collections
import hashlib
import re
import numpy as np
from squircle_reply import content_words
from squircle_reply_v4 import SquircleRouterV4, COVER, GENERIC
D = 512
BETA = 14.0
TAU = 0.22 # a value must fit the demand at least this well to be carried
REF_W = 0.8 # how much of the referent the REF head writes into the query
MAX_VALUES = 2
MAX_ELIG = 4000
POS_MAX = 6
def atom(w):
h = int.from_bytes(hashlib.sha256(("osub:" + w).encode()).digest()[:8], "little")
return np.random.default_rng(h).standard_normal(D).astype(np.float32) / np.sqrt(D)
def bind(a, b):
return np.fft.irfft(np.fft.rfft(a) * np.fft.rfft(b), n=D).astype(np.float32)
def unbind(m, a):
return np.fft.irfft(np.fft.rfft(m) * np.conj(np.fft.rfft(a)), n=D).astype(np.float32)
def unit(v):
n = float(np.linalg.norm(v))
return v / n if n > 1e-9 else v
class SquircleRouterV6(SquircleRouterV4):
def __init__(self, *a, **k):
super().__init__(*a, **k)
self._wv = {}
self._glw = {}
self.P = [atom("position:%d" % i) for i in range(POS_MAX + 1)]
self.hist = collections.defaultdict(list) # session -> [(vector, words)] for earlier turns
# keys of every record sentence (computed once from the store)
sents = self.rec.sents
self.K = np.zeros((len(sents), D), dtype=np.float16)
for i, (_, _, ws) in enumerate(sents):
self.K[i] = unit(self.text_vec(ws)).astype(np.float16)
self.ginv = collections.defaultdict(set) # gloss word -> words it defines (the graph mask's second hop)
self.stats = collections.Counter()
# ---------------- word and text vectors from the store
def gloss_words(self, w):
if w not in self._glw:
out = []
try:
for pos, gs in self.reader.d.entries(w):
if pos in ("noun", "verb", "adj", "adv", "name") and gs:
g = gs[0]
if not re.search(r"\b(?:spelling|plural|past|participle|form) of\b", g, re.I):
out = [x for x in content_words(g) if x != w][:8]
break
except Exception: # noqa: BLE001
out = []
self._glw[w] = out
return self._glw[w]
def wv(self, w):
if w not in self._wv:
v = atom(w)
gw = self.gloss_words(w)
if gw:
v = v + 0.5 * unit(sum(atom(g) for g in gw))
self._wv[w] = unit(v)
return self._wv[w]
def idf(self, w):
return self.rec.idf.get(w, 6.0)
def text_vec(self, words, weights=None):
v = np.zeros(D, dtype=np.float32)
for w in words:
if w in GENERIC:
continue
v += (weights.get(w, 1.0) if weights else 1.0) * self.idf(w) * self.wv(w)
return v
# ---------------- the query: the turn's demand
def head_noun(self, fr):
obj = [w for w in fr["object"] if w.isalpha() and w not in ("it", "this", "that", "they", "them")
and not self.reader.is_closed(w) and w not in GENERIC]
for w in reversed(obj):
if "noun" in self.reader.d.pos(w):
return w
return obj[-1] if obj else None
def demand(self, turn, fr):
wts = {}
for w in content_words(fr["fixed"] or turn):
if w not in GENERIC and not self.reader.is_closed(w) and len(w) > 2:
wts[w] = 0.5
for w in fr["topic"]:
if w.isalpha() and not self.reader.is_closed(w):
wts[w] = 1.5
for w in fr["object"]:
if w.isalpha() and not self.reader.is_closed(w) and w not in GENERIC:
wts[w] = max(wts.get(w, 0), 1.0)
h = self.head_noun(fr)
if h:
wts[h] = 2.0
return wts, h
# ---------------- L1: the REF head over the positional memory (common ground)
def ref_head(self, session, q, fr, wts):
H = self.hist[session][-POS_MAX:]
needs = bool(fr["refs"]) or sum(1 for w in wts if wts[w] >= 1.0) == 0 or re.search(
r"\b(?:it|its|it's|this|that|these|those|they|them)\b", fr["fixed"].lower())
if not H or not needs:
return q, []
M = np.zeros(D, dtype=np.float32)
for d, (v, _) in enumerate(reversed(H), start=1):
M += bind(self.P[d], v)
reads = []
for d in range(1, len(H) + 1):
r = unit(unbind(M, self.P[d]))
fits = [float(np.dot(r, unit(v))) for v, _ in H] # clean-up: which stored turn this read-back is
j = int(np.argmax(fits))
# the REF head's query is the turn itself: a read-back scores by its fit to what was just said, then distance
reads.append((fits[j] + 0.6 * float(np.dot(unit(q), unit(H[j][0]))) - 0.08 * d, H[j]))
sc = np.array([s for s, _ in reads])
w = np.exp(BETA * 0.25 * (sc - sc.max()))
w /= w.sum()
ref = sum(wi * unit(v) for wi, (_, (v, _)) in zip(w, reads))
best = reads[int(np.argmax(w))][1]
self.stats["ref_used"] += 1
return unit(q + REF_W * unit(ref) * max(float(np.linalg.norm(q)), 1.0)), [x for x in best[1] if x not in GENERIC][:4]
# ---------------- L2: the ABOUT heads over the store, graph-masked
def eligible(self, words):
el = set()
for w in words:
el.update(self.rec.inv.get(w, ())[:1500])
for g in self.gloss_words(w)[:4]:
if self.idf(g) >= 4.0:
el.update(self.rec.inv.get(g, ())[:300])
return sorted(el)[:MAX_ELIG]
def about_heads(self, q_turn, q_head, words):
el = self.eligible(words)
if not el:
return []
K = self.K[el].astype(np.float32)
fit = 0.6 * (K @ q_head) + 0.4 * (K @ q_turn) if q_head is not None else K @ q_turn
top = np.argsort(-fit)[:40]
f = fit[top]
w = np.exp(BETA * (f - f.max()))
w /= w.sum()
out = []
for j, wi in zip(top, w):
if float(fit[j]) < TAU:
break
out.append((float(wi), float(fit[j]), el[j]))
return out
def superpose(self, vals, q):
"""weighted sum: the state is the superposition of the selected values; a value that disagrees with it is dropped"""
if not vals:
return []
state = unit(sum(wi * self.K[i].astype(np.float32) for wi, _, i in vals[:6]))
kept, files = [], set()
for wi, fi, i in vals:
s, f, _ = self.rec.sents[i]
if f in files and len(kept) >= 1:
continue
agree = float(np.dot(state, self.K[i].astype(np.float32)))
if kept and agree < 0.6 * kept[0][3]:
continue
kept.append((wi, fi, i, agree))
files.add(f)
if len(kept) >= MAX_VALUES:
break
return kept
# ---------------- feed-forward: the dictionary table, for a head the store does not hold
def ffn_define(self, h):
if not h or self.idf(h) < 6.0:
return None
for pos, gs in self.reader.d.entries(h):
if pos in ("noun", "verb", "adj", "name") and gs:
g = gs[0]
if not re.search(r"\b(?:spelling|plural|past|participle|form) of\b", g, re.I):
return "%s: %s" % (h, g.rstrip(".") + ".")
return None
# ---------------- L3: the act, with the attended values as one more port
def speak(self, fr, h, kept, ref_words):
about = h or (ref_words[0] if ref_words else None)
body = " ".join("%s (%s)" % (self.rec.sents[i][0], self.rec.sents[i][1]) for _, _, i, _ in kept)
lead = {"question": "On %s, what I hold: " % about if about else "What I hold: ",
"request": "On %s, what I hold: " % about if about else "What I hold: ",
"commitment": "On %s, what I hold: " % about if about else "What I hold: "}.get(
fr["mood"], ("On %s: " % about) if about else "")
tail = ""
if fr["mood"] in ("request", "commitment"):
tail = " No operation of mine does %s yet; that goes to the builder as a named hole." % (
" ".join(x for x in [fr["verb"] or "", h or ""] if x) or "that")
return lead + body + tail
def candidates(self, turn, fr, session, cg, head):
out = super().candidates(turn, fr, session, cg, head)
wts, h = self.demand(turn, fr)
words = list(wts)
q_turn = unit(self.text_vec(words, wts)) if words else np.zeros(D, dtype=np.float32)
q_turn, ref_words = self.ref_head(session, q_turn, fr, wts) if words or self.hist[session] else (q_turn, [])
for w in ref_words:
wts.setdefault(w, 1.0)
q_head = unit(self.wv(h) + (0.5 * unit(self.text_vec(ref_words)) if ref_words else 0)) if h else (
unit(self.text_vec(ref_words)) if ref_words else None)
fr["bound"] = list(dict.fromkeys(fr.get("bound", []) + ref_words))[:6]
vals = self.about_heads(q_turn, q_head, list(wts)) if float(np.linalg.norm(q_turn)) > 0 else []
kept = self.superpose(vals, q_turn)
if kept:
self.stats["attended"] += 1
out.append(("inform", "attn%d" % len(kept), self.speak(fr, h, kept, ref_words), True, ""))
else:
d = self.ffn_define(h)
if d:
self.stats["ffn"] += 1
out.append(("inform", "ffn", d, True, ""))
# residual: write this turn's demand (with its referent) into the common ground
self.hist[session].append((q_turn if float(np.linalg.norm(q_turn)) > 0 else atom("empty"),
[w for w in sorted(wts, key=lambda x: -wts[x])][:6]))
return out