Download code/bm25.py from tablinum/beam-engram-tables: direct link, hf CLI and curl.
- Browser
- Download file 2.17 kB
-
https://huggingface.co/datasets/tablinum/beam-engram-tables/resolve/main/code/bm25.py
- Command line
-
hf download hf://datasets/tablinum/beam-engram-tables/code/bm25.py
-
curl -L -o bm25.py https://huggingface.co/datasets/tablinum/beam-engram-tables/resolve/main/code/bm25.py
2.17 kB
| """bm25.py TABLE - lexical (BM25) first stage for an engram table (10-20). The static keys average token vectors, so rare exact | |
| identifiers (json_encode flags, zoneinfo.TZPATH, case names, gene symbols) blur away; BM25 keeps them. tantivy index of the | |
| passage text (en_stem, term frequencies only, no positions, nothing stored but the pid) in <table>/bm25/, built from the | |
| table's passages/*.parquet. Resumable per passage file (bm25/done.txt). engram.py merges its hits with the static ones before | |
| the re-rank. Env: THREADS (2), HEAP_MB (1000).""" | |
| import os, sys, glob, time | |
| import pyarrow.parquet as pq, tantivy | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| E = "/mnt/optane/engram" | |
| def schema(): | |
| sb = tantivy.SchemaBuilder() | |
| sb.add_text_field("text", stored=False, tokenizer_name="en_stem", index_option="freq") | |
| sb.add_integer_field("pid", stored=True, indexed=False, fast=False) | |
| return sb.build() | |
| def open_index(root, create=False): | |
| d = f"{root}/bm25" | |
| if create: | |
| os.makedirs(d, exist_ok=True) | |
| return tantivy.Index(schema(), path=d, reuse=True) | |
| if __name__ == "__main__": | |
| t = sys.argv[1]; root = E if t == "wiki" else f"{E}/tables/{t}" | |
| ix = open_index(root, create=True); donef = f"{root}/bm25/done.txt" | |
| done = set(open(donef).read().split()) if os.path.exists(donef) else set() | |
| w = ix.writer(heap_size=int(os.environ.get("HEAP_MB", 1000)) * 1_000_000, num_threads=int(os.environ.get("THREADS", 2))) | |
| for f in sorted(glob.glob(f"{root}/passages/*.parquet")): | |
| name = os.path.basename(f) | |
| if name in done: | |
| continue | |
| t0 = time.time(); n = 0 | |
| for b in pq.ParquetFile(f).iter_batches(batch_size=8192, columns=["pid", "text"]): | |
| for pid, text in zip(b.column("pid").to_pylist(), b.column("text").to_pylist()): | |
| w.add_document(tantivy.Document(text=text, pid=pid)); n += 1 | |
| w.commit(); open(donef, "a").write(name + "\n") | |
| print(f"{time.strftime('%H:%M:%S')} {t} {name}: {n} in {time.time() - t0:.0f} s", flush=True) | |
| w.wait_merging_threads() | |
| print(f"{time.strftime('%H:%M:%S')} {t} bm25 done", flush=True) | |