#!/usr/bin/env python3 """SQUIRCLE ROUTER v7 (round 8): the parts-built transformer of v6, completed on the three classes round 7's probe named. Round 7 (3/60): the heads attended to the head noun only, so a correct reply carried 20% of a long turn; 34 of 57 of Ben's turns are requests to do work, answered by a hole that said nothing but "no operation"; the reply was copied sentences. 1. MULTI-HEAD, AS DESIGNED: one head per typed relation of the demand. The frame's object, its topic and the referent each get their own query (that word's vector, blended half with the whole demand) and carry their own best value; values are deduplicated and kept only if they fit the whole demand >= TAU. A long turn is answered on each thing it names. 2. THE OPERATIONS HEAD: the same attention over Oracle7's own operations: every command of the head's help text and every operation in the catalogue, keyed by its own declared description. A request's query attends there. A read-only command runs (v4); one that changes state is offered as its command (v4); otherwise the nearest operation and its fit are named in the hole. 3. THE DECODER: the reply is written from the attended terms, not from the turn's words: what was understood (verb + object + topic from the frame), then the values or the operation's result, then, for a request no operation does, what Oracle7 would need to receive to do it (the constitution's first article: a hole says what is missing and the next turn can fill it). Nothing is written about any turn or topic. usage: module (SquircleRouterV7(..., reader=Reader))""" from __future__ import annotations import re import numpy as np from squircle_reply import content_words from squircle_reply_v4 import GENERIC from squircle_reply_v6 import SquircleRouterV6, unit, TAU, BETA, D OP_TAU = 0.30 MAX_HEADS = 3 class SquircleRouterV7(SquircleRouterV6): def __init__(self, *a, **k): super().__init__(*a, **k) self.op_rows = [("command", cmd, usage, desc) for cmd, usage, desc in self.rep] self.op_rows += [("operation", o.get("id", ""), o.get("id", ""), o.get("title", "")) for o in self.ops] self.OK = np.zeros((len(self.op_rows), D), dtype=np.float32) for i, (_, cmd, _, desc) in enumerate(self.op_rows): ws = content_words(desc + " " + cmd.replace("-", " ").replace(".", " ").replace("_", " ")) self.OK[i] = unit(self.text_vec(ws)) # ---------------- 2. the operations head def op_head(self, q): if self.OK.shape[0] == 0 or float(np.linalg.norm(q)) == 0: return None fit = self.OK @ q j = int(np.argmax(fit)) return (float(fit[j]),) + self.op_rows[j] if float(fit[j]) >= OP_TAU else None # ---------------- 1. multi-head over the store def headable(self, w): """a word can carry a head only if it is a real content word the store indexes and it is not common""" return (w.isalpha() and len(w) > 2 and not self.reader.is_closed(w) and w not in GENERIC and self.idf(w) >= 3.0 and bool(self.rec.inv.get(w)) and bool(self.reader.d.pos(w))) def heads(self, fr, wts, h, ref_words): groups = [] h = h if h and self.headable(h) else None if h: groups.append(("object", h)) for w in fr["topic"]: if w in wts and w != h and self.headable(w): groups.append(("topic", w)) break for r in ref_words: if self.headable(r): groups.append(("ref", r)) break rest = sorted((w for w in wts if w not in [g for _, g in groups] and self.headable(w)), key=lambda w: -wts[w] * self.idf(w)) for w in rest: if len(groups) >= MAX_HEADS: break groups.append(("turn", w)) return groups[:MAX_HEADS] def attend(self, q_turn, groups, words): el = self.eligible(words) if not el: return [] K = self.K[el].astype(np.float32) whole = K @ q_turn out, used = [], set() for kind, w in groups: qh = unit(0.5 * self.wv(w) + 0.5 * q_turn) fit = K @ qh fit = np.where(whole >= TAU, fit, -1.0) order = np.argsort(-fit)[:10] p = np.exp(BETA * (fit[order] - fit[order].max())) p /= p.sum() for j, pj in zip(order, p): i = el[j] if fit[j] < TAU or i in used: continue s, f, ws = self.rec.sents[i] if any(self.rec.sents[u][1] == f and len(ws & self.rec.sents[u][2]) > 3 for u in used): continue used.add(i) out.append((kind, w, float(fit[j]), i)) break return out # ---------------- 3. the decoder def understood(self, fr, h): obj = [w for w in fr["object"] if w not in ("it", "this", "that", "they", "them") and w.isalnum()] top = [w for w in fr["topic"] if w not in ("it", "this", "that") and w.isalnum()] bound = fr.get("bound", []) thing = " ".join(obj) or (" ".join(bound[:2]) if bound else (h or "")) return (fr["verb"] or "", thing, " ".join(top)) def decode(self, fr, h, vals, op): verb, thing, top = self.understood(fr, h) parts = [] for kind, w, fit, i in vals: s, f, _ = self.rec.sents[i] parts.append("On %s: %s (%s)" % (w, s.rstrip("."), f) + ".") body = " ".join(parts) if fr["mood"] in ("request", "commitment"): want = " ".join(x for x in [verb, thing, ("on " + top) if top else ""] if x).strip() or "that" lead = "You want me to %s." % want if op: fit, kind, cmd, usage, desc = op near = " The nearest operation I have is `%s` (%s), a fit of %.2f, which is not the same job." % ( usage if kind == "command" else cmd, desc[:120], fit) else: near = " None of my operations comes near it." th = re.sub(r"\s+itself$", "", thing or "thing to change") need = (" To do it I would need to receive the %s itself, or a part that acts on it; until then it stays an " "open hole, named for the builder." % th) return lead + (" " + body if body else "") + near + need if fr["mood"] == "question": return body or None return ("Noted. " + body) if body else None def candidates(self, turn, fr, session, cg, head): out = super(SquircleRouterV6, self).candidates(turn, fr, session, cg, head) # v4's ports (head, ledger, essay, commands) 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) fr["bound"] = list(dict.fromkeys(fr.get("bound", []) + ref_words))[:6] vals = self.attend(q_turn, self.heads(fr, wts, h, ref_words), list(wts)) if float(np.linalg.norm(q_turn)) > 0 else [] ran = any(sub in ("run", "commit", "essay", "ledger") for _, sub, _, _, _ in out) op = self.op_head(q_turn) if fr["mood"] in ("request", "commitment") and not ran else None if vals or (fr["mood"] in ("request", "commitment") and not ran): txt = self.decode(fr, h, vals, op) if txt: self.stats["decoded"] += 1 self.stats["heads_%d" % len(vals)] += 1 out = [c for c in out if c[1] != "hole"] out.append(("inform" if vals else "hole", "dec%d" % len(vals), txt, bool(vals), "")) if not vals and fr["mood"] not in ("request", "commitment"): d = self.ffn_define(h) if d: out.append(("inform", "ffn", d, True, "")) self.hist[session].append((q_turn if float(np.linalg.norm(q_turn)) > 0 else np.zeros(D, dtype=np.float32) + 1e-6, [w for w in sorted(wts, key=lambda x: -wts[x])][:6])) return out