Upload lhc_core.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421"""LHC-0 — Left-Hemisphere Cortex v0 (المرحلة A+B)Layerless sparse recurrent architecture derived from left-hemisphere neuroanatomy.
Regions implemented (see left_hemisphere_model_design.md): VWFA/Encoder : text -> sparse random-indexing codes Wernicke/Hippocampus : associative engram memory (read / instant write) Broca/VSA : compositional structure (binding ⊗, bundling ⊕, permutation π) IPS/AG : symbolic workspace — arithmetic FACTS (angular gyrus) + sequential PROCEDURES (IPS) with place-value decomposition DLPFC : working memory stack + executive control (adaptive depth via time) Basal Ganglia : winner-take-all action selection ACC : confidence monitor (top1-top2 gap) Cerebellum : forward predictor with delta-rule learning Articulator : output emitter (v0: retrieves the response string)
No stacked layers. Depth = iterations through time. Pure NumPy."""import reimport timeimport hashlibfrom collections import OrderedDict
import numpy as np
# ============================================================# 1. Encoder (VWFA / auditory) — Random Indexing over tokens# ============================================================class Encoder: """Token -> sparse bipolar hypervector (hash-seeded). Text -> normalized sum."""
def __init__(self, N=20000, k_tok=64, seed=0): self.N = N self.k_tok = k_tok self.seed = seed self.cache = {}
def word_vec(self, token): v = self.cache.get(token) if v is None: h = int(hashlib.md5((token + f"#{self.seed}").encode()).hexdigest()[:8], 16) rng = np.random.RandomState(h % (2**31 - 1)) idx = rng.choice(self.N, self.k_tok, replace=False) vals = rng.choice([-1.0, 1.0], self.k_tok) v = np.zeros(self.N, dtype=np.float32) v[idx] = vals self.cache[token] = v return v
@staticmethod def tokenize(text): return re.findall(r"\w+", text.lower(), flags=re.UNICODE)
def encode(self, text): toks = self.tokenize(text) if not toks: return np.zeros(self.N, dtype=np.float32) acc = np.zeros(self.N, dtype=np.float32) for t in toks: acc += self.word_vec(t) n = np.linalg.norm(acc) return acc / n if n > 0 else acc
# ============================================================# 2. Memory (Wernicke read + Hippocampus write) — engram store# ============================================================class EngramMemory: """Rows = engrams (cosine-indexed). Read = WTA over scores (Basal Ganglia). Write = append instantly (no retraining -> lifelong memory)."""
def __init__(self, encoder: Encoder): self.enc = encoder self.codes = [] # list of np.float32 vectors self.entries = [] # list of dicts (prompt, response, domain) self._M = None # cached code matrix
def write(self, entry): self.entries.append(entry) self.codes.append(self.enc.encode(entry["prompt"])) self._M = None
def _matrix(self): if self._M is None: self._M = np.stack(self.codes, axis=0) return self._M
def read(self, query, top_k=1): """Returns (entry, score, confidence) — confidence = gap(top1,top2) [ACC].""" q = self.enc.encode(query) M = self._matrix() scores = M @ q order = np.argsort(-scores) top1 = float(scores[order[0]]) gap = float(top1 - scores[order[1]]) if len(order) > 1 else float(top1) picks = [self.entries[int(i)] for i in order[:top_k]] return (picks[0] if top_k == 1 else picks), top1, gap
# ============================================================# 3. VSA (Broca) — binding, bundling, permutation, cleanup# ============================================================class VSA: """Vector Symbolic Architecture: elementwise binding (⊗), additive bundling (⊕), fixed permutation π for position. Bipolar vectors."""
def __init__(self, D=2048, seed=42): self.D = D self.rng = np.random.RandomState(seed) self.perm = self.rng.permutation(D) # π self.cache = {}
def vec(self, key): v = self.cache.get(key) if v is None: h = int(hashlib.md5(f"vsa:{key}".encode()).hexdigest()[:8], 16) r = np.random.RandomState(h % (2**31 - 1)) v = r.choice([-1.0, 1.0], self.D).astype(np.float32) self.cache[key] = v return v
@staticmethod def bind(a, b): # a ⊗ b (elementwise, ±1 inverse = itself) return a * b
@staticmethod def bundle(*vs): # a ⊕ b ⊕ ... return np.sum(vs, axis=0)
def permute(self, v, power=1): idx = np.arange(self.D) for _ in range(power): idx = self.perm[idx] return v[idx]
def structure_svo(self, agent, verb, patient): """role-filler structure: agent⊗roleA ⊕ verb⊗roleV ⊕ patient⊗roleP""" return self.bundle( self.bind(self.vec(agent), self.vec("role:agent")), self.bind(self.vec(verb), self.vec("role:verb")), self.bind(self.vec(patient), self.vec("role:patient")), )
def decode(self, structure, role, lexicon): """Cleanup: invert binding with role, pick nearest known filler.""" probe = self.bind(structure, self.vec(role)) best, best_s = None, -2.0 for w in lexicon: s = float(np.dot(probe, self.vec(w))) if s > best_s: best, best_s = w, s return best, best_s
def similarity(self, s1, s2): n1, n2 = np.linalg.norm(s1), np.linalg.norm(s2) return float(np.dot(s1, s2) / (n1 * n2)) if n1 and n2 else 0.0
# ============================================================# 4. Symbolic workspace (IPS procedures + AG fact memory) — BODMAS# ============================================================class SymbolicWorkspace: """Human-like arithmetic: - AG : rote FACTS for small operands (0..25) - IPS : sequential PROCEDURES (place-value decomposition, carry/borrow, division as multiplication-fact search) for larger operands - DLPFC working-memory stack for parsing (shunting-yard) Each fact lookup / decomposition step counts as 1 'time step' (depth through time). """
FACT_MAX = 25
def __init__(self): self.facts = {} for a in range(self.FACT_MAX + 1): for b in range(self.FACT_MAX + 1): self.facts[("+", a, b)] = a + b self.facts[("*", a, b)] = a * b self.facts[("-", a, b)] = a - b if b != 0 and a % b == 0: self.facts[("/", a, b)] = a // b self.steps = 0 self.wm = WorkingMemory(capacity=32)
# ---- IPS procedures ------------------------------------- def add(self, a, b): self.steps += 1 if ("+", a, b) in self.facts: return self.facts[("+", a, b)] if a < 0 and b < 0: return -self.add(-a, -b) if a < 0 or b < 0: return self.sub(max(a, b), -min(a, b)) ah, al = divmod(a, 10) # place-value decomposition bh, bl = divmod(b, 10) t = self.add(al, bl) carry, low = divmod(t, 10) high = self.add(self.add(ah, bh), carry) return high * 10 + low
def sub(self, a, b): self.steps += 1 if ("-", a, b) in self.facts: return self.facts[("-", a, b)] if a < 0 and b < 0: # sign handling FIRST return self.sub(-b, -a) if a < 0: return -self.add(-a, b) if b < 0: return self.add(a, -b) if b > a: return -self.sub(b, a) ah, al = divmod(a, 10) # borrow procedure (a,b >= 0) bh, bl = divmod(b, 10) if al < bl: ah = self.sub(ah, 1) al += 10 low = self.sub(al, bl) high = self.sub(ah, bh) return high * 10 + low
def mul(self, a, b): self.steps += 1 if ("*", a, b) in self.facts: return self.facts[("*", a, b)] if a < 0 or b < 0: s = -1 if (a < 0) ^ (b < 0) else 1 return s * self.mul(abs(a), abs(b)) if a < b: return self.mul(b, a) ah, al = divmod(a, 10) # distributive decomposition return self.add(self.mul(ah, b) * 10, self.mul(al, b))
def div(self, a, b): if b == 0: raise ZeroDivisionError("BODMAS: division by zero") self.steps += 1 if ("/", a, b) in self.facts: return self.facts[("/", a, b)] sign = -1 if (a < 0) ^ (b < 0) else 1 a, b = abs(a), abs(b) if b <= self.FACT_MAX: # IPS sequential search (kid-like) q, acc = 0, 0 while acc + b <= a: acc = self.add(acc, b) q = self.add(q, 1) if acc != a: return sign * (a // b) # inexact: floor (flagged by tests) return sign * q return sign * (a // b)
def pow_(self, a, b): """Power via repeated multiplication (IPS-style). ^ binds tighter than */. Right-associative: 2^3^2 = 2^(3^2).""" if b < 0: raise ValueError("BODMAS: negative exponent not supported") self.steps += 1 if ("^", a, b) in self.facts: return self.facts[("^", a, b)] r = 1 for _ in range(b): r = self.mul(r, a) return r
# ---- DLPFC parser (shunting-yard -> RPN -> evaluation) --- @staticmethod def tokenize_expr(s): """Numbers and operators; `**` is power; unary minus becomes (0 - x). (v2 fix: `^` used to be silently dropped — '2^3' parsed as 2,3 !)""" s = s.replace("×", "*").replace("÷", "/").replace("**", "^") toks = re.findall(r"\d+|[+\-*/^()]", s) out, prev = [], None for t in toks: if t in "+-" and (prev is None or prev in "(+-*/^u"): if t == "-": out.append("u") # unary minus -> negate operator prev = "u" if t == "-" else prev # stay in unary context if t == "+": continue # unary plus is a no-op continue out.append(t) prev = t return out
def evaluate(self, expression): """Full BODMAS pipeline. Returns (value, steps).""" self.steps = 0 tokens = self.tokenize_expr(expression) prec = {"+": 1, "-": 1, "*": 2, "/": 2, "u": 2.5, "^": 3} out, ops = [], [] for t in tokens: if t.isdigit(): out.append(int(t)) elif t == "u": ops.append(t) # never pops (binds to its operand) elif t in prec: if t == "^": # right-associative while ops and ops[-1] in prec and prec[ops[-1]] > prec[t]: out.append(ops.pop()) else: while ops and ops[-1] in prec and prec[ops[-1]] >= prec[t]: out.append(ops.pop()) ops.append(t) elif t == "(": self.wm.push("(") ops.append(t) elif t == ")": while ops and ops[-1] != "(": out.append(ops.pop()) ops.pop() self.wm.pop() while ops: out.append(ops.pop()) stack = [] for t in out: if isinstance(t, int): stack.append(t) elif t == "u": stack.append(self.sub(0, stack.pop())) else: b, a = stack.pop(), stack.pop() stack.append( {"+": self.add, "-": self.sub, "*": self.mul, "/": self.div, "^": self.pow_}[t](a, b) ) return stack[0], self.steps
class WorkingMemory: """DLPFC working memory — fixed capacity stack."""
def __init__(self, capacity=32): self.capacity = capacity self.buf = []
def push(self, x): if len(self.buf) >= self.capacity: raise MemoryError("DLPFC working-memory overflow") self.buf.append(x)
def pop(self): return self.buf.pop() if self.buf else None
# ============================================================# 5. Basal Ganglia — winner-take-all selection# ============================================================def wta(scores): return int(np.argmax(scores))
# ============================================================# 6. Cerebellum — forward predictor + delta-rule learning# ============================================================class Cerebellum: """ŝ(t+1) = W_f · s(t); W_f ← W_f + η · e(t) · s(t)ᵀ (delta rule / SGD)."""
def __init__(self, D=256, lr=0.05, seed=7): self.D = D self.rng = np.random.RandomState(seed) self.W = self.rng.randn(D, D) * 0.02 self.lr = lr
def predict(self, s): return self.W @ s
def step(self, s, s_next): e = s_next - self.predict(s) self.W += self.lr * np.outer(e, s) return float(np.mean(e**2))
@staticmethod def make_dynamics(D=256, seed=11): """Ground-truth world dynamics: fixed rotation + mixing (learnable).""" rng = np.random.RandomState(seed) Q = np.linalg.qr(rng.randn(D, D))[0] return lambda s: Q @ s
# ============================================================# 7. Articulator — output emitter (v0: speak the retrieved response)# ============================================================class Articulator: def speak(self, text, delay=None): for ch in text: # char-by-char emission (the 'mouth') yield ch
# ============================================================# The whole left hemisphere as ONE layerless system# ============================================================class LHC0: def __init__(self, N=20000, kb=None, encoder=None): self.encoder = encoder if encoder is not None else Encoder(N=N) self.memory = EngramMemory(self.encoder) self.vsa = VSA() self.symbols = SymbolicWorkspace() self.cerebellum = Cerebellum() self.n_iters = 0 if kb: for e in kb: self.memory.write(e)
def think(self, query, top_k=1): """One 'thought': encode -> read memory (WTA) -> ACC confidence gate.""" entry, score, conf = self.memory.read(query, top_k=top_k) self.n_iters += 1 return entry, score, conf
def answer(self, query, conf_threshold=0.02): entry, score, conf = self.think(query) if conf < conf_threshold: return {"status": "uncertain", "confidence": conf, "top_score": score} speech = "".join(Articulator().speak(entry["response"])) return {"status": "ok", "response": speech, "domain": entry.get("domain"), "confidence": conf}
def compute(self, expression): value, steps = self.symbols.evaluate(expression) return {"expression": expression, "value": value, "steps": steps}lhc_core.pyAdded+421