"""engram.py - the retrieval side of the Beam engram (10-19): question -> static key -> IVF (Optane lists) top-N passages -> cross-encoder re-rank (ms-marco-MiniLM-L6-v2, as cowork-cli retrieval_v2) -> top-k passages to inject BEFORE inference (cowork paper: pre-injection 0.94 vs a retrieval tool 0.51-0.63; always-inject beats gated). from engram import Engram; eg = Engram(); eg.retrieve("question", k=3) -> [{pid, title, section, text, score}] python engram.py "question" # prints the hits Tables (10-20): "wiki" is the root table (index/, passages/); every other table is tables//{index,passages}. Engram(tables=["wiki", "health"]) splits the NCAND first-stage candidates over the tables and re-ranks them together; hits carry "table" (pids are only unique within a table). Env: NPROBE (512: 10-19 sweep, gold article in top 200 0.62 at 32 -> 0.68, flat after; 83 ms), NCAND (100), THREADS (4), TABLES (wiki), HYBRID (1: tables with a bm25/ index split their candidates half static, half BM25 - tools/bm25.py).""" import os, re, sys, glob, bisect, time import numpy as np, faiss, torch import pyarrow.parquet as pq sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import static_embed os.environ.setdefault("HF_HOME", "/mnt/optane/hf-cache") E = "/mnt/optane/engram" class Passages: """pid (file_idx << 32 | n) -> row n of passages/.parquet, read one 4096-row group at a time (cached)""" def __init__(self, root=E): self.files = {} for f in glob.glob(f"{root}/passages/*.parquet"): a, b = os.path.basename(f)[:-8].split("_"); pf = pq.ParquetFile(f) starts = np.cumsum([0] + [pf.metadata.row_group(i).num_rows for i in range(pf.metadata.num_row_groups)]) self.files[int(b) + 100 * int(a)] = (pf, starts) self.cache = {} def get(self, pid): fi, n = int(pid) >> 32, int(pid) & 0xFFFFFFFF pf, st = self.files[fi]; rg = bisect.bisect_right(st, n) - 1 key = (fi, rg) if key not in self.cache: if len(self.cache) > 512: self.cache.clear() self.cache[key] = pf.read_row_group(rg, columns=["title", "section", "text"]).to_pylist() return self.cache[key][n - st[rg]] def table_root(name): return E if name == "wiki" else f"{E}/tables/{name}" class Engram: def __init__(self, nprobe=int(os.environ.get("NPROBE", 512)), ncand=int(os.environ.get("NCAND", 100)), rerank=True, tables=None): faiss.omp_set_num_threads(int(os.environ.get("THREADS", 4))); torch.set_num_threads(int(os.environ.get("THREADS", 4))) self.tables, self.lex = {}, {} for t in tables or os.environ.get("TABLES", "wiki").split(","): path = os.environ.get("INDEX") if t == "wiki" and os.environ.get("INDEX") else f"{table_root(t)}/index/engram.index" ix = faiss.read_index(path) # OnDisk lists mmap themselves; IO_FLAG_MMAP here segfaults search faiss.extract_index_ivf(ix).nprobe = nprobe; self.tables[t] = (ix, Passages(table_root(t))) if os.environ.get("HYBRID", "1") != "0" and os.path.exists(f"{table_root(t)}/bm25/meta.json"): import bm25 self.lex[t] = bm25.open_index(table_root(t)) self.ncand = ncand; self.ce = None if rerank: from transformers import AutoTokenizer, AutoModelForSequenceClassification self.ct = AutoTokenizer.from_pretrained("cross-encoder/ms-marco-MiniLM-L6-v2") self.ce = AutoModelForSequenceClassification.from_pretrained("cross-encoder/ms-marco-MiniLM-L6-v2").eval() def candidates(self, q, n=None, tables=None): qv = static_embed.embed([q]); ts = [t for t in (tables or self.tables) if t in self.tables]; out = [] for t in ts: m = max(1, (n or self.ncand) // len(ts)); m_lex = m // 2 if t in self.lex else 0 s, ids = self.tables[t][0].search(qv, m - m_lex) got = [(t, int(i), float(v)) for i, v in zip(ids[0], s[0]) if i >= 0] if m_lex and q.strip(): lx = self.lex[t]; lx.reload(); se = lx.searcher(); seen = {i for _, i, _ in got} terms = re.sub(r"[\W_]+", " ", q.lower()).split() or ["the"] # one token per term: no phrase queries (no positions) for sc, a in se.search(lx.parse_query(" ".join(terms), ["text"]), m_lex + len(got)).hits: pid = se.doc(a)["pid"][0] if pid not in seen and len(got) < m: got.append((t, pid, float(sc))); seen.add(pid) out += got return out def retrieve(self, q, k=3, tables=None, extra=()): """extra: more first-stage queries (e.g. q + a draft answer, 10-20 two-pass); each gets an equal share of NCAND, the union is de-duplicated and re-ranked against q alone, so a draft can widen the net but cannot bias the ranking""" qs = [q] + [x for x in extra if x and x.strip()]; seen, cand = set(), [] for x in qs: for t, i, v in self.candidates(x, n=max(2, self.ncand // len(qs)), tables=tables): if (t, i) not in seen: seen.add((t, i)); cand.append((t, i, v)) hits = [dict(table=t, pid=i, first=v, **self.tables[t][1].get(i)) for t, i, v in cand] if self.ce is not None and hits: with torch.inference_mode(): b = self.ct([q] * len(hits), [h["text"] for h in hits], padding=True, truncation=True, max_length=256, return_tensors="pt") sc = self.ce(**b).logits[:, 0].tolist() for h, v in zip(hits, sc): h["score"] = v hits.sort(key=lambda h: -h["score"]) return hits[:k] if __name__ == "__main__": eg = Engram(); t0 = time.time() for h in eg.retrieve(" ".join(sys.argv[1:]), k=5): print(f"{h.get('score', h['first']):7.3f} {h['text'][:200]}") print(f"{time.time() - t0:.2f} s")