sayed125 commited on
Commit
e08c63a
·
verified ·
1 Parent(s): f0bfa3f

Upload phase_e_callosum.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. phase_e_callosum.py +140 -0
phase_e_callosum.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Phase E — Corpus Callosum (الجسم الثفني): the bi-hemispheric bridge.
3
+
4
+ Right hemisphere : the REAL artifacts of `bi-hemispheric-brain-5m`
5
+ (superbrain_engram_matrix.npz = 243 engrams x 5,000,000
6
+ sparse neurons; knowledge_bank_superbrain.json).
7
+ Left hemisphere : LHC-0 (trained bilingual encoder + symbolic workspace).
8
+
9
+ The right hemisphere stores its engrams in a 5M-neuron coordinate system but
10
+ the original query encoder was never published -> the hemisphere is a SEALED
11
+ VAULT for new queries. The corpus callosum is a LEARNED translator between
12
+ the two coordinate systems:
13
+
14
+ e_left (128-d semantic) --W--> y_right (k-dim, k = neurons actually
15
+ used by the real rows, ≈3.6K)
16
+
17
+ fitted by dual ridge regression on the 243 (prompt, real-row) pairs.
18
+ Without the callosum the right hemisphere cannot be read at all (ablation).
19
+ """
20
+ import json
21
+
22
+ import numpy as np
23
+
24
+
25
+ class RightHemisphere:
26
+ """Reads the real engram matrix exactly as stored (CSR arrays)."""
27
+
28
+ def __init__(self, npz_path, kb_path):
29
+ z = np.load(npz_path, allow_pickle=True)
30
+ self.indptr = z["indptr"]
31
+ self.indices = z["indices"]
32
+ self.data = z["data"].astype(np.float32)
33
+ self.shape = tuple(z["shape"]) # (243, 5_000_000)
34
+ self.entries = json.load(open(kb_path, encoding="utf-8"))
35
+ assert len(self.entries) == self.shape[0], "rows must match KB"
36
+
37
+ # rows live in a small neuron subspace -> local coordinates
38
+ self.global_ids = np.unique(self.indices) # sorted unique neurons
39
+ remap = {int(g): i for i, g in enumerate(self.global_ids)}
40
+ self.k = len(self.global_ids)
41
+ self.Y = np.zeros((self.shape[0], self.k), dtype=np.float32)
42
+ for r in range(self.shape[0]):
43
+ s, e = self.indptr[r], self.indptr[r + 1]
44
+ for g, v in zip(self.indices[s:e], self.data[s:e]):
45
+ self.Y[r, remap[int(g)]] = v
46
+
47
+ def describe(self):
48
+ return {"rows": int(self.shape[0]), "neuron_space": int(self.shape[1]),
49
+ "active_neurons_used": int(self.k),
50
+ "stored_synapses": int(self.indices.size)}
51
+
52
+
53
+ class CorpusCallosum:
54
+ """Learned cross-space translator (kernel ridge / dual form):
55
+
56
+ A = (K + αI)^{-1} Y , K = X X^T (n×n, tiny)
57
+ ŷ(x) = (x · X^T) A (soft blend of learned columns)
58
+
59
+ X = left-hemisphere representation (sensory n-gram features work best:
60
+ both spaces are lexical at this scale; 128-d semantic also supported).
61
+ Stores X and A only — no giant W."""
62
+
63
+ def __init__(self, alpha=0.5):
64
+ self.alpha = alpha
65
+ self.X = self.A = None
66
+
67
+ def fit(self, X_left, Y_right):
68
+ X = np.asarray(X_left, dtype=np.float32)
69
+ n = X.shape[0]
70
+ K = X @ X.T + self.alpha * np.eye(n, dtype=np.float32)
71
+ self.A = np.linalg.solve(K, Y_right.astype(np.float32)) # (n, k)
72
+ self.X = X
73
+ return self
74
+
75
+ def translate(self, x_left):
76
+ sims = np.asarray(x_left, dtype=np.float32) @ self.X.T # (n,)
77
+ y = sims @ self.A # (k,)
78
+ n = float(np.linalg.norm(y))
79
+ return y / n if n > 0 else y
80
+
81
+ def translate_batch(self, X):
82
+ sims = np.asarray(X, dtype=np.float32) @ self.X.T # (m, n)
83
+ Y = sims @ self.A
84
+ norms = np.linalg.norm(Y, axis=1, keepdims=True)
85
+ return Y / np.maximum(norms, 1e-8)
86
+
87
+
88
+ class BiCallosum:
89
+ """The real corpus callosum carries TWO streams (Hickok & Poeppel dual-stream
90
+ language model):
91
+ • dorsal channel: sensory lexical features -> right codes (precision)
92
+ • ventral channel: semantic embeddings -> right codes (meaning, cross-lingual)
93
+ Right-hemisphere score = average of both channels' normalized scores."""
94
+
95
+ def __init__(self, alpha=0.5):
96
+ self.dorsal = CorpusCallosum(alpha) # features (n-grams)
97
+ self.ventral = CorpusCallosum(alpha) # 128-d semantic
98
+
99
+ def fit(self, X_feat, E_sem, Y_right):
100
+ self.dorsal.fit(X_feat, Y_right)
101
+ self.ventral.fit(E_sem, Y_right)
102
+ return self
103
+
104
+ def right_scores(self, x_feat, e_sem, Y_right):
105
+ """Each channel votes with its confidence weight (top1−top2 gap) —
106
+ Basal-Ganglia/ACC style selection between the two callosal streams."""
107
+ def gap(s):
108
+ s2 = np.sort(s)[::-1]
109
+ if len(s2) < 2:
110
+ return 1.0
111
+ span = float(s2[0] - s2[-1]) + 1e-6 # scale-invariant
112
+ return float(s2[0] - s2[1]) / span
113
+ Yn = Y_right / np.maximum(np.linalg.norm(Y_right, axis=1, keepdims=True), 1e-8)
114
+ s_d = self.dorsal.translate(x_feat) @ Yn.T
115
+ s_v = self.ventral.translate(e_sem) @ Yn.T
116
+ g_d, g_v = gap(s_d) + 1e-6, gap(s_v) + 1e-6
117
+ return (g_d * s_d + g_v * s_v) / (g_d + g_v)
118
+
119
+
120
+ def right_scores(callosal_codes, Y_right):
121
+ """cosine scores of a translated code against the real engram rows."""
122
+ Yn = Y_right / np.maximum(np.linalg.norm(Y_right, axis=1, keepdims=True), 1e-8)
123
+ return callosal_codes @ Yn.T
124
+
125
+
126
+ def fuse(s_left, s_right, has_right=None, lam=0.5):
127
+ """Confidence-weighted fusion (ACC-style): each hemisphere votes with its
128
+ top1−top2 gap; entries the right hemisphere never stored vote left-only."""
129
+ def gap(s):
130
+ s2 = np.sort(s)[::-1]
131
+ if len(s2) < 2:
132
+ return 1.0
133
+ span = float(s2[0] - s2[-1]) + 1e-6 # scale-invariant
134
+ return float(s2[0] - s2[1]) / span
135
+ if has_right is None:
136
+ has_right = np.ones(len(s_left), dtype=bool)
137
+ g_l = gap(s_left) + 1e-6
138
+ g_r = (gap(s_right) + 1e-6) * has_right.astype(np.float64)
139
+ w = g_l + g_r
140
+ return (g_l * s_left + g_r * s_right) / w