"""BM25 baseline for the Vietnamese benchmark (CPU). Same data loader, top-100 run and metrics as the GPU workers. Tokens: pyvi word segmentation (as for the PhoBERT models), lower-cased, punctuation-only tokens dropped. BM25 (bm25s, Lucene variant), k1 = 1.5, b = 0.75 (the law_search defaults). No stemming, no stop words. Usage: RESULTS=~/embed4090/nm/q python bm25_run.py [task ...]""" import os, sys, json, gzip, time, re, string from multiprocessing import Pool from pathlib import Path import numpy as np os.environ.setdefault("RESULTS", os.path.expanduser("~/embed4090/nm/q")) import data _argv, sys.argv = sys.argv, [sys.argv[0], "bm25"] # worker.py reads its worker id from argv[1] from worker import evaluate, to_run, K # noqa: E402 sys.argv = _argv R = Path(os.environ["RESULTS"]); NP = int(os.environ.get("BM25_PROCS", 46)) PUNCT = re.compile(r"^[\W_]+$", re.UNICODE) def toks(t): from pyvi.ViTokenizer import tokenize return [w for w in tokenize(" ".join(t.split())).lower().split() if not PUNCT.match(w)] def run(task): import bm25s corpus, queries, qrels = data.load_task(task) t0 = time.time() with Pool(NP) as p: D = p.map(toks, [data.doc_plain(d) for d in corpus], chunksize=64) Q = p.map(toks, [q["text"] for q in queries], chunksize=64) tseg = time.time() - t0 vocab = {} ids = lambda L: [[vocab.setdefault(w, len(vocab)) for w in x] for x in L] Di = ids(D); Qi = [[vocab[w] for w in x if w in vocab] for x in Q] t1 = time.time() m = bm25s.BM25(k1=1.5, b=0.75); m.index(bm25s.tokenization.Tokenized(ids=Di, vocab=vocab), show_progress=False) k = min(K + 1, len(corpus)) Qi = [x if x else [0] for x in Qi] I, S = m.retrieve(bm25s.tokenization.Tokenized(ids=Qi, vocab=vocab), k=k, show_progress=False, n_threads=NP) tret = time.time() - t1 qids, dids = [q["id"] for q in queries], [d["id"] for d in corpus] runr = to_run(S, I, qids, dids) met = evaluate(qrels, runr) rec = {"model": "bm25", "hf": "bm25s (pyvi tokens, k1=1.5, b=0.75)", "task": task, "dtype": "lexical", "max_len": None, "n_docs": len(corpus), "n_queries": len(queries), "seg_s": tseg, "index_retrieve_s": tret, "gpu": "cpu", "dim": None, "nan_rows": 0, **met, "wall_s": time.time() - t0} name = f"bm25__{task.replace(':', '_')}" (R / "metrics" / f"{name}.jsonl").write_text(json.dumps(rec) + "\n") (R / "runs" / "bm25").mkdir(parents=True, exist_ok=True) with gzip.open(R / "runs" / "bm25" / (task.replace(":", "_") + ".json.gz"), "wt") as f: json.dump({q: dict(sorted(v.items(), key=lambda x: -x[1])[:10]) for q, v in runr.items()}, f) (R / "done" / f"{name}.done").write_text(json.dumps({"s": rec["wall_s"], "wid": "cpu"})) print(f"{time.strftime('%H:%M:%S')} DONE {name} nDCG@10={met['ndcg10']:.2f} P@1={met['p1']:.2f} R@100={met['recall100']:.2f} " f"seg {tseg:.0f}s bm25 {tret:.0f}s", flush=True) if __name__ == "__main__": TASKS = ['ArguAna-VN', 'BelebeleRetrieval:vie_Latn-vie_Latn', 'FiQA2018-VN', 'GreenNodeTableMarkdownRetrieval', 'MLQARetrieval:vie-vie', 'NFCorpus-VN', 'PublicHealthQA:vietnamese', 'SciFact-VN', 'TVPLRetrieval', 'VieQuADRetrieval', 'WebFAQRetrieval:vie', 'XQuADRetrieval:vi', 'ZacLegalTextRetrieval'] for t in (sys.argv[1:] or TASKS): run(t) print("ALL_DONE", flush=True)