File size: 14,004 Bytes
3f51d96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
#!/usr/bin/env python3
"""tablinum_loop_engine.py - Hierarchical centroid router, atom-then-expand store, and Mode A loop proxy.

Implements the three software-side pillars of Tablinum-Loop (schema: 2):
  1. HierarchicalTableRouter : K centroids per table in 256-d normalized embedding space (O(1) table scaling).
  2. AtomStore               : Compact 40-80 token fact atoms for Pass 1 with optional parent-passage expansion.
  3. TwoStageEngramLoop      : Adaptive Pass-1 draft/early-exit -> targeted fetch -> Pass-2 grounded synthesis.
"""
import argparse, json, re, time, urllib.request
from dataclasses import dataclass
from typing import Callable, Dict, List, Optional, Sequence, Tuple
import numpy as np


def _l2_normalize(x: np.ndarray) -> np.ndarray:
    norm = np.linalg.norm(x, axis=-1, keepdims=True)
    return x / np.maximum(norm, 1e-12)


@dataclass
class TableRoute:
    table: str
    score: float
    centroid_idx: int


class HierarchicalTableRouter:
    """Routes a query embedding to top-M tables using K centroids per table."""

    def __init__(self, tables: Sequence[str], centroids: np.ndarray, k_per_table: int):
        """
        Args:
            tables: Ordered table names of length N.
            centroids: Normalized float32 array of shape [N, K, D].
            k_per_table: Number of centroids K per table.
        """
        assert centroids.ndim == 3 and centroids.shape[0] == len(tables)
        self.tables = list(tables)
        self.k_per_table = k_per_table
        self.n_tables, _, self.dim = centroids.shape
        # Contiguous [N*K, D] layout for single-BLAS scoring
        self.flat_centroids = np.ascontiguousarray(_l2_normalize(centroids.astype(np.float32)).reshape(-1, self.dim))

    @classmethod
    def from_table_vectors(
        cls,
        table_vecs: Dict[str, np.ndarray],
        k_per_table: int = 8,
        iters: int = 12,
        seed: int = 42,
    ) -> "HierarchicalTableRouter":
        """Build balanced normalized centroids per table using deterministic spherical k-means."""
        rng = np.random.default_rng(seed)
        tables = sorted(table_vecs.keys())
        first = next(iter(table_vecs.values()))
        dim = first.shape[1]
        all_c = np.zeros((len(tables), k_per_table, dim), dtype=np.float32)

        for ti, name in enumerate(tables):
            vecs = _l2_normalize(table_vecs[name].astype(np.float32))
            if len(vecs) <= k_per_table:
                pad = np.tile(vecs, (k_per_table // max(1, len(vecs)) + 1, 1))[:k_per_table]
                all_c[ti] = pad
                continue
            pick = rng.choice(len(vecs), size=k_per_table, replace=False)
            c = vecs[pick].copy()
            for _ in range(iters):
                sims = vecs @ c.T
                assign = np.argmax(sims, axis=1)
                for k in range(k_per_table):
                    mask = assign == k
                    if np.any(mask):
                        c[k] = _l2_normalize(vecs[mask].mean(axis=0, keepdims=True))[0]
            all_c[ti] = c
        return cls(tables, all_c, k_per_table)

    def save(self, path: str) -> None:
        np.savez(
            path,
            tables=np.array(self.tables),
            centroids=self.flat_centroids.reshape(self.n_tables, self.k_per_table, self.dim),
            k_per_table=np.array([self.k_per_table], dtype=np.int32),
        )

    @classmethod
    def load(cls, path: str) -> "HierarchicalTableRouter":
        z = np.load(path, allow_pickle=False)
        return cls(list(z["tables"]), z["centroids"], int(z["k_per_table"][0]))

    def route(self, query_vec: np.ndarray, top_m: int = 5) -> List[TableRoute]:
        """Score all N*K centroids in one matmul and return top-M tables sorted by max centroid IP."""
        q = _l2_normalize(query_vec.astype(np.float32).reshape(1, self.dim))[0]
        sims = (self.flat_centroids @ q).reshape(self.n_tables, self.k_per_table)
        best_c = np.argmax(sims, axis=1)
        best_s = sims[np.arange(self.n_tables), best_c]
        top_idx = np.argpartition(best_s, -min(top_m, self.n_tables))[-min(top_m, self.n_tables):]
        top_idx = top_idx[np.argsort(-best_s[top_idx])]
        return [TableRoute(self.tables[i], float(best_s[i]), int(best_c[i])) for i in top_idx]


@dataclass
class EngramAtom:
    atom_id: str
    pid: str
    table: str
    atom_text: str
    parent_text: str
    vec: np.ndarray


class AtomStore:
    """In-memory prototype of atom-then-expand shards (atoms on Pass 1, parent passage expansion on Pass 2)."""

    def __init__(self, atoms: Sequence[EngramAtom]):
        self.atoms = list(atoms)
        self.by_table: Dict[str, List[int]] = {}
        self.by_pid: Dict[str, str] = {}
        vecs = []
        for idx, a in enumerate(self.atoms):
            self.by_table.setdefault(a.table, []).append(idx)
            self.by_pid[a.pid] = a.parent_text
            vecs.append(a.vec)
        self.mat = _l2_normalize(np.stack(vecs).astype(np.float32)) if vecs else np.zeros((0, 256), dtype=np.float32)

    def retrieve_atoms(self, query_vec: np.ndarray, tables: Sequence[str], k: int = 3) -> List[Tuple[EngramAtom, float]]:
        q = _l2_normalize(query_vec.astype(np.float32).reshape(1, -1))[0]
        cand_idx: List[int] = []
        for t in tables:
            cand_idx.extend(self.by_table.get(t, []))
        if not cand_idx:
            return []
        sub_mat = self.mat[cand_idx]
        scores = sub_mat @ q
        top_local = np.argsort(-scores)[:k]
        return [(self.atoms[cand_idx[i]], float(scores[i])) for i in top_local]

    def expand_pid(self, pid: str) -> Optional[str]:
        return self.by_pid.get(pid)


class TwoStageEngramLoop:
    """Mode A adaptive proxy: Pass-1 quick confidence check & query formulation -> Pass-2 grounded synthesis."""

    def __init__(
        self,
        router: HierarchicalTableRouter,
        store: AtomStore,
        embed_fn: Callable[[str], np.ndarray],
        llm_fn: Callable[[List[Dict[str, str]], bool, int], str],
        conf_threshold: float = 0.85,
        top_tables: int = 5,
        k_pass1: int = 3,
        k_expand: int = 2,
    ):
        self.router = router
        self.store = store
        self.embed_fn = embed_fn
        self.llm_fn = llm_fn
        self.conf_threshold = conf_threshold
        self.top_tables = top_tables
        self.k_pass1 = k_pass1
        self.k_expand = k_expand

    @staticmethod
    def openai_caller(url: str, temperature: float = 1.0, top_p: float = 0.95, top_k: int = 20):
        def _call(messages: List[Dict[str, str]], thinking: bool, max_tokens: int) -> str:
            payload = {
                "model": "moonbeam",
                "messages": messages,
                "temperature": temperature if thinking else 0.0,
                "top_p": top_p,
                "top_k": top_k,
                "max_tokens": max_tokens,
                "chat_template_kwargs": {"enable_thinking": thinking},
            }
            req = urllib.request.Request(url, data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"})
            with urllib.request.urlopen(req, timeout=600) as resp:
                data = json.loads(resp.read().decode())
            msg = data["choices"][0]["message"]
            return msg.get("content") or msg.get("reasoning_content") or ""
        return _call

    def run(self, question: str) -> Dict[str, object]:
        t0 = time.perf_counter()
        # Pass 1: quick non-thinking triage (decides early exit OR generates targeted sub-queries)
        p1_prompt = (
            "Evaluate the question. If you are certain of the exact answer without external facts, "
            "output `CONFIDENCE: <0.0-1.0>` and `ANSWER: <answer>`. "
            "Otherwise output `CONFIDENCE: 0.2` and up to two search queries as `<query>...</query>`.\n\n"
            f"Question: {question}"
        )
        p1_out = self.llm_fn([{"role": "user", "content": p1_prompt}], False, 192)
        m_conf = re.search(r"CONFIDENCE:\s*([0-9]*\.?[0-9]+)", p1_out, re.I)
        conf = float(m_conf.group(1)) if m_conf else 0.0
        queries = [q.strip() for q in re.findall(r"<query>(.*?)</query>", p1_out, re.I | re.S) if q.strip()]

        if conf >= self.conf_threshold and not queries and "ANSWER:" in p1_out:
            ans = p1_out.split("ANSWER:", 1)[1].strip()
            return {
                "answer": ans,
                "early_exit": True,
                "confidence": conf,
                "tables_routed": [],
                "atoms_used": 0,
                "expanded_pids": [],
                "elapsed_ms": round((time.perf_counter() - t0) * 1000, 2),
            }

        # Hierarchical table routing + compact atom lookup
        search_queries = queries[:2] if queries else [question]
        routed_tables: List[str] = []
        picked_atoms: Dict[str, Tuple[EngramAtom, float]] = {}
        for sq in search_queries:
            qv = self.embed_fn(sq)
            routes = self.router.route(qv, top_m=self.top_tables)
            t_names = [r.table for r in routes]
            for tn in t_names:
                if tn not in routed_tables:
                    routed_tables.append(tn)
            for atom, sc in self.store.retrieve_atoms(qv, t_names, k=self.k_pass1):
                if atom.atom_id not in picked_atoms or sc > picked_atoms[atom.atom_id][1]:
                    picked_atoms[atom.atom_id] = (atom, sc)

        ranked = sorted(picked_atoms.values(), key=lambda x: -x[1])[: self.k_pass1]
        # Expand full parent passage only for top hits
        expanded_pids = [a.pid for a, _ in ranked[: self.k_expand]]
        blocks = []
        for idx, (atom, _) in enumerate(ranked, 1):
            if atom.pid in expanded_pids:
                blocks.append(f"[{idx}] ({atom.table}) {atom.atom_text}\nDetail: {self.store.expand_pid(atom.pid)}")
            else:
                blocks.append(f"[{idx}] ({atom.table}) {atom.atom_text}")

        grounded_prompt = (
            "Reference passages (retrieved automatically; they may be incomplete or irrelevant):\n"
            + "\n\n".join(blocks)
            + f"\n\nQuestion: {question}"
        )
        p2_out = self.llm_fn([{"role": "user", "content": grounded_prompt}], True, 2048)
        return {
            "answer": p2_out,
            "early_exit": False,
            "confidence": conf,
            "queries": search_queries,
            "tables_routed": routed_tables,
            "atoms_used": len(ranked),
            "expanded_pids": expanded_pids,
            "elapsed_ms": round((time.perf_counter() - t0) * 1000, 2),
        }


def run_self_test() -> None:
    rng = np.random.default_rng(7)
    n_tables, vecs_per_table, dim = 100, 64, 256
    table_vecs = {}
    table_centers = {}
    atoms = []
    for ti in range(n_tables):
        tname = f"domain_{ti:03d}"
        center = _l2_normalize(rng.normal(size=(1, dim)).astype(np.float32))[0]
        table_centers[tname] = center
        vecs = _l2_normalize(center + 0.25 * rng.normal(size=(vecs_per_table, dim)).astype(np.float32))
        table_vecs[tname] = vecs
        for vi in range(8):
            atoms.append(
                EngramAtom(
                    atom_id=f"{tname}_{vi}",
                    pid=f"pid_{tname}_{vi}",
                    table=tname,
                    atom_text=f"Compact fact {vi} from {tname}.",
                    parent_text=f"Full detailed paragraph {vi} in table {tname} explaining exact evidence.",
                    vec=vecs[vi],
                )
            )

    t_build = time.perf_counter()
    router = HierarchicalTableRouter.from_table_vectors(table_vecs, k_per_table=8)
    build_ms = (time.perf_counter() - t_build) * 1000
    store = AtomStore(atoms)

    # Latency & recall test over 100 tables
    n_queries = 500
    t_route = time.perf_counter()
    hits = 0
    for qi in range(n_queries):
        target = f"domain_{qi % n_tables:03d}"
        qv = _l2_normalize(table_centers[target] + 0.12 * rng.normal(size=(dim,)).astype(np.float32))
        top5 = router.route(qv, top_m=5)
        if any(r.table == target for r in top5):
            hits += 1
    route_us = ((time.perf_counter() - t_route) / n_queries) * 1e6
    flat_cands = 9 * n_tables
    hier_cands = 9 * 5
    print(
        f"[Router Bench 100 tables x 8 centroids] build={build_ms:.1f}ms, "
        f"route_latency={route_us:.1f}us/query, top5_table_recall={100*hits/n_queries:.1f}%, "
        f"candidates_reduced={flat_cands} -> {hier_cands} ({flat_cands/hier_cands:.1f}x fewer)"
    )
    assert hits / n_queries >= 0.99

    # Test Mode A early-exit vs 2-stage grounded synthesis
    def mock_embed(text: str) -> np.ndarray:
        if "domain_042" in text:
            return atoms[42 * 8].vec
        return table_centers["domain_007"]

    def mock_llm(messages, thinking: bool, max_tokens: int) -> str:
        msg = messages[0]["content"]
        if not thinking and "2+2" in msg:
            return "CONFIDENCE: 0.98\nANSWER: 4"
        if not thinking:
            return "CONFIDENCE: 0.15\n<query>evidence in domain_042</query>"
        assert "domain_042" in msg and "Detail:" in msg
        return "Grounded final answer citing [1]."

    engine = TwoStageEngramLoop(router, store, mock_embed, mock_llm)
    res_fast = engine.run("What is 2+2?")
    assert res_fast["early_exit"] is True and res_fast["answer"] == "4"
    res_loop = engine.run("Explain exact fact from domain 42.")
    assert res_loop["early_exit"] is False and "domain_042" in res_loop["tables_routed"] and res_loop["atoms_used"] == 3
    print("[Mode A Self-Test] PASS:", {"fast_exit": res_fast["early_exit"], "loop_tables": res_loop["tables_routed"], "expanded_pids": res_loop["expanded_pids"]})


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--self-test", action="store_true")
    args = ap.parse_args()
    if args.self_test:
        run_self_test()