"""index.py - the engram's key table: a faiss IVF (inner product, SQ8 codes) over every static passage key in emb_static/, with its inverted lists on Optane (OnDiskInvertedLists) so only the 16k centroids sit in RAM (10-19). Steps: train on a TRAIN-vector sample spread over all shards -> per-shard sub-indexes (index/shard_*.index) -> merge into index/engram.index + index/lists.ivfdata. Resumable per step. Env: EMB (emb_static/), OUT (index/), NLIST (16384), TRAIN (1000000), THREADS (4), NSHARDS (optional cap; default all shards - the old 999 default silently dropped health's last 19 shards).""" import os, glob, time import numpy as np, faiss from faiss.contrib.ondisk import merge_ondisk E = "/mnt/optane/engram"; OUT = os.environ.get("OUT", f"{E}/index"); os.makedirs(OUT, exist_ok=True) NLIST = int(os.environ.get("NLIST", 16384)); NTRAIN = int(os.environ.get("TRAIN", 1_000_000)) faiss.omp_set_num_threads(int(os.environ.get("THREADS", 4))) log = lambda *a: print(time.strftime("%H:%M:%S"), *a, flush=True) shards = sorted(f for f in glob.glob(f"{os.environ.get('EMB', E + '/emb_static')}/*.npy") if not f.endswith(".pid.npy") and ".tmp" not in f)[:int(os.environ.get("NSHARDS", 10**9))] mm = [np.load(f, mmap_mode="r") for f in shards]; D = mm[0].shape[1]; N = sum(len(m) for m in mm) log(f"{len(shards)} shards, {N} keys, dim {D}") tr = f"{OUT}/trained.index" if not os.path.exists(tr): rng = np.random.default_rng(0); per = NTRAIN // len(mm) X = np.concatenate([m[np.sort(rng.choice(len(m), min(per, len(m)), replace=False))] for m in mm]).astype(np.float32) ix = faiss.index_factory(D, f"IVF{NLIST}_HNSW32,SQ8", faiss.METRIC_INNER_PRODUCT) t0 = time.time(); ix.train(X); faiss.write_index(ix, tr); log(f"trained on {len(X)} in {time.time() - t0:.0f} s"); del X for f, m in zip(shards, mm): o = f"{OUT}/shard_{os.path.basename(f)[:-4]}.index" if os.path.exists(o): continue ix = faiss.read_index(tr); pid = np.load(f[:-4] + ".pid.npy"); t0 = time.time() for i in range(0, len(m), 500_000): ix.add_with_ids(np.ascontiguousarray(m[i:i + 500_000], dtype=np.float32), pid[i:i + 500_000]) faiss.write_index(ix, o + ".tmp"); os.replace(o + ".tmp", o); log(f"{o}: {ix.ntotal} in {time.time() - t0:.0f} s") if not os.path.exists(f"{OUT}/engram.index"): ix = faiss.read_index(tr); t0 = time.time() merge_ondisk(ix, sorted(glob.glob(f"{OUT}/shard_*.index")), f"{OUT}/lists.ivfdata") faiss.write_index(ix, f"{OUT}/engram.index"); log(f"merged {ix.ntotal} keys in {time.time() - t0:.0f} s") for f in glob.glob(f"{OUT}/shard_*.index"): os.remove(f) # their lists now live in lists.ivfdata