chadstthomas commited on
Commit
3f51d96
·
verified ·
1 Parent(s): 0868b04

Initial release of Tablinum-Loop: TBLR v1 34-table hierarchical router (210M passages), EngramBench atom shards, and Mode A/B prototypes

Browse files
ARCHITECTURE.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tablinum-Loop (`schema: 2`): Scalable External Engram Architecture for Looped MoE Models
2
+
3
+ ## Why Tablinum-3 (`schema: 1`) Bottlenecks on Looped Models
4
+
5
+ Tablinum-3 + `terrabeam 0.3` uses **single-shot pre-turn retrieval** (`Pool::Global` across `N` tables, injecting `k=3` full passages before generation). While effective for single-pass models, it hits four structural bottlenecks as table counts grow and models loop:
6
+
7
+ 1. **Loop Prefill Amplification:** Every token injected into the prompt traverses all `L` layers *plus* `passes − 1` extra executions of the looped band (`L12–19 ×2` on Moon-Beam 2 = `+33%` attention & MoE prefill compute per retrieved token).
8
+ 2. **Linear Table Scaling (`O(N)`):** `Pool::Global` pulls `8` vector candidates + `1` BM25 hit from every table (`9 × N` candidates). Scaling from `29` tables to `100+` domain tables pushes cross-encoder reranking latency into multiple seconds per query.
9
+ 3. **Distractor Overload:** Past engram ablations (`engram-knowledge-tables`) showed injecting `k=5` full passages degraded AA-Omniscience from `8.0` down to `0.5` because off-target context lures small/quantized experts into near-miss hallucinations.
10
+ 4. **No Loop / Multi-Format Metadata:** `schema: 1` has no fields for looped band geometry (`band`, `passes`, `reenter`, `per_pass_cache`), adaptive early exit, or non-GGUF hardware formats (`mlx`, `nvfp4`, `npu`, `pytorch_loop`).
11
+
12
+ ---
13
+
14
+ ## Four Pillars of Tablinum-Loop (`schema: 2`)
15
+
16
+ ### 1. Hierarchical Centroid Table Router (`domain_router.npz` / `.bin`)
17
+ - **Offline:** Run `k-means` (`K=8` centroids per table) on each table's `256`-dimensional `static-retrieval-mrl-en-v1` embeddings and pack them into a tiny contiguous matrix `[N × K, 256]` (`~82 KB` per `10` tables, `<1 MB` for `100` tables).
18
+ - **Online:** Single BLAS dot product (`q @ C.T`) scores all `N` tables in `<0.2 ms` CPU time and routes only to the **top-`M=5` tables** (plus fallback lexical triggers).
19
+ - **Scaling:** Keeps IVF + BM25 + MiniLM cross-encoder cost **strictly `O(1)` in `N`** (`~45` candidates regardless of whether the pack has `20` or `200` tables).
20
+
21
+ ### 2. Atom-Then-Expand Shards (`atoms.parquet`)
22
+ - Instead of injecting three `200–350` token passages upfront, each passage (`pid`) is indexed alongside distilled `40–80` token **fact atoms** (`atom_id -> pid`).
23
+ - **Pass 1** reads compact atoms (`~150` tokens total instead of `~900` tokens — cutting looped prefill overhead by **6×** and suppressing off-target distractors).
24
+ - **Pass 2** only calls `expand(pid)` for the 1–2 passages the model actually cites or queries.
25
+
26
+ ### 3. Mode A — Two-Stage Engram-Loop with Early Exit (Deployable Today on `terrabeam` + `llama.cpp`)
27
+ Runs directly over any OpenAI-compatible `llama-server` / `terrabeam` backend:
28
+ 1. **Pass 1 (Fast Draft & Confidence Check):** Model evaluates the user prompt (thinking off / short budget) with zero retrieval (`0` extra engram tokens) and outputs either a high-confidence direct answer (`confidence >= 0.85` → **Early Exit**, skipping both retrieval and Pass 2) OR `1–2` crisp targeted micro-queries (`<query>...</query>`).
29
+ 2. **Hierarchical Fetch:** `HierarchicalTableRouter` selects the top-`M` tables and `AtomStore` fetches compact Pass-1 atoms (and optional expanded parent passages).
30
+ 3. **Pass 2 (Grounded Synthesis):** Full thinking-ON synthesis grounded on retrieved evidence, preserving canonical reasoning traces.
31
+
32
+ ### 4. Mode B — Mid-Band Hidden-State Engram Bridge (Zero Extra Context Tokens)
33
+ For native PyTorch / future `llama.cpp` loop execution inside `loopmb.LoopBand`:
34
+ - After Pass 1 exits `L19` (`hidden_size = 1536`), a tiny projection head `W_q: 1536 → 256` maps the current token's hidden representation directly into normalized `static-retrieval-mrl-en-v1` / IVF-SQ8 space.
35
+ - Top-`k=4` retrieved passage/entity embeddings `[K_mem, V_mem]` are mixed via zero-initialized cross-attention (`reenter_engram_up = 0` at initialization, guaranteeing exact mathematical identity at step 0) into Pass 2's re-entry state before `L12–19` execute a second time.
36
+ - Because knowledge enters directly between Pass 1 and Pass 2 inside the latent stream, **zero retrieved context tokens enter the KV/KDA cache**.
37
+
38
+ ---
39
+
40
+ ## `terrabeam 0.4` Rust Crate Touchpoints (`~/optane-llm/terrabeam`)
41
+
42
+ | Component | Target File | Change |
43
+ |---|---|---|
44
+ | Table Router | `crates/engram/src/router.rs` | Memory-map `domain_router.bin` (`[N×K, 256]`), select top-`M` table IDs via SIMD dot product before `Engram::retrieve()` |
45
+ | Atom Expander | `crates/engram/src/passages.rs` | Optional `atoms.parquet` lookup + `expand_pid(pid)` endpoint |
46
+ | Adaptive Loop Proxy | `crates/terrabeam/src/proxy.rs` | Implement `loop_policy: pass1_draft_pass2_verify` with early-exit threshold and `/v1` `X-Tablinum-Loop` telemetry header |
47
+ | Multi-Format Manifest | `crates/terrabeam/src/manifest.rs` | Parse `schema: 2` (`loop`, `formats`, `engram.routing`, `engram.granularity`) while staying backwards-compatible with `schema: 1` |
README.md ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ task_categories:
4
+ - question-answering
5
+ - text-retrieval
6
+ language:
7
+ - en
8
+ tags:
9
+ - tablinum
10
+ - tablinum-loop
11
+ - engram
12
+ - moe
13
+ - looped-transformer
14
+ - moon-beam
15
+ - terrabeam
16
+ - research-preview
17
+ pretty_name: Tablinum-Loop (Engram Router & Atom Shards for Looped MoE)
18
+ ---
19
+
20
+ # Tablinum-Loop (`schema: 2`)
21
+
22
+ **Tablinum-Loop** is the loop-native companion dataset and routing pack for [Moon-Beam-2-8B-A1B-Research-Preview](https://huggingface.co/tablinum/Moon-Beam-2-8B-A1B-Research-Preview) and [`terrabeam`](https://github.com/chadstthomas-svg/terrabeam), released openly to **foster open-source frontier discovery** in external memory + looped MoE reasoning.
23
+
24
+ ---
25
+
26
+ ## What Is Included
27
+
28
+ | Artifact | Description | Size |
29
+ |---|---|---:|
30
+ | `domain_router.bin` | `TBLR` v1 binary hierarchical router (`34` real Tablinum-3 tables × `8` normalized `256`-d centroids) for Rust `engram::router::TableRouter` | `272.4 KB` |
31
+ | `domain_router.npz` | NumPy archive of the same `34 × 8 × 256` centroid matrix for Python callers | `274.3 KB` |
32
+ | `atoms_engrambench.parquet` | `5,000` distilled atom-then-expand shards (`atom_id`, `pid`, `table`, `title`, `section`, `atom_text`, `parent_text`) built from EngramBench retrieval pools | `2.75 MB` |
33
+ | `router_manifest.json` | Table inventory across `209,998,995` indexed Tablinum-3 passages + routing benchmark metrics | — |
34
+ | `packs.json` | `schema: 2` pack definitions (`lite` and `all` with hierarchical `top_tables=5`) | — |
35
+ | `tablinum_loop_engine.py` | Reference Python implementation (`HierarchicalTableRouter`, `AtomStore`, `TwoStageEngramLoop` Mode A) | — |
36
+ | `midband_engram.py` | Reference PyTorch Mode B latent bridge (`MidBandEngramBridge`, zero-init identity for `loopmb.LoopBand`) | — |
37
+ | `ARCHITECTURE.md` | Design spec covering Mode A (Two-Stage + Early Exit), Mode B (Latent Bridge), and Rust integration | — |
38
+ | `examples/moonbeam2_tablinum_v2.json` | Schema v2 `tablinum.json` manifest for Moon-Beam 2 Research Preview | — |
39
+
40
+ ---
41
+
42
+ ## Real Indexed Coverage & Routing Telemetry
43
+
44
+ Built directly from **`34` real FAISS IVF-SQ8 tables** spanning **`209,998,995` indexed passages** (`wiki, apps, cdcj, cli, ecfr, eulex, fdalabel, finreg, health, healthp, homerepair, humprim, humref, law, math, oer, papers_bio, papers_eng, papers_fin, papers_hum, papers_humft, papers_sci, philo, psych, scicode, sedev, sefin, sehum, selaw, sestem, sesys, software, uscode, web`):
45
+
46
+ - **Routing speed:** **`24.9 µs/query`** (`0.1–0.3 ms` to score all `34 × 8` centroids on CPU)
47
+ - **Top-5 table recall (`1,000` IVF centroid queries):** **`97.7%`** (`Top-10`: **`99.1%`**)
48
+ - **Candidate reduction vs. flat `Pool::Global`:** `306 → 45` candidates (`6.8×` fewer cross-encoder pairs on `M=5` tables)
49
+
50
+ ---
51
+
52
+ ## Quickstart
53
+
54
+ ### Rust (`terrabeam` / `engram` crate)
55
+ ```rust
56
+ use engram::{Engram, Pool, router::TableRouter};
57
+
58
+ let router = TableRouter::open("domain_router.bin".as_ref())?;
59
+ let mut eg = Engram::open(engram_root, &tables, embed_dir, 128, 48)?
60
+ .with_router(router);
61
+ eg.pool = Pool::hierarchical(48, 5);
62
+ let hits = eg.retrieve("Which Finnish club did Kevin Czuczman sign with?", 3, &tables)?;
63
+ ```
64
+
65
+ ### Python
66
+ ```python
67
+ from tablinum_loop_engine import HierarchicalTableRouter
68
+ router = HierarchicalTableRouter.load("domain_router.npz")
69
+ top_tables = router.route(query_vec, top_m=5)
70
+ ```
71
+
72
+ ---
73
+
74
+ ## Links & Attribution
75
+ - **Model:** [tablinum/Moon-Beam-2-8B-A1B-Research-Preview](https://huggingface.co/tablinum/Moon-Beam-2-8B-A1B-Research-Preview) · [GGUF + Lite-Beam v2](https://huggingface.co/tablinum/Moon-Beam-2-8B-A1B-GGUF-Research-Preview)
76
+ - **Sidecar Runtime:** [chadstthomas-svg/terrabeam](https://github.com/chadstthomas-svg/terrabeam)
77
+ - **Full Library:** [tablinum/tablinum-3](https://huggingface.co/datasets/tablinum/tablinum-3)
78
+ - **License:** MIT
atoms_engrambench.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dc5a929c65b4d1768bc8fcf578d87c35d103b0ebee14a48e69c4a2600b4f058d
3
+ size 2753275
domain_router.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a2c82bd4ce9a086c4f30af7b3dc04f6cfd4daf8f692f03402c2490d185851a0d
3
+ size 278899
domain_router.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d020e79b06a4ee515d7a99ad3b1ec4ba311501035ad525463f7915e237f473b0
3
+ size 280934
examples/moonbeam2_tablinum_v2.json ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": 2,
3
+ "name": "Moon-Beam-2-8B-A1B-Research-Preview",
4
+ "stage": "research-preview",
5
+ "progression": [
6
+ "research-preview",
7
+ "preview",
8
+ "release"
9
+ ],
10
+ "mission": "Foster open-source frontier discovery through early, reproducible looped-MoE weights, routing telemetry, and quantization ladders.",
11
+ "context": 131072,
12
+ "sampling": {
13
+ "temperature": 1.0,
14
+ "top_p": 0.95,
15
+ "top_k": 20,
16
+ "min_p": 0.0
17
+ },
18
+ "loop": {
19
+ "band": [12, 20],
20
+ "passes": 2,
21
+ "reenter": true,
22
+ "reenter_dim": 256,
23
+ "per_pass_cache": true,
24
+ "train_routers": true,
25
+ "adaptive_exit": {
26
+ "mode": "two_stage_engram",
27
+ "pass1_confidence_threshold": 0.85
28
+ }
29
+ },
30
+ "formats": {
31
+ "pytorch_loop": {
32
+ "repo": "tablinum/Moon-Beam-2-8B-A1B-Research-Preview",
33
+ "base_model": "tablinum/Moon-Beam-8B-A1B",
34
+ "adapter": "adapter_model.safetensors",
35
+ "loop_gates": "loop_gates.pt",
36
+ "runtime": "loopmb.py"
37
+ },
38
+ "gguf": {
39
+ "repo": "tablinum/Moon-Beam-2-8B-A1B-GGUF-Research-Preview",
40
+ "llama_cpp_min": "1121",
41
+ "recommended_band_protected": [
42
+ "LB2-IQ1_M",
43
+ "LB2-IQ2_XXS",
44
+ "LB2-IQ2_M"
45
+ ],
46
+ "standard": [
47
+ "IQ3_XXS",
48
+ "IQ4_XS",
49
+ "MXFP4_MOE",
50
+ "Q4_K_M",
51
+ "Q6_K",
52
+ "Q8_0"
53
+ ]
54
+ },
55
+ "nvfp4": {
56
+ "repo": "tablinum/Moon-Beam-2-8B-A1B-NVFP4-Research-Preview",
57
+ "file": "Moon-Beam-2-8B-A1B-RP-NVFP4.gguf",
58
+ "tail_layers_precision": "Q8_0",
59
+ "routed_experts_precision": "NVFP4"
60
+ },
61
+ "npu": {
62
+ "repo": "tablinum/Moon-Beam-2-8B-A1B-NPU-Research-Preview",
63
+ "file": "Moon-Beam-2-8B-A1B-RP-Q4_0.gguf",
64
+ "precision": "Q4_0"
65
+ },
66
+ "mlx": {
67
+ "repo": "tablinum/Moon-Beam-2-8B-A1B-MLX-Research-Preview",
68
+ "backend": "metal",
69
+ "quant": "beam-mix-4bit-8bit"
70
+ },
71
+ "mlx_8bit": {
72
+ "repo": "tablinum/Moon-Beam-2-8B-A1B-MLX-8bit-Research-Preview",
73
+ "backend": "metal",
74
+ "quant": "8bit-g64"
75
+ }
76
+ },
77
+ "engram": {
78
+ "default_pack": "lite",
79
+ "format": "tablinum_v2",
80
+ "routing": {
81
+ "strategy": "hierarchical_centroid",
82
+ "top_tables": 5,
83
+ "centroids_per_table": 8,
84
+ "embed_dim": 256
85
+ },
86
+ "granularity": "atom_then_expand",
87
+ "k_pass1": 3,
88
+ "k_pass2_expand": 2,
89
+ "ncand_per_routed_table": 16,
90
+ "nprobe": 128,
91
+ "loop_policy": "pass1_draft_pass2_verify"
92
+ },
93
+ "harness": {
94
+ "id": "tb2;inject=loop_adaptive;routing=centroid5;granularity=atom;tool=library;reasoning=keep",
95
+ "library_tool": true,
96
+ "keep_reasoning": true
97
+ }
98
+ }
midband_engram.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """midband_engram.py - Mode B zero-context-token mid-band hidden-state engram bridge for LoopBand.
3
+
4
+ Projects Pass-1 hidden states from BailingMoeV3 (d_model=1536) into normalized 256-d engram space,
5
+ retrieves top-k external memory keys/values, and injects a zero-initialized cross-attention residual
6
+ into Pass 2's re-entry state so step-0 behavior is mathematically identical to the base model.
7
+ """
8
+ import argparse, math
9
+ import torch
10
+ from torch import nn
11
+ import torch.nn.functional as F
12
+
13
+
14
+ class MidBandEngramBridge(nn.Module):
15
+ """Latent between-pass external memory bridge for looped MoE bands (Mode B)."""
16
+
17
+ def __init__(self, d_model: int = 1536, d_engram: int = 256, n_heads: int = 4, top_k: int = 4):
18
+ super().__init__()
19
+ assert d_engram % n_heads == 0
20
+ self.d_model = d_model
21
+ self.d_engram = d_engram
22
+ self.n_heads = n_heads
23
+ self.head_dim = d_engram // n_heads
24
+ self.top_k = top_k
25
+
26
+ self.norm = nn.RMSNorm(d_model, eps=1e-6)
27
+ self.q_proj = nn.Linear(d_model, d_engram, bias=False)
28
+ self.k_proj = nn.Linear(d_engram, d_engram, bias=False)
29
+ self.v_proj = nn.Linear(d_engram, d_model, bias=False)
30
+ self.out_proj = nn.Linear(d_model, d_model, bias=False)
31
+ # Zero-init output projection & bias so step 0 == exact identity
32
+ nn.init.zeros_(self.out_proj.weight)
33
+ self.gate_proj = nn.Linear(d_model, 1, bias=True)
34
+ nn.init.zeros_(self.gate_proj.weight)
35
+ nn.init.constant_(self.gate_proj.bias, -4.0)
36
+
37
+ def forward(self, hidden_states: torch.Tensor, mem_keys: torch.Tensor, mem_vals: torch.Tensor) -> torch.Tensor:
38
+ """
39
+ Args:
40
+ hidden_states: [B, T, d_model] output of LoopBand Pass 1.
41
+ mem_keys: [M, d_engram] L2-normalized external memory index keys (e.g. static MRL / IVF bank).
42
+ mem_vals: [M, d_engram] external memory representation bank.
43
+ Returns:
44
+ Tensor [B, T, d_model] conditioned for LoopBand Pass 2 entry.
45
+ """
46
+ b, t, _ = hidden_states.shape
47
+ x_norm = self.norm(hidden_states)
48
+ q_raw = self.q_proj(x_norm)
49
+ q_norm = F.normalize(q_raw.float(), dim=-1)
50
+ keys_norm = F.normalize(mem_keys.float(), dim=-1)
51
+
52
+ # Lookup top-k nearest external memory entries per token
53
+ sim = torch.matmul(q_norm, keys_norm.t()) # [B, T, M]
54
+ k_use = min(self.top_k, mem_keys.shape[0])
55
+ _, idx = torch.topk(sim, k=k_use, dim=-1) # [B, T, k]
56
+
57
+ gathered_keys = mem_keys[idx] # [B, T, k, d_engram]
58
+ gathered_vals = mem_vals[idx] # [B, T, k, d_engram]
59
+
60
+ # Lightweight cross-attention over top-k retrieved vectors
61
+ k_h = self.k_proj(gathered_keys).view(b, t, k_use, self.n_heads, self.head_dim)
62
+ q_h = q_raw.view(b, t, 1, self.n_heads, self.head_dim)
63
+ attn_logits = (q_h * k_h).sum(dim=-1) / math.sqrt(self.head_dim) # [B, T, k, H]
64
+ attn_w = F.softmax(attn_logits.float(), dim=2).to(hidden_states.dtype)
65
+
66
+ # Combine per-head weighted memory values (broadcasted over d_model via v_proj)
67
+ v_full = self.v_proj(gathered_vals) # [B, T, k, d_model]
68
+ mean_w = attn_w.mean(dim=-1, keepdim=True) # [B, T, k, 1]
69
+ ctx = (v_full * mean_w).sum(dim=2) # [B, T, d_model]
70
+
71
+ gate = torch.sigmoid(self.gate_proj(x_norm).float()).to(hidden_states.dtype)
72
+ return hidden_states + gate * self.out_proj(ctx)
73
+
74
+
75
+ def run_self_test() -> None:
76
+ torch.manual_seed(0)
77
+ bridge = MidBandEngramBridge(d_model=1536, d_engram=256, n_heads=4, top_k=4)
78
+ x = torch.randn(2, 16, 1536, requires_grad=True)
79
+ mem_k = torch.randn(512, 256)
80
+ mem_v = torch.randn(512, 256)
81
+
82
+ # 1. Zero-init identity check
83
+ y0 = bridge(x, mem_k, mem_v)
84
+ max_diff = (y0 - x).abs().max().item()
85
+ assert max_diff == 0.0, f"Expected exact zero-init identity, got max_diff={max_diff}"
86
+
87
+ # 2. Gradient flow check once out_proj is perturbed / backpropagated
88
+ with torch.no_grad():
89
+ bridge.out_proj.weight.normal_(std=0.02)
90
+ y1 = bridge(x, mem_k, mem_v)
91
+ loss = (y1 ** 2).mean()
92
+ loss.backward()
93
+ assert bridge.q_proj.weight.grad is not None and bridge.q_proj.weight.grad.abs().sum().item() > 0
94
+ assert bridge.gate_proj.weight.grad is not None and bridge.gate_proj.weight.grad.abs().sum().item() > 0
95
+ assert x.grad is not None and x.grad.abs().sum().item() > 0
96
+ print(
97
+ "[MidBandEngramBridge Self-Test] PASS:",
98
+ {
99
+ "zero_init_max_diff": max_diff,
100
+ "q_proj_grad_norm": round(bridge.q_proj.weight.grad.norm().item(), 6),
101
+ "gate_grad_norm": round(bridge.gate_proj.weight.grad.norm().item(), 6),
102
+ "trainable_params": sum(p.numel() for p in bridge.parameters()),
103
+ },
104
+ )
105
+
106
+
107
+ if __name__ == "__main__":
108
+ ap = argparse.ArgumentParser()
109
+ ap.add_argument("--self-test", action="store_true")
110
+ args = ap.parse_args()
111
+ if args.self_test:
112
+ run_self_test()
packs.json ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": 2,
3
+ "router_file": "domain_router.bin",
4
+ "router_bytes": 278899,
5
+ "atoms_starter": "atoms_engrambench.parquet",
6
+ "packs": {
7
+ "lite": {
8
+ "tables": [
9
+ "wiki",
10
+ "software",
11
+ "law",
12
+ "health",
13
+ "oer"
14
+ ],
15
+ "top_tables": 5
16
+ },
17
+ "all": {
18
+ "tables": [
19
+ "wiki",
20
+ "apps",
21
+ "cdcj",
22
+ "cli",
23
+ "ecfr",
24
+ "eulex",
25
+ "fdalabel",
26
+ "finreg",
27
+ "health",
28
+ "healthp",
29
+ "homerepair",
30
+ "humprim",
31
+ "humref",
32
+ "law",
33
+ "math",
34
+ "oer",
35
+ "papers_bio",
36
+ "papers_eng",
37
+ "papers_fin",
38
+ "papers_hum",
39
+ "papers_humft",
40
+ "papers_sci",
41
+ "philo",
42
+ "psych",
43
+ "scicode",
44
+ "sedev",
45
+ "sefin",
46
+ "sehum",
47
+ "selaw",
48
+ "sestem",
49
+ "sesys",
50
+ "software",
51
+ "uscode",
52
+ "web"
53
+ ],
54
+ "top_tables": 5
55
+ }
56
+ }
57
+ }
router_manifest.json ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": 2,
3
+ "router_format": "TBLR_v1",
4
+ "k_per_table": 8,
5
+ "embed_dim": 256,
6
+ "embed_model": "sentence-transformers/static-retrieval-mrl-en-v1",
7
+ "n_tables": 34,
8
+ "total_passages": 209998995,
9
+ "router_bytes": 278899,
10
+ "bench_1000_queries": {
11
+ "route_us_per_query": 24.9,
12
+ "top5_table_recall": 0.977,
13
+ "top10_table_recall": 0.991
14
+ },
15
+ "tables": [
16
+ {
17
+ "table": "wiki",
18
+ "d": 256,
19
+ "nlist": 16384,
20
+ "ntotal": 57494899,
21
+ "metric": 0,
22
+ "coarse_centroids": 8
23
+ },
24
+ {
25
+ "table": "apps",
26
+ "d": 256,
27
+ "nlist": 1024,
28
+ "ntotal": 144929,
29
+ "metric": 0,
30
+ "coarse_centroids": 8
31
+ },
32
+ {
33
+ "table": "cdcj",
34
+ "d": 256,
35
+ "nlist": 4096,
36
+ "ntotal": 1185134,
37
+ "metric": 0,
38
+ "coarse_centroids": 8
39
+ },
40
+ {
41
+ "table": "cli",
42
+ "d": 256,
43
+ "nlist": 1024,
44
+ "ntotal": 127289,
45
+ "metric": 0,
46
+ "coarse_centroids": 8
47
+ },
48
+ {
49
+ "table": "ecfr",
50
+ "d": 256,
51
+ "nlist": 1024,
52
+ "ntotal": 226682,
53
+ "metric": 0,
54
+ "coarse_centroids": 8
55
+ },
56
+ {
57
+ "table": "eulex",
58
+ "d": 256,
59
+ "nlist": 8192,
60
+ "ntotal": 6569241,
61
+ "metric": 0,
62
+ "coarse_centroids": 8
63
+ },
64
+ {
65
+ "table": "fdalabel",
66
+ "d": 256,
67
+ "nlist": 2048,
68
+ "ntotal": 273483,
69
+ "metric": 0,
70
+ "coarse_centroids": 8
71
+ },
72
+ {
73
+ "table": "finreg",
74
+ "d": 256,
75
+ "nlist": 4096,
76
+ "ntotal": 1235376,
77
+ "metric": 0,
78
+ "coarse_centroids": 8
79
+ },
80
+ {
81
+ "table": "health",
82
+ "d": 256,
83
+ "nlist": 16384,
84
+ "ntotal": 27390442,
85
+ "metric": 0,
86
+ "coarse_centroids": 8
87
+ },
88
+ {
89
+ "table": "healthp",
90
+ "d": 256,
91
+ "nlist": 2048,
92
+ "ntotal": 760326,
93
+ "metric": 0,
94
+ "coarse_centroids": 8
95
+ },
96
+ {
97
+ "table": "homerepair",
98
+ "d": 256,
99
+ "nlist": 2048,
100
+ "ntotal": 544423,
101
+ "metric": 0,
102
+ "coarse_centroids": 8
103
+ },
104
+ {
105
+ "table": "humprim",
106
+ "d": 256,
107
+ "nlist": 16384,
108
+ "ntotal": 18815032,
109
+ "metric": 0,
110
+ "coarse_centroids": 8
111
+ },
112
+ {
113
+ "table": "humref",
114
+ "d": 256,
115
+ "nlist": 2048,
116
+ "ntotal": 317939,
117
+ "metric": 0,
118
+ "coarse_centroids": 8
119
+ },
120
+ {
121
+ "table": "law",
122
+ "d": 256,
123
+ "nlist": 16384,
124
+ "ntotal": 15354819,
125
+ "metric": 0,
126
+ "coarse_centroids": 8
127
+ },
128
+ {
129
+ "table": "math",
130
+ "d": 256,
131
+ "nlist": 2048,
132
+ "ntotal": 340433,
133
+ "metric": 0,
134
+ "coarse_centroids": 8
135
+ },
136
+ {
137
+ "table": "oer",
138
+ "d": 256,
139
+ "nlist": 16384,
140
+ "ntotal": 17500842,
141
+ "metric": 0,
142
+ "coarse_centroids": 8
143
+ },
144
+ {
145
+ "table": "papers_bio",
146
+ "d": 256,
147
+ "nlist": 2048,
148
+ "ntotal": 660081,
149
+ "metric": 0,
150
+ "coarse_centroids": 8
151
+ },
152
+ {
153
+ "table": "papers_eng",
154
+ "d": 256,
155
+ "nlist": 8192,
156
+ "ntotal": 8331056,
157
+ "metric": 0,
158
+ "coarse_centroids": 8
159
+ },
160
+ {
161
+ "table": "papers_fin",
162
+ "d": 256,
163
+ "nlist": 4096,
164
+ "ntotal": 2448152,
165
+ "metric": 0,
166
+ "coarse_centroids": 8
167
+ },
168
+ {
169
+ "table": "papers_hum",
170
+ "d": 256,
171
+ "nlist": 4096,
172
+ "ntotal": 3549211,
173
+ "metric": 0,
174
+ "coarse_centroids": 8
175
+ },
176
+ {
177
+ "table": "papers_humft",
178
+ "d": 256,
179
+ "nlist": 8192,
180
+ "ntotal": 10692645,
181
+ "metric": 0,
182
+ "coarse_centroids": 8
183
+ },
184
+ {
185
+ "table": "papers_sci",
186
+ "d": 256,
187
+ "nlist": 8192,
188
+ "ntotal": 7203281,
189
+ "metric": 0,
190
+ "coarse_centroids": 8
191
+ },
192
+ {
193
+ "table": "philo",
194
+ "d": 256,
195
+ "nlist": 2048,
196
+ "ntotal": 443486,
197
+ "metric": 0,
198
+ "coarse_centroids": 8
199
+ },
200
+ {
201
+ "table": "psych",
202
+ "d": 256,
203
+ "nlist": 1024,
204
+ "ntotal": 92172,
205
+ "metric": 0,
206
+ "coarse_centroids": 8
207
+ },
208
+ {
209
+ "table": "scicode",
210
+ "d": 256,
211
+ "nlist": 2048,
212
+ "ntotal": 272523,
213
+ "metric": 0,
214
+ "coarse_centroids": 8
215
+ },
216
+ {
217
+ "table": "sedev",
218
+ "d": 256,
219
+ "nlist": 8192,
220
+ "ntotal": 7764758,
221
+ "metric": 0,
222
+ "coarse_centroids": 8
223
+ },
224
+ {
225
+ "table": "sefin",
226
+ "d": 256,
227
+ "nlist": 2048,
228
+ "ntotal": 278444,
229
+ "metric": 0,
230
+ "coarse_centroids": 8
231
+ },
232
+ {
233
+ "table": "sehum",
234
+ "d": 256,
235
+ "nlist": 2048,
236
+ "ntotal": 680886,
237
+ "metric": 0,
238
+ "coarse_centroids": 8
239
+ },
240
+ {
241
+ "table": "selaw",
242
+ "d": 256,
243
+ "nlist": 1024,
244
+ "ntotal": 105913,
245
+ "metric": 0,
246
+ "coarse_centroids": 8
247
+ },
248
+ {
249
+ "table": "sestem",
250
+ "d": 256,
251
+ "nlist": 4096,
252
+ "ntotal": 3762014,
253
+ "metric": 0,
254
+ "coarse_centroids": 8
255
+ },
256
+ {
257
+ "table": "sesys",
258
+ "d": 256,
259
+ "nlist": 8192,
260
+ "ntotal": 10144858,
261
+ "metric": 0,
262
+ "coarse_centroids": 8
263
+ },
264
+ {
265
+ "table": "software",
266
+ "d": 256,
267
+ "nlist": 8192,
268
+ "ntotal": 4827247,
269
+ "metric": 0,
270
+ "coarse_centroids": 8
271
+ },
272
+ {
273
+ "table": "uscode",
274
+ "d": 256,
275
+ "nlist": 2048,
276
+ "ntotal": 366167,
277
+ "metric": 0,
278
+ "coarse_centroids": 8
279
+ },
280
+ {
281
+ "table": "web",
282
+ "d": 256,
283
+ "nlist": 1024,
284
+ "ntotal": 94812,
285
+ "metric": 0,
286
+ "coarse_centroids": 8
287
+ }
288
+ ]
289
+ }
tablinum_loop_engine.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """tablinum_loop_engine.py - Hierarchical centroid router, atom-then-expand store, and Mode A loop proxy.
3
+
4
+ Implements the three software-side pillars of Tablinum-Loop (schema: 2):
5
+ 1. HierarchicalTableRouter : K centroids per table in 256-d normalized embedding space (O(1) table scaling).
6
+ 2. AtomStore : Compact 40-80 token fact atoms for Pass 1 with optional parent-passage expansion.
7
+ 3. TwoStageEngramLoop : Adaptive Pass-1 draft/early-exit -> targeted fetch -> Pass-2 grounded synthesis.
8
+ """
9
+ import argparse, json, re, time, urllib.request
10
+ from dataclasses import dataclass
11
+ from typing import Callable, Dict, List, Optional, Sequence, Tuple
12
+ import numpy as np
13
+
14
+
15
+ def _l2_normalize(x: np.ndarray) -> np.ndarray:
16
+ norm = np.linalg.norm(x, axis=-1, keepdims=True)
17
+ return x / np.maximum(norm, 1e-12)
18
+
19
+
20
+ @dataclass
21
+ class TableRoute:
22
+ table: str
23
+ score: float
24
+ centroid_idx: int
25
+
26
+
27
+ class HierarchicalTableRouter:
28
+ """Routes a query embedding to top-M tables using K centroids per table."""
29
+
30
+ def __init__(self, tables: Sequence[str], centroids: np.ndarray, k_per_table: int):
31
+ """
32
+ Args:
33
+ tables: Ordered table names of length N.
34
+ centroids: Normalized float32 array of shape [N, K, D].
35
+ k_per_table: Number of centroids K per table.
36
+ """
37
+ assert centroids.ndim == 3 and centroids.shape[0] == len(tables)
38
+ self.tables = list(tables)
39
+ self.k_per_table = k_per_table
40
+ self.n_tables, _, self.dim = centroids.shape
41
+ # Contiguous [N*K, D] layout for single-BLAS scoring
42
+ self.flat_centroids = np.ascontiguousarray(_l2_normalize(centroids.astype(np.float32)).reshape(-1, self.dim))
43
+
44
+ @classmethod
45
+ def from_table_vectors(
46
+ cls,
47
+ table_vecs: Dict[str, np.ndarray],
48
+ k_per_table: int = 8,
49
+ iters: int = 12,
50
+ seed: int = 42,
51
+ ) -> "HierarchicalTableRouter":
52
+ """Build balanced normalized centroids per table using deterministic spherical k-means."""
53
+ rng = np.random.default_rng(seed)
54
+ tables = sorted(table_vecs.keys())
55
+ first = next(iter(table_vecs.values()))
56
+ dim = first.shape[1]
57
+ all_c = np.zeros((len(tables), k_per_table, dim), dtype=np.float32)
58
+
59
+ for ti, name in enumerate(tables):
60
+ vecs = _l2_normalize(table_vecs[name].astype(np.float32))
61
+ if len(vecs) <= k_per_table:
62
+ pad = np.tile(vecs, (k_per_table // max(1, len(vecs)) + 1, 1))[:k_per_table]
63
+ all_c[ti] = pad
64
+ continue
65
+ pick = rng.choice(len(vecs), size=k_per_table, replace=False)
66
+ c = vecs[pick].copy()
67
+ for _ in range(iters):
68
+ sims = vecs @ c.T
69
+ assign = np.argmax(sims, axis=1)
70
+ for k in range(k_per_table):
71
+ mask = assign == k
72
+ if np.any(mask):
73
+ c[k] = _l2_normalize(vecs[mask].mean(axis=0, keepdims=True))[0]
74
+ all_c[ti] = c
75
+ return cls(tables, all_c, k_per_table)
76
+
77
+ def save(self, path: str) -> None:
78
+ np.savez(
79
+ path,
80
+ tables=np.array(self.tables),
81
+ centroids=self.flat_centroids.reshape(self.n_tables, self.k_per_table, self.dim),
82
+ k_per_table=np.array([self.k_per_table], dtype=np.int32),
83
+ )
84
+
85
+ @classmethod
86
+ def load(cls, path: str) -> "HierarchicalTableRouter":
87
+ z = np.load(path, allow_pickle=False)
88
+ return cls(list(z["tables"]), z["centroids"], int(z["k_per_table"][0]))
89
+
90
+ def route(self, query_vec: np.ndarray, top_m: int = 5) -> List[TableRoute]:
91
+ """Score all N*K centroids in one matmul and return top-M tables sorted by max centroid IP."""
92
+ q = _l2_normalize(query_vec.astype(np.float32).reshape(1, self.dim))[0]
93
+ sims = (self.flat_centroids @ q).reshape(self.n_tables, self.k_per_table)
94
+ best_c = np.argmax(sims, axis=1)
95
+ best_s = sims[np.arange(self.n_tables), best_c]
96
+ top_idx = np.argpartition(best_s, -min(top_m, self.n_tables))[-min(top_m, self.n_tables):]
97
+ top_idx = top_idx[np.argsort(-best_s[top_idx])]
98
+ return [TableRoute(self.tables[i], float(best_s[i]), int(best_c[i])) for i in top_idx]
99
+
100
+
101
+ @dataclass
102
+ class EngramAtom:
103
+ atom_id: str
104
+ pid: str
105
+ table: str
106
+ atom_text: str
107
+ parent_text: str
108
+ vec: np.ndarray
109
+
110
+
111
+ class AtomStore:
112
+ """In-memory prototype of atom-then-expand shards (atoms on Pass 1, parent passage expansion on Pass 2)."""
113
+
114
+ def __init__(self, atoms: Sequence[EngramAtom]):
115
+ self.atoms = list(atoms)
116
+ self.by_table: Dict[str, List[int]] = {}
117
+ self.by_pid: Dict[str, str] = {}
118
+ vecs = []
119
+ for idx, a in enumerate(self.atoms):
120
+ self.by_table.setdefault(a.table, []).append(idx)
121
+ self.by_pid[a.pid] = a.parent_text
122
+ vecs.append(a.vec)
123
+ self.mat = _l2_normalize(np.stack(vecs).astype(np.float32)) if vecs else np.zeros((0, 256), dtype=np.float32)
124
+
125
+ def retrieve_atoms(self, query_vec: np.ndarray, tables: Sequence[str], k: int = 3) -> List[Tuple[EngramAtom, float]]:
126
+ q = _l2_normalize(query_vec.astype(np.float32).reshape(1, -1))[0]
127
+ cand_idx: List[int] = []
128
+ for t in tables:
129
+ cand_idx.extend(self.by_table.get(t, []))
130
+ if not cand_idx:
131
+ return []
132
+ sub_mat = self.mat[cand_idx]
133
+ scores = sub_mat @ q
134
+ top_local = np.argsort(-scores)[:k]
135
+ return [(self.atoms[cand_idx[i]], float(scores[i])) for i in top_local]
136
+
137
+ def expand_pid(self, pid: str) -> Optional[str]:
138
+ return self.by_pid.get(pid)
139
+
140
+
141
+ class TwoStageEngramLoop:
142
+ """Mode A adaptive proxy: Pass-1 quick confidence check & query formulation -> Pass-2 grounded synthesis."""
143
+
144
+ def __init__(
145
+ self,
146
+ router: HierarchicalTableRouter,
147
+ store: AtomStore,
148
+ embed_fn: Callable[[str], np.ndarray],
149
+ llm_fn: Callable[[List[Dict[str, str]], bool, int], str],
150
+ conf_threshold: float = 0.85,
151
+ top_tables: int = 5,
152
+ k_pass1: int = 3,
153
+ k_expand: int = 2,
154
+ ):
155
+ self.router = router
156
+ self.store = store
157
+ self.embed_fn = embed_fn
158
+ self.llm_fn = llm_fn
159
+ self.conf_threshold = conf_threshold
160
+ self.top_tables = top_tables
161
+ self.k_pass1 = k_pass1
162
+ self.k_expand = k_expand
163
+
164
+ @staticmethod
165
+ def openai_caller(url: str, temperature: float = 1.0, top_p: float = 0.95, top_k: int = 20):
166
+ def _call(messages: List[Dict[str, str]], thinking: bool, max_tokens: int) -> str:
167
+ payload = {
168
+ "model": "moonbeam",
169
+ "messages": messages,
170
+ "temperature": temperature if thinking else 0.0,
171
+ "top_p": top_p,
172
+ "top_k": top_k,
173
+ "max_tokens": max_tokens,
174
+ "chat_template_kwargs": {"enable_thinking": thinking},
175
+ }
176
+ req = urllib.request.Request(url, data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"})
177
+ with urllib.request.urlopen(req, timeout=600) as resp:
178
+ data = json.loads(resp.read().decode())
179
+ msg = data["choices"][0]["message"]
180
+ return msg.get("content") or msg.get("reasoning_content") or ""
181
+ return _call
182
+
183
+ def run(self, question: str) -> Dict[str, object]:
184
+ t0 = time.perf_counter()
185
+ # Pass 1: quick non-thinking triage (decides early exit OR generates targeted sub-queries)
186
+ p1_prompt = (
187
+ "Evaluate the question. If you are certain of the exact answer without external facts, "
188
+ "output `CONFIDENCE: <0.0-1.0>` and `ANSWER: <answer>`. "
189
+ "Otherwise output `CONFIDENCE: 0.2` and up to two search queries as `<query>...</query>`.\n\n"
190
+ f"Question: {question}"
191
+ )
192
+ p1_out = self.llm_fn([{"role": "user", "content": p1_prompt}], False, 192)
193
+ m_conf = re.search(r"CONFIDENCE:\s*([0-9]*\.?[0-9]+)", p1_out, re.I)
194
+ conf = float(m_conf.group(1)) if m_conf else 0.0
195
+ queries = [q.strip() for q in re.findall(r"<query>(.*?)</query>", p1_out, re.I | re.S) if q.strip()]
196
+
197
+ if conf >= self.conf_threshold and not queries and "ANSWER:" in p1_out:
198
+ ans = p1_out.split("ANSWER:", 1)[1].strip()
199
+ return {
200
+ "answer": ans,
201
+ "early_exit": True,
202
+ "confidence": conf,
203
+ "tables_routed": [],
204
+ "atoms_used": 0,
205
+ "expanded_pids": [],
206
+ "elapsed_ms": round((time.perf_counter() - t0) * 1000, 2),
207
+ }
208
+
209
+ # Hierarchical table routing + compact atom lookup
210
+ search_queries = queries[:2] if queries else [question]
211
+ routed_tables: List[str] = []
212
+ picked_atoms: Dict[str, Tuple[EngramAtom, float]] = {}
213
+ for sq in search_queries:
214
+ qv = self.embed_fn(sq)
215
+ routes = self.router.route(qv, top_m=self.top_tables)
216
+ t_names = [r.table for r in routes]
217
+ for tn in t_names:
218
+ if tn not in routed_tables:
219
+ routed_tables.append(tn)
220
+ for atom, sc in self.store.retrieve_atoms(qv, t_names, k=self.k_pass1):
221
+ if atom.atom_id not in picked_atoms or sc > picked_atoms[atom.atom_id][1]:
222
+ picked_atoms[atom.atom_id] = (atom, sc)
223
+
224
+ ranked = sorted(picked_atoms.values(), key=lambda x: -x[1])[: self.k_pass1]
225
+ # Expand full parent passage only for top hits
226
+ expanded_pids = [a.pid for a, _ in ranked[: self.k_expand]]
227
+ blocks = []
228
+ for idx, (atom, _) in enumerate(ranked, 1):
229
+ if atom.pid in expanded_pids:
230
+ blocks.append(f"[{idx}] ({atom.table}) {atom.atom_text}\nDetail: {self.store.expand_pid(atom.pid)}")
231
+ else:
232
+ blocks.append(f"[{idx}] ({atom.table}) {atom.atom_text}")
233
+
234
+ grounded_prompt = (
235
+ "Reference passages (retrieved automatically; they may be incomplete or irrelevant):\n"
236
+ + "\n\n".join(blocks)
237
+ + f"\n\nQuestion: {question}"
238
+ )
239
+ p2_out = self.llm_fn([{"role": "user", "content": grounded_prompt}], True, 2048)
240
+ return {
241
+ "answer": p2_out,
242
+ "early_exit": False,
243
+ "confidence": conf,
244
+ "queries": search_queries,
245
+ "tables_routed": routed_tables,
246
+ "atoms_used": len(ranked),
247
+ "expanded_pids": expanded_pids,
248
+ "elapsed_ms": round((time.perf_counter() - t0) * 1000, 2),
249
+ }
250
+
251
+
252
+ def run_self_test() -> None:
253
+ rng = np.random.default_rng(7)
254
+ n_tables, vecs_per_table, dim = 100, 64, 256
255
+ table_vecs = {}
256
+ table_centers = {}
257
+ atoms = []
258
+ for ti in range(n_tables):
259
+ tname = f"domain_{ti:03d}"
260
+ center = _l2_normalize(rng.normal(size=(1, dim)).astype(np.float32))[0]
261
+ table_centers[tname] = center
262
+ vecs = _l2_normalize(center + 0.25 * rng.normal(size=(vecs_per_table, dim)).astype(np.float32))
263
+ table_vecs[tname] = vecs
264
+ for vi in range(8):
265
+ atoms.append(
266
+ EngramAtom(
267
+ atom_id=f"{tname}_{vi}",
268
+ pid=f"pid_{tname}_{vi}",
269
+ table=tname,
270
+ atom_text=f"Compact fact {vi} from {tname}.",
271
+ parent_text=f"Full detailed paragraph {vi} in table {tname} explaining exact evidence.",
272
+ vec=vecs[vi],
273
+ )
274
+ )
275
+
276
+ t_build = time.perf_counter()
277
+ router = HierarchicalTableRouter.from_table_vectors(table_vecs, k_per_table=8)
278
+ build_ms = (time.perf_counter() - t_build) * 1000
279
+ store = AtomStore(atoms)
280
+
281
+ # Latency & recall test over 100 tables
282
+ n_queries = 500
283
+ t_route = time.perf_counter()
284
+ hits = 0
285
+ for qi in range(n_queries):
286
+ target = f"domain_{qi % n_tables:03d}"
287
+ qv = _l2_normalize(table_centers[target] + 0.12 * rng.normal(size=(dim,)).astype(np.float32))
288
+ top5 = router.route(qv, top_m=5)
289
+ if any(r.table == target for r in top5):
290
+ hits += 1
291
+ route_us = ((time.perf_counter() - t_route) / n_queries) * 1e6
292
+ flat_cands = 9 * n_tables
293
+ hier_cands = 9 * 5
294
+ print(
295
+ f"[Router Bench 100 tables x 8 centroids] build={build_ms:.1f}ms, "
296
+ f"route_latency={route_us:.1f}us/query, top5_table_recall={100*hits/n_queries:.1f}%, "
297
+ f"candidates_reduced={flat_cands} -> {hier_cands} ({flat_cands/hier_cands:.1f}x fewer)"
298
+ )
299
+ assert hits / n_queries >= 0.99
300
+
301
+ # Test Mode A early-exit vs 2-stage grounded synthesis
302
+ def mock_embed(text: str) -> np.ndarray:
303
+ if "domain_042" in text:
304
+ return atoms[42 * 8].vec
305
+ return table_centers["domain_007"]
306
+
307
+ def mock_llm(messages, thinking: bool, max_tokens: int) -> str:
308
+ msg = messages[0]["content"]
309
+ if not thinking and "2+2" in msg:
310
+ return "CONFIDENCE: 0.98\nANSWER: 4"
311
+ if not thinking:
312
+ return "CONFIDENCE: 0.15\n<query>evidence in domain_042</query>"
313
+ assert "domain_042" in msg and "Detail:" in msg
314
+ return "Grounded final answer citing [1]."
315
+
316
+ engine = TwoStageEngramLoop(router, store, mock_embed, mock_llm)
317
+ res_fast = engine.run("What is 2+2?")
318
+ assert res_fast["early_exit"] is True and res_fast["answer"] == "4"
319
+ res_loop = engine.run("Explain exact fact from domain 42.")
320
+ assert res_loop["early_exit"] is False and "domain_042" in res_loop["tables_routed"] and res_loop["atoms_used"] == 3
321
+ print("[Mode A Self-Test] PASS:", {"fast_exit": res_fast["early_exit"], "loop_tables": res_loop["tables_routed"], "expanded_pids": res_loop["expanded_pids"]})
322
+
323
+
324
+ if __name__ == "__main__":
325
+ ap = argparse.ArgumentParser()
326
+ ap.add_argument("--self-test", action="store_true")
327
+ args = ap.parse_args()
328
+ if args.self_test:
329
+ run_self_test()