#!/usr/bin/env python3 """STAIR reproduction -- retrieval evaluation for one or all books. Modes: --selftest : validate metric math on synthetic gold/candidates (no data needed). --bm25 : rank leaves with a rank_bm25-style BM25Okapi implemented here, over leaf_docs tokenized text; per-book + macro metrics. --predictions FILE : load {book_id: {paragraph_id: [leaf_id, ...]}} JSON produced by a trained-model inference job; per-book + macro metrics. --hallucination-rate : fraction of test queries whose top candidate is not a valid leaf of the book (with --bm25 it is 0 by construction). Test questions are subsampled per book (--max-per-book, default 800) with a fixed seed -> deterministic across runs. Examples: python eval_retrieval.py --selftest python eval_retrieval.py --bm25 --book compgov --max-per-book 100 python eval_retrieval.py --predictions preds.json --hallucination-rate """ import argparse, json, math, os, random, re, sys from collections import Counter sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from stair_common import BOOKS, load_books, load_questions, evaluate_rankings TOKEN_RE = re.compile(r"[a-z0-9]+") # --------------------------------------------------------------------------- # # BM25 (rank_bm25.BM25Okapi-style, implemented manually) # # --------------------------------------------------------------------------- # def tokenize(text): return TOKEN_RE.findall(text.lower()) class BM25Okapi: """Okapi BM25 over pre-tokenized documents (same math as rank_bm25, including its epsilon flooring of negative idfs).""" def __init__(self, corpus_tokens, k1=1.5, b=0.75, epsilon=0.25): self.k1, self.b, self.epsilon = k1, b, epsilon self.doc_count = len(corpus_tokens) self.doc_len = [len(d) for d in corpus_tokens] self.avgdl = sum(self.doc_len) / max(1, self.doc_count) self.doc_freqs = [Counter(d) for d in corpus_tokens] df = Counter() for freqs in self.doc_freqs: for t in freqs: df[t] += 1 nd = self.doc_count self.idf = {t: math.log((nd - n + 0.5) / (n + 0.5) + 1) for t, n in df.items()} mean_idf = sum(self.idf.values()) / len(self.idf) if self.idf else 0.0 for t in list(self.idf): if self.idf[t] < 0: self.idf[t] = self.epsilon_floor(0.25, mean_idf) @staticmethod def epsilon_floor(epsilon, mean_idf): return epsilon * mean_idf def get_scores(self, query_tokens): scores = [0.0] * self.doc_count q = Counter(query_tokens) for i in range(self.doc_count): dl = self.doc_len[i] denom_bias = self.k1 * (1 - self.b + self.b * dl / self.avgdl) freqs = self.doc_freqs[i] s = 0.0 for t, qw in q.items(): f = freqs.get(t, 0) if f == 0: continue s += self.idf.get(t, 0.0) * f * (self.k1 + 1) / (f + denom_bias) scores[i] = s return scores def rank_leaves_bm25(query, leaf_docs, bm25): """leaf_ids ranked by BM25 score for `query` (descending).""" scores = bm25.get_scores(tokenize(query)) order = sorted(range(len(scores)), key=lambda i: -scores[i]) return [leaf_docs[i]["leaf_id"] for i in order] # --------------------------------------------------------------------------- # # Test-question loading + deterministic subsample # # --------------------------------------------------------------------------- # def subsample_test(questions, max_per_book, seed=42): """{book_id: [rec, ...]} -- deterministic subsample of the test split.""" rng = random.Random(seed) out = {} for book_id, per_split in questions.items(): test = list(per_split["test"]) if max_per_book and len(test) > max_per_book: test = rng.sample(test, max_per_book) out[book_id] = test return out def top1_hallucination_rate(ranked_by_query, valid_leaf_ids): """Fraction of queries whose TOP candidate is not a valid leaf id.""" valid = set(valid_leaf_ids) n = bad = 0 for qid, cands in ranked_by_query.items(): n += 1 if not cands or cands[0] not in valid: bad += 1 return bad / n if n else 0.0 # --------------------------------------------------------------------------- # def run_selftest(): """Validate metric math with known-answer cases (random gold / empty cands).""" from stair_common import recall_at_k, ndcg_at_k, evaluate_rankings ok = lambda c, m: abs(c - m) < 1e-9 cases = [] cases.append(("recall@1, gold at 1", recall_at_k(["a", "b", "c"], "a", 1), 1.0)) cases.append(("recall@1, gold at 2", recall_at_k(["a", "b", "c"], "b", 1), 0.0)) cases.append(("recall@3, gold at 3", recall_at_k(["a", "b", "c"], "c", 3), 1.0)) cases.append(("recall@3, gold missing", recall_at_k(["a", "b", "c"], "z", 3), 0.0)) cases.append(("recall@3, empty candidates", recall_at_k([], "a", 3), 0.0)) # nDCG@3, single gold: nDCG = 1/log2(rank+1) when gold is in the top-3 cases.append(("ndcg@3, gold at 1", ndcg_at_k(["a", "b", "c"], "a", 3), 1.0)) cases.append(("ndcg@3, gold at 2", ndcg_at_k(["a", "b", "c"], "b", 3), 1 / math.log2(3))) cases.append(("ndcg@3, gold at 3", ndcg_at_k(["a", "b", "c"], "c", 3), 1 / math.log2(4))) cases.append(("ndcg@3, gold at 4 (outside k)", ndcg_at_k(["a", "b", "c", "d"], "d", 3), 0.0)) cases.append(("ndcg@3, empty candidates", ndcg_at_k([], "a", 3), 0.0)) cases.append(("ndcg@3, gold None", ndcg_at_k(["a"], None, 3), 0.0)) # IDCG = 1/log2(min(3, len(ideal)) + 1) = 1 for a single gold e = evaluate_rankings({"q1": ["a", "b", "c"], "q2": ["x", "a", "c"], "q3": []}, {"q1": "a", "q2": "a", "q3": "a"}) cases.append(("macro recall@1", e["recall@1"], (1 + 0 + 0) / 3)) # q1 gold at rank 1 -> 1.0; q2 gold at rank 2 (in top-3) -> 1.0; q3 empty -> 0 cases.append(("macro recall@3", e["recall@3"], 2 / 3)) cases.append(("macro ndcg@3", e["ndcg@3"], (1.0 + 1 / math.log2(3)) / 3)) bad = [(n, got, exp) for n, got, exp in cases if not ok(got, exp)] for n, got, exp in cases: status = "ok " if ok(got, exp) else "FAIL" print(f" [{status}] {n:<28} got={got:.6f} expected={exp:.6f}") if bad: raise SystemExit(f"selftest FAILED: {len(bad)} case(s) wrong") print(f"selftest passed: {len(cases)}/{len(cases)} metric checks ok") def main(): ap = argparse.ArgumentParser() ap.add_argument("--selftest", action="store_true", help="validate metric math on synthetic data and exit") ap.add_argument("--book", action="append", default=None, help="book_id to evaluate (repeatable; default: all six)") ap.add_argument("--max-per-book", type=int, default=800, help="deterministic test subsample per book (default 800)") ap.add_argument("--bm25", action="store_true", help="rank leaves with built-in BM25Okapi over leaf_docs text") ap.add_argument("--predictions", default=None, help="JSON file {book_id: {paragraph_id: [leaf_id, ...]}} from a trained model") ap.add_argument("--hallucination-rate", action="store_true", help="also report fraction of test queries whose top candidate is not a valid leaf") ap.add_argument("--seed", type=int, default=42) args = ap.parse_args() if args.selftest: run_selftest() return if not args.bm25 and not args.predictions: ap.error("choose --bm25 or --predictions FILE (or --selftest)") books = load_books() questions = load_questions(splits=("test",)) all_ids = [bid for dom in BOOKS.values() for bid, _ in dom] want = set(args.book) if args.book else set(all_ids) sampled = {bid: qs for bid, qs in subsample_test(questions, args.max_per_book, seed=args.seed).items() if bid in want} preds_all = None if args.predictions: with open(args.predictions) as f: preds_all = json.load(f) per_book = {} for bid, test_recs in sampled.items(): b = books[bid] valid_ids = [l["leaf_id"] for l in b["leaves"]] ranked_by_query, gold_by_query = {}, {} if args.bm25: corpus = [d["text"] for d in b["leaf_docs"]] if not corpus: print(f"[warn] {bid}: no leaf_docs, skipping") continue bm25 = BM25Okapi([tokenize(d) for d in corpus]) for i, r in enumerate(test_recs): key = r.get("paragraph_id", str(i)) ranked_by_query[key] = rank_leaves_bm25(r["query"], b["leaf_docs"], bm25) gold_by_query[key] = r.get("leaf_id") else: preds = preds_all.get(bid, {}) for i, r in enumerate(test_recs): key = r.get("paragraph_id", str(i)) ranked_by_query[key] = preds.get(key, []) gold_by_query[key] = r.get("leaf_id") m = evaluate_rankings(ranked_by_query, gold_by_query, k=3) if args.hallucination_rate: m["hallucination_rate"] = (0.0 if args.bm25 else top1_hallucination_rate(ranked_by_query, valid_ids)) per_book[bid] = m hdr = f"{'book':<22}{'n':>6}{'recall@1':>10}{'recall@3':>10}{'ndcg@3':>10}" if args.hallucination_rate: hdr += f"{'halluc':>10}" print(hdr) for bid, m in per_book.items(): line = f"{bid:<22}{m['n']:>6}{m['recall@1']:>10.4f}{m['recall@3']:>10.4f}{m['ndcg@3']:>10.4f}" if args.hallucination_rate: line += f"{m.get('hallucination_rate', 0.0):>10.4f}" print(line) if per_book: n_books = len(per_book) macro = {k: sum(m[k] for m in per_book.values()) / n_books for k in ("recall@1", "recall@3", "ndcg@3")} line = f"{'MACRO-AVG':<22}{'':>6}{macro['recall@1']:>10.4f}{macro['recall@3']:>10.4f}{macro['ndcg@3']:>10.4f}" if args.hallucination_rate: line += f"{sum(m.get('hallucination_rate', 0.0) for m in per_book.values()) / n_books:>10.4f}" print(line) if __name__ == "__main__": main()