sayed125 commited on
Commit
151b1ec
·
verified ·
1 Parent(s): 9e9cb4c

Upload lhc_core.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. lhc_core.py +421 -0
lhc_core.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LHC-0 — Left-Hemisphere Cortex v0 (المرحلة A+B)
3
+ Layerless sparse recurrent architecture derived from left-hemisphere neuroanatomy.
4
+
5
+ Regions implemented (see left_hemisphere_model_design.md):
6
+ VWFA/Encoder : text -> sparse random-indexing codes
7
+ Wernicke/Hippocampus : associative engram memory (read / instant write)
8
+ Broca/VSA : compositional structure (binding ⊗, bundling ⊕, permutation π)
9
+ IPS/AG : symbolic workspace — arithmetic FACTS (angular gyrus) +
10
+ sequential PROCEDURES (IPS) with place-value decomposition
11
+ DLPFC : working memory stack + executive control (adaptive depth via time)
12
+ Basal Ganglia : winner-take-all action selection
13
+ ACC : confidence monitor (top1-top2 gap)
14
+ Cerebellum : forward predictor with delta-rule learning
15
+ Articulator : output emitter (v0: retrieves the response string)
16
+
17
+ No stacked layers. Depth = iterations through time. Pure NumPy.
18
+ """
19
+ import re
20
+ import time
21
+ import hashlib
22
+ from collections import OrderedDict
23
+
24
+ import numpy as np
25
+
26
+
27
+ # ============================================================
28
+ # 1. Encoder (VWFA / auditory) — Random Indexing over tokens
29
+ # ============================================================
30
+ class Encoder:
31
+ """Token -> sparse bipolar hypervector (hash-seeded). Text -> normalized sum."""
32
+
33
+ def __init__(self, N=20000, k_tok=64, seed=0):
34
+ self.N = N
35
+ self.k_tok = k_tok
36
+ self.seed = seed
37
+ self.cache = {}
38
+
39
+ def word_vec(self, token):
40
+ v = self.cache.get(token)
41
+ if v is None:
42
+ h = int(hashlib.md5((token + f"#{self.seed}").encode()).hexdigest()[:8], 16)
43
+ rng = np.random.RandomState(h % (2**31 - 1))
44
+ idx = rng.choice(self.N, self.k_tok, replace=False)
45
+ vals = rng.choice([-1.0, 1.0], self.k_tok)
46
+ v = np.zeros(self.N, dtype=np.float32)
47
+ v[idx] = vals
48
+ self.cache[token] = v
49
+ return v
50
+
51
+ @staticmethod
52
+ def tokenize(text):
53
+ return re.findall(r"\w+", text.lower(), flags=re.UNICODE)
54
+
55
+ def encode(self, text):
56
+ toks = self.tokenize(text)
57
+ if not toks:
58
+ return np.zeros(self.N, dtype=np.float32)
59
+ acc = np.zeros(self.N, dtype=np.float32)
60
+ for t in toks:
61
+ acc += self.word_vec(t)
62
+ n = np.linalg.norm(acc)
63
+ return acc / n if n > 0 else acc
64
+
65
+
66
+ # ============================================================
67
+ # 2. Memory (Wernicke read + Hippocampus write) — engram store
68
+ # ============================================================
69
+ class EngramMemory:
70
+ """Rows = engrams (cosine-indexed). Read = WTA over scores (Basal Ganglia).
71
+ Write = append instantly (no retraining -> lifelong memory)."""
72
+
73
+ def __init__(self, encoder: Encoder):
74
+ self.enc = encoder
75
+ self.codes = [] # list of np.float32 vectors
76
+ self.entries = [] # list of dicts (prompt, response, domain)
77
+ self._M = None # cached code matrix
78
+
79
+ def write(self, entry):
80
+ self.entries.append(entry)
81
+ self.codes.append(self.enc.encode(entry["prompt"]))
82
+ self._M = None
83
+
84
+ def _matrix(self):
85
+ if self._M is None:
86
+ self._M = np.stack(self.codes, axis=0)
87
+ return self._M
88
+
89
+ def read(self, query, top_k=1):
90
+ """Returns (entry, score, confidence) — confidence = gap(top1,top2) [ACC]."""
91
+ q = self.enc.encode(query)
92
+ M = self._matrix()
93
+ scores = M @ q
94
+ order = np.argsort(-scores)
95
+ top1 = float(scores[order[0]])
96
+ gap = float(top1 - scores[order[1]]) if len(order) > 1 else float(top1)
97
+ picks = [self.entries[int(i)] for i in order[:top_k]]
98
+ return (picks[0] if top_k == 1 else picks), top1, gap
99
+
100
+
101
+ # ============================================================
102
+ # 3. VSA (Broca) — binding, bundling, permutation, cleanup
103
+ # ============================================================
104
+ class VSA:
105
+ """Vector Symbolic Architecture: elementwise binding (⊗), additive bundling (⊕),
106
+ fixed permutation π for position. Bipolar vectors."""
107
+
108
+ def __init__(self, D=2048, seed=42):
109
+ self.D = D
110
+ self.rng = np.random.RandomState(seed)
111
+ self.perm = self.rng.permutation(D) # π
112
+ self.cache = {}
113
+
114
+ def vec(self, key):
115
+ v = self.cache.get(key)
116
+ if v is None:
117
+ h = int(hashlib.md5(f"vsa:{key}".encode()).hexdigest()[:8], 16)
118
+ r = np.random.RandomState(h % (2**31 - 1))
119
+ v = r.choice([-1.0, 1.0], self.D).astype(np.float32)
120
+ self.cache[key] = v
121
+ return v
122
+
123
+ @staticmethod
124
+ def bind(a, b): # a ⊗ b (elementwise, ±1 inverse = itself)
125
+ return a * b
126
+
127
+ @staticmethod
128
+ def bundle(*vs): # a ⊕ b ⊕ ...
129
+ return np.sum(vs, axis=0)
130
+
131
+ def permute(self, v, power=1):
132
+ idx = np.arange(self.D)
133
+ for _ in range(power):
134
+ idx = self.perm[idx]
135
+ return v[idx]
136
+
137
+ def structure_svo(self, agent, verb, patient):
138
+ """role-filler structure: agent⊗roleA ⊕ verb⊗roleV ⊕ patient⊗roleP"""
139
+ return self.bundle(
140
+ self.bind(self.vec(agent), self.vec("role:agent")),
141
+ self.bind(self.vec(verb), self.vec("role:verb")),
142
+ self.bind(self.vec(patient), self.vec("role:patient")),
143
+ )
144
+
145
+ def decode(self, structure, role, lexicon):
146
+ """Cleanup: invert binding with role, pick nearest known filler."""
147
+ probe = self.bind(structure, self.vec(role))
148
+ best, best_s = None, -2.0
149
+ for w in lexicon:
150
+ s = float(np.dot(probe, self.vec(w)))
151
+ if s > best_s:
152
+ best, best_s = w, s
153
+ return best, best_s
154
+
155
+ def similarity(self, s1, s2):
156
+ n1, n2 = np.linalg.norm(s1), np.linalg.norm(s2)
157
+ return float(np.dot(s1, s2) / (n1 * n2)) if n1 and n2 else 0.0
158
+
159
+
160
+ # ============================================================
161
+ # 4. Symbolic workspace (IPS procedures + AG fact memory) — BODMAS
162
+ # ============================================================
163
+ class SymbolicWorkspace:
164
+ """Human-like arithmetic:
165
+ - AG : rote FACTS for small operands (0..25)
166
+ - IPS : sequential PROCEDURES (place-value decomposition, carry/borrow,
167
+ division as multiplication-fact search) for larger operands
168
+ - DLPFC working-memory stack for parsing (shunting-yard)
169
+ Each fact lookup / decomposition step counts as 1 'time step' (depth through time).
170
+ """
171
+
172
+ FACT_MAX = 25
173
+
174
+ def __init__(self):
175
+ self.facts = {}
176
+ for a in range(self.FACT_MAX + 1):
177
+ for b in range(self.FACT_MAX + 1):
178
+ self.facts[("+", a, b)] = a + b
179
+ self.facts[("*", a, b)] = a * b
180
+ self.facts[("-", a, b)] = a - b
181
+ if b != 0 and a % b == 0:
182
+ self.facts[("/", a, b)] = a // b
183
+ self.steps = 0
184
+ self.wm = WorkingMemory(capacity=32)
185
+
186
+ # ---- IPS procedures -------------------------------------
187
+ def add(self, a, b):
188
+ self.steps += 1
189
+ if ("+", a, b) in self.facts:
190
+ return self.facts[("+", a, b)]
191
+ if a < 0 and b < 0:
192
+ return -self.add(-a, -b)
193
+ if a < 0 or b < 0:
194
+ return self.sub(max(a, b), -min(a, b))
195
+ ah, al = divmod(a, 10) # place-value decomposition
196
+ bh, bl = divmod(b, 10)
197
+ t = self.add(al, bl)
198
+ carry, low = divmod(t, 10)
199
+ high = self.add(self.add(ah, bh), carry)
200
+ return high * 10 + low
201
+
202
+ def sub(self, a, b):
203
+ self.steps += 1
204
+ if ("-", a, b) in self.facts:
205
+ return self.facts[("-", a, b)]
206
+ if a < 0 and b < 0: # sign handling FIRST
207
+ return self.sub(-b, -a)
208
+ if a < 0:
209
+ return -self.add(-a, b)
210
+ if b < 0:
211
+ return self.add(a, -b)
212
+ if b > a:
213
+ return -self.sub(b, a)
214
+ ah, al = divmod(a, 10) # borrow procedure (a,b >= 0)
215
+ bh, bl = divmod(b, 10)
216
+ if al < bl:
217
+ ah = self.sub(ah, 1)
218
+ al += 10
219
+ low = self.sub(al, bl)
220
+ high = self.sub(ah, bh)
221
+ return high * 10 + low
222
+
223
+ def mul(self, a, b):
224
+ self.steps += 1
225
+ if ("*", a, b) in self.facts:
226
+ return self.facts[("*", a, b)]
227
+ if a < 0 or b < 0:
228
+ s = -1 if (a < 0) ^ (b < 0) else 1
229
+ return s * self.mul(abs(a), abs(b))
230
+ if a < b:
231
+ return self.mul(b, a)
232
+ ah, al = divmod(a, 10) # distributive decomposition
233
+ return self.add(self.mul(ah, b) * 10, self.mul(al, b))
234
+
235
+ def div(self, a, b):
236
+ if b == 0:
237
+ raise ZeroDivisionError("BODMAS: division by zero")
238
+ self.steps += 1
239
+ if ("/", a, b) in self.facts:
240
+ return self.facts[("/", a, b)]
241
+ sign = -1 if (a < 0) ^ (b < 0) else 1
242
+ a, b = abs(a), abs(b)
243
+ if b <= self.FACT_MAX: # IPS sequential search (kid-like)
244
+ q, acc = 0, 0
245
+ while acc + b <= a:
246
+ acc = self.add(acc, b)
247
+ q = self.add(q, 1)
248
+ if acc != a:
249
+ return sign * (a // b) # inexact: floor (flagged by tests)
250
+ return sign * q
251
+ return sign * (a // b)
252
+
253
+ def pow_(self, a, b):
254
+ """Power via repeated multiplication (IPS-style). ^ binds tighter than */.
255
+ Right-associative: 2^3^2 = 2^(3^2)."""
256
+ if b < 0:
257
+ raise ValueError("BODMAS: negative exponent not supported")
258
+ self.steps += 1
259
+ if ("^", a, b) in self.facts:
260
+ return self.facts[("^", a, b)]
261
+ r = 1
262
+ for _ in range(b):
263
+ r = self.mul(r, a)
264
+ return r
265
+
266
+ # ---- DLPFC parser (shunting-yard -> RPN -> evaluation) ---
267
+ @staticmethod
268
+ def tokenize_expr(s):
269
+ """Numbers and operators; `**` is power; unary minus becomes (0 - x).
270
+ (v2 fix: `^` used to be silently dropped — '2^3' parsed as 2,3 !)"""
271
+ s = s.replace("×", "*").replace("÷", "/").replace("**", "^")
272
+ toks = re.findall(r"\d+|[+\-*/^()]", s)
273
+ out, prev = [], None
274
+ for t in toks:
275
+ if t in "+-" and (prev is None or prev in "(+-*/^u"):
276
+ if t == "-":
277
+ out.append("u") # unary minus -> negate operator
278
+ prev = "u" if t == "-" else prev # stay in unary context
279
+ if t == "+":
280
+ continue # unary plus is a no-op
281
+ continue
282
+ out.append(t)
283
+ prev = t
284
+ return out
285
+
286
+ def evaluate(self, expression):
287
+ """Full BODMAS pipeline. Returns (value, steps)."""
288
+ self.steps = 0
289
+ tokens = self.tokenize_expr(expression)
290
+ prec = {"+": 1, "-": 1, "*": 2, "/": 2, "u": 2.5, "^": 3}
291
+ out, ops = [], []
292
+ for t in tokens:
293
+ if t.isdigit():
294
+ out.append(int(t))
295
+ elif t == "u":
296
+ ops.append(t) # never pops (binds to its operand)
297
+ elif t in prec:
298
+ if t == "^": # right-associative
299
+ while ops and ops[-1] in prec and prec[ops[-1]] > prec[t]:
300
+ out.append(ops.pop())
301
+ else:
302
+ while ops and ops[-1] in prec and prec[ops[-1]] >= prec[t]:
303
+ out.append(ops.pop())
304
+ ops.append(t)
305
+ elif t == "(":
306
+ self.wm.push("(")
307
+ ops.append(t)
308
+ elif t == ")":
309
+ while ops and ops[-1] != "(":
310
+ out.append(ops.pop())
311
+ ops.pop()
312
+ self.wm.pop()
313
+ while ops:
314
+ out.append(ops.pop())
315
+ stack = []
316
+ for t in out:
317
+ if isinstance(t, int):
318
+ stack.append(t)
319
+ elif t == "u":
320
+ stack.append(self.sub(0, stack.pop()))
321
+ else:
322
+ b, a = stack.pop(), stack.pop()
323
+ stack.append(
324
+ {"+": self.add, "-": self.sub, "*": self.mul, "/": self.div,
325
+ "^": self.pow_}[t](a, b)
326
+ )
327
+ return stack[0], self.steps
328
+
329
+
330
+ class WorkingMemory:
331
+ """DLPFC working memory — fixed capacity stack."""
332
+
333
+ def __init__(self, capacity=32):
334
+ self.capacity = capacity
335
+ self.buf = []
336
+
337
+ def push(self, x):
338
+ if len(self.buf) >= self.capacity:
339
+ raise MemoryError("DLPFC working-memory overflow")
340
+ self.buf.append(x)
341
+
342
+ def pop(self):
343
+ return self.buf.pop() if self.buf else None
344
+
345
+
346
+ # ============================================================
347
+ # 5. Basal Ganglia — winner-take-all selection
348
+ # ============================================================
349
+ def wta(scores):
350
+ return int(np.argmax(scores))
351
+
352
+
353
+ # ============================================================
354
+ # 6. Cerebellum — forward predictor + delta-rule learning
355
+ # ============================================================
356
+ class Cerebellum:
357
+ """ŝ(t+1) = W_f · s(t); W_f ← W_f + η · e(t) · s(t)ᵀ (delta rule / SGD)."""
358
+
359
+ def __init__(self, D=256, lr=0.05, seed=7):
360
+ self.D = D
361
+ self.rng = np.random.RandomState(seed)
362
+ self.W = self.rng.randn(D, D) * 0.02
363
+ self.lr = lr
364
+
365
+ def predict(self, s):
366
+ return self.W @ s
367
+
368
+ def step(self, s, s_next):
369
+ e = s_next - self.predict(s)
370
+ self.W += self.lr * np.outer(e, s)
371
+ return float(np.mean(e**2))
372
+
373
+ @staticmethod
374
+ def make_dynamics(D=256, seed=11):
375
+ """Ground-truth world dynamics: fixed rotation + mixing (learnable)."""
376
+ rng = np.random.RandomState(seed)
377
+ Q = np.linalg.qr(rng.randn(D, D))[0]
378
+ return lambda s: Q @ s
379
+
380
+
381
+ # ============================================================
382
+ # 7. Articulator — output emitter (v0: speak the retrieved response)
383
+ # ============================================================
384
+ class Articulator:
385
+ def speak(self, text, delay=None):
386
+ for ch in text: # char-by-char emission (the 'mouth')
387
+ yield ch
388
+
389
+
390
+ # ============================================================
391
+ # The whole left hemisphere as ONE layerless system
392
+ # ============================================================
393
+ class LHC0:
394
+ def __init__(self, N=20000, kb=None, encoder=None):
395
+ self.encoder = encoder if encoder is not None else Encoder(N=N)
396
+ self.memory = EngramMemory(self.encoder)
397
+ self.vsa = VSA()
398
+ self.symbols = SymbolicWorkspace()
399
+ self.cerebellum = Cerebellum()
400
+ self.n_iters = 0
401
+ if kb:
402
+ for e in kb:
403
+ self.memory.write(e)
404
+
405
+ def think(self, query, top_k=1):
406
+ """One 'thought': encode -> read memory (WTA) -> ACC confidence gate."""
407
+ entry, score, conf = self.memory.read(query, top_k=top_k)
408
+ self.n_iters += 1
409
+ return entry, score, conf
410
+
411
+ def answer(self, query, conf_threshold=0.02):
412
+ entry, score, conf = self.think(query)
413
+ if conf < conf_threshold:
414
+ return {"status": "uncertain", "confidence": conf, "top_score": score}
415
+ speech = "".join(Articulator().speak(entry["response"]))
416
+ return {"status": "ok", "response": speech, "domain": entry.get("domain"),
417
+ "confidence": conf}
418
+
419
+ def compute(self, expression):
420
+ value, steps = self.symbols.evaluate(expression)
421
+ return {"expression": expression, "value": value, "steps": steps}