MedIR-RAG-Milestone1 / src /experiment.py
OurShash's picture
MedIR-RAG Milestone 1: BM25 baseline, saved Terrier index and evaluation artefacts
737c451 verified
Raw History Blame Contribute Delete
32.2 kB
"""Stages B-E -- indexing, BM25 baseline, development tuning, test evaluation, efficiency.
Design rules enforced here:
* the test split is touched only once, after the configuration is frozen from dev;
* all metrics come from pytrec_eval (trec_eval) applied to real retrieval runs;
* MRR@10 uses a run truncated to depth 10, never the untruncated recip_rank;
* retrieval depth is identical (1000) for every configuration.
Outputs (results/raw/): dev_grid.csv, selected_config.json, test_default.trec,
test_tuned.trec, test_per_query.csv, test_summary.json, experiment_manifest.json,
metric_validation.json
"""
from __future__ import annotations
import argparse
import json
import os
import platform
import statistics
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
import numpy as np
import pandas as pd
ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "data"
INDEX_ROOT = ROOT / "index"
INDEX_PATH = INDEX_ROOT / "terrier_bm25"
RAW = ROOT / "results" / "raw"
RETRIEVAL_DEPTH = 1000
DEFAULT_K1, DEFAULT_B = 1.2, 0.75
K1_GRID = (0.6, 0.9, 1.2, 1.5, 1.8)
B_GRID = (0.3, 0.5, 0.75, 0.9)
SELECTION_METRIC = "NDCG@10"
RANDOM_SEED = 42
# pytrec_eval measure -> report label. MRR@10 is handled separately (truncated run).
MEASURES = {
"ndcg_cut_5": "NDCG@5",
"ndcg_cut_10": "NDCG@10",
"map_cut_1000": "MAP",
"recall_100": "Recall@100",
}
MRR_LABEL = "MRR@10"
METRIC_ORDER = ["NDCG@5", "NDCG@10", "MRR@10", "MAP", "Recall@100"]
# --------------------------------------------------------------------------- #
# environment
# --------------------------------------------------------------------------- #
def ensure_java() -> None:
"""Use JAVA_HOME if set, else the project-local portable JDK in .jdk/."""
if os.environ.get("JAVA_HOME") and Path(os.environ["JAVA_HOME"], "bin", "java.exe").exists():
return
local = sorted((ROOT / ".jdk").glob("*/bin/java.exe"))
if local:
os.environ["JAVA_HOME"] = str(local[0].parent.parent)
os.environ["PATH"] = str(local[0].parent) + os.pathsep + os.environ.get("PATH", "")
def import_pyterrier():
ensure_java()
import pyterrier as pt
if not pt.java.started():
pt.java.init()
return pt
def _versions(packages: list[str]) -> dict:
from importlib.metadata import PackageNotFoundError, version
out = {}
for p in packages:
try:
out[p] = version(p)
except PackageNotFoundError:
out[p] = None
return out
# --------------------------------------------------------------------------- #
# data
# --------------------------------------------------------------------------- #
def load_split(split: str):
queries = pd.read_parquet(DATA / f"queries_{split}.parquet")
qrels = pd.read_parquet(DATA / f"qrels_{split}.parquet")
queries["id"] = queries["id"].astype(str)
queries["text"] = queries["text"].astype(str)
qrels["query_id"] = qrels["query_id"].astype(str)
qrels["corpus_id"] = qrels["corpus_id"].astype(str)
qrels["score"] = qrels["score"].astype(int)
return queries, qrels
def qrels_dict(qrels: pd.DataFrame) -> dict[str, dict[str, int]]:
out: dict[str, dict[str, int]] = {}
for qid, grp in qrels.groupby("query_id", sort=True):
out[str(qid)] = {
str(d): int(s) for d, s in zip(grp["corpus_id"], grp["score"])
}
return out
def topics_frame(queries: pd.DataFrame) -> pd.DataFrame:
return pd.DataFrame({"qid": queries["id"].astype(str), "query": queries["text"]})
def indexed_population(qrels: dict[str, dict[str, int]]) -> list[str]:
"""Queries with at least one positive judgment: the evaluated population."""
return sorted(q for q, judged in qrels.items() if any(v > 0 for v in judged.values()))
# --------------------------------------------------------------------------- #
# indexing
# --------------------------------------------------------------------------- #
def build_index(pt, force: bool = False) -> dict:
"""Build the Terrier inverted index (title+abstract), or reuse it if present."""
info_file = INDEX_ROOT / "index_build_info.json"
done = (INDEX_PATH / "data.properties").exists()
if done and not force:
print(f"[index] reusing {INDEX_PATH}")
prior = json.loads(info_file.read_text()) if info_file.exists() else {}
prior.update({"built": False, "reused": True, "path": str(INDEX_PATH)})
return prior
if INDEX_PATH.exists() and force:
import shutil
shutil.rmtree(INDEX_PATH)
INDEX_ROOT.mkdir(parents=True, exist_ok=True)
corpus = pd.read_parquet(DATA / "corpus.parquet")
corpus["id"] = corpus["id"].astype(str)
corpus = corpus[corpus["text"].astype(str).str.strip() != ""]
meta = {"docno": 20, "title": 400, "abstract": 4000}
def docs():
for r in corpus.itertuples(index=False):
yield {
"docno": r.id,
"title": str(r.title)[:390],
"abstract": str(r.text)[:3990],
"text": str(r.text),
}
indexer = pt.terrier.IterDictIndexer(
str(INDEX_PATH),
meta=meta,
text_attrs=["text"],
tokeniser="english",
stemmer="porter",
stopwords="terrier",
threads=1,
)
t0 = time.perf_counter()
indexer.index(docs())
build_s = time.perf_counter() - t0
info = {
"built": True,
"path": str(INDEX_PATH),
"build_seconds": round(build_s, 3),
"built_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"documents_indexed": int(len(corpus)),
"documents_excluded_empty_text": int(
len(pd.read_parquet(DATA / "corpus.parquet")) - len(corpus)
),
"tokeniser": "english (Terrier EnglishTokeniser)",
"stemmer": "porter",
"stopwords": "terrier",
"indexed_field": "text = title + abstract",
"meta_fields": meta,
}
INDEX_ROOT.mkdir(parents=True, exist_ok=True)
(INDEX_ROOT / "index_build_info.json").write_text(json.dumps(info, indent=2))
return info
def open_index(pt):
return pt.terrier.TerrierIndex(str(INDEX_PATH))
def index_stats(pt, index, build_info: dict) -> dict:
stats = index.index_obj().getCollectionStatistics()
n_docs = int(stats.getNumberOfDocuments())
n_tokens = int(stats.getNumberOfTokens())
n_terms = int(stats.getNumberOfUniqueTerms())
n_postings = int(stats.getNumberOfPointers())
disk = sum(p.stat().st_size for p in INDEX_PATH.rglob("*") if p.is_file())
props = {}
prop_file = INDEX_PATH / "data.properties"
if prop_file.exists():
for line in prop_file.read_text(encoding="utf-8", errors="ignore").splitlines():
if "=" in line and not line.startswith("#"):
k, v = line.split("=", 1)
if k.strip() in {
"terrier.termpipelines",
"index.terrier.tokeniser",
"index.terrier.stemmer",
"index.meta.reverse",
"index.terrier.stopwords",
}:
props[k.strip()] = v.strip()
return {
"documents_indexed": n_docs,
"vocabulary_size": n_terms,
"postings": n_postings,
"tokens_indexed": n_tokens,
"mean_document_length_tokens": round(n_tokens / max(n_docs, 1), 3),
"index_disk_mb": round(disk / 1e6, 2),
"index_path": str(INDEX_PATH),
"build_seconds": build_info.get("build_seconds"),
"index_properties": props,
}
# --------------------------------------------------------------------------- #
# retrieval and evaluation
# --------------------------------------------------------------------------- #
def retrieve(retriever, queries: pd.DataFrame, depth: int = RETRIEVAL_DEPTH) -> pd.DataFrame:
"""Run BM25 over a queries frame (id/text) or topics frame (qid/query)."""
topics = queries if "qid" in queries.columns else topics_frame(queries)
t0 = time.perf_counter()
res = retriever.transform(topics)
elapsed = time.perf_counter() - t0
if len(res) == 0:
return pd.DataFrame(columns=["qid", "docno", "rank", "score"]), elapsed
res = res[["qid", "docno", "rank", "score"]].copy()
res["qid"] = res["qid"].astype(str)
res["docno"] = res["docno"].astype(str)
res = res[res["rank"] < depth]
return res.reset_index(drop=True), elapsed
def run_dict(run_df: pd.DataFrame, depth: int) -> dict[str, dict[str, float]]:
"""TREC run as {qid: {docno: score}}, truncated to the top `depth` ranks."""
out: dict[str, dict[str, float]] = {}
if len(run_df) == 0:
return out
truncated = run_df[run_df["rank"] < depth].sort_values(["qid", "rank"])
for qid, grp in truncated.groupby("qid", sort=False):
out[str(qid)] = {
str(d): float(s) for d, s in zip(grp["docno"], grp["score"])
}
return out
def evaluate_run(
qrels: dict[str, dict[str, int]],
run: dict[str, dict[str, float]],
population: list[str],
) -> tuple[dict[str, dict[str, float]], dict]:
"""Per-query metrics with pytrec_eval over a fixed query population.
Queries in the population with no retrieved documents are padded with an empty
result list, so they score zero instead of disappearing from the mean.
"""
import pytrec_eval
judged = {q: qrels[q] for q in population}
padded_run = {q: run.get(q, {}) for q in population}
evaluator = pytrec_eval.RelevanceEvaluator(judged, set(MEASURES))
raw = evaluator.evaluate(padded_run)
run_at_10 = {
q: {d: s for d, s in list(padded_run[q].items())[:10]} for q in population
}
mrr_eval = pytrec_eval.RelevanceEvaluator(judged, {"recip_rank"})
mrr_raw = mrr_eval.evaluate(run_at_10)
per_query: dict[str, dict[str, float]] = {}
for qid in population:
row = {label: float(raw[qid][m]) for m, label in MEASURES.items()}
row[MRR_LABEL] = float(mrr_raw[qid]["recip_rank"])
per_query[qid] = row
missing = [q for q in population if q not in raw]
if missing: # pragma: no cover - pytrec_eval always returns padded queries
raise RuntimeError(f"pytrec_eval dropped {len(missing)} queries")
aggregate = {
label: float(np.mean([per_query[q][label] for q in population]))
for label in METRIC_ORDER
}
return per_query, aggregate
def truncation_effect(run: dict[str, dict[str, float]], depth: int) -> dict:
lengths = [len(v) for v in run.values()]
return {
"retrieval_depth": depth,
"queries_returning_full_depth": int(sum(1 for n in lengths if n >= depth)),
"queries_with_no_results": int(sum(1 for n in lengths if n == 0)),
"mean_results_per_query": round(float(np.mean(lengths)), 2) if lengths else 0.0,
"max_results_per_query": int(max(lengths)) if lengths else 0,
"note": (
"MAP is computed as map_cut_1000: relevant documents ranked below the "
"1000-result cutoff are invisible to the metric"
),
}
def evaluate_with_selection_metric(
retriever, topics: pd.DataFrame, qrels: dict, population: list[str]
) -> tuple[dict, dict[str, dict[str, float]], float, pd.DataFrame]:
run_df, elapsed = retrieve(retriever, topics)
run = run_dict(run_df, RETRIEVAL_DEPTH)
per_query, aggregate = evaluate_run(qrels, run, population)
return aggregate, per_query, elapsed, run_df
# --------------------------------------------------------------------------- #
# metric self-validation (deterministic synthetic cases)
# --------------------------------------------------------------------------- #
def validate_metrics() -> dict:
"""Prove the metric implementation on rankings whose values are known by hand."""
import math
cases = []
def check(name, qrels, run, expected, tol=1e-9):
per_query, aggregate = evaluate_run(qrels, run, sorted(qrels))
ok = all(abs(aggregate[k] - v) <= tol for k, v in expected.items())
cases.append(
{
"case": name,
"expected": expected,
"measured": aggregate,
"passed": bool(ok),
"difference": {
k: round(abs(aggregate[k] - v), 12) for k, v in expected.items()
},
}
)
# 1. relevant doc at rank 2 out of 2 retrieved
check(
"single relevant at rank 2",
{"q1": {"d1": 1}},
{"q1": {"d9": 3.0, "d1": 1.0}},
{
"NDCG@5": 1 / math.log2(3),
"NDCG@10": 1 / math.log2(3),
"MRR@10": 0.5,
"MAP": 0.5,
"Recall@100": 1.0,
},
)
# 2. relevant doc at rank 11 -> MRR@10 must be exactly zero, MAP stays 1/11
rank11 = {f"dx{i}": float(100 - i) for i in range(10)}
rank11["d1"] = 1.0
check(
"relevant at rank 11 (strict MRR@10 cutoff)",
{"q1": {"d1": 1}},
{"q1": rank11},
{"MRR@10": 0.0, "MAP": 1 / 11, "Recall@100": 1.0},
)
# 3. queries with no retrieved documents score zero and stay in the mean
check(
"empty result list contributes zero",
{"q1": {"d1": 1}, "q2": {"d2": 1}},
{"q1": {"d1": 1.0}, "q2": {}},
{"NDCG@5": 0.5, "NDCG@10": 0.5, "MRR@10": 0.5, "MAP": 0.5, "Recall@100": 0.5},
)
# 4. graded qrels: trec_eval ndcg_cut uses LINEAR gain (gain = relevance grade),
# while AP treats any grade > 0 as relevant
ideal = 2 / math.log2(2) + 1 / math.log2(3)
actual = 1 / math.log2(2) + 2 / math.log2(3)
check(
"graded relevance ordering (linear gain)",
{"q1": {"d1": 2, "d2": 1}},
{"q1": {"d2": 2.0, "d1": 1.0}},
{
"NDCG@5": actual / ideal,
"NDCG@10": actual / ideal,
"MRR@10": 1.0,
"MAP": 1.0,
"Recall@100": 1.0,
},
)
# 5. Recall@100 uses all judged relevant documents
ranked = {f"d{i}": float(200 - i) for i in range(1, 201)}
check(
"recall@100 restricted to the first 100 ranks",
{"q1": {"d1": 1, "d150": 1}},
{"q1": ranked},
{"Recall@100": 0.5, "MRR@10": 1.0},
)
result = {
"generated_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"evaluator": "pytrec_eval (trec_eval bindings)",
"all_passed": all(c["passed"] for c in cases),
"cases": cases,
}
RAW.mkdir(parents=True, exist_ok=True)
(RAW / "metric_validation.json").write_text(json.dumps(result, indent=2))
return result
def cross_check_with_ir_measures(qrels: dict, run: dict, population: list[str]) -> dict:
"""Independent second implementation (ir_measures) on the same run."""
try:
import ir_measures
from ir_measures import AP, RR, Recall, nDCG
except Exception as exc: # pragma: no cover
return {"available": False, "error": str(exc)}
q = [{"query_id": qid, "doc_id": d, "relevance": s}
for qid in population for d, s in qrels[qid].items()]
r = [{"query_id": qid, "doc_id": d, "score": s, **{"rank": i}}
for qid in population
for i, (d, s) in enumerate(run.get(qid, {}).items(), start=1)]
qdf, rdf = pd.DataFrame(q), pd.DataFrame(r)
try:
m = ir_measures.calc_aggregate(
[nDCG @ 5, nDCG @ 10, RR @ 10, AP @ 1000, Recall @ 100], qdf, rdf
)
except Exception as exc: # pragma: no cover
return {"available": False, "error": str(exc)}
return {
"available": True,
"values": {str(k): round(float(v), 6) for k, v in m.items()},
}
# --------------------------------------------------------------------------- #
# development grid
# --------------------------------------------------------------------------- #
def dev_grid_search(pt, index, dev_queries, dev_qrels, population) -> tuple[dict, pd.DataFrame]:
rows = []
per_query_store = {}
for k1 in K1_GRID:
for b in B_GRID:
retriever = index.bm25(k1=k1, b=b, num_results=RETRIEVAL_DEPTH)
aggregate, per_query, elapsed, _ = evaluate_with_selection_metric(
retriever, dev_queries, dev_qrels, population
)
per_query_store[(k1, b)] = {q: per_query[q]["NDCG@10"] for q in population}
rows.append(
{
"k1": k1,
"b": b,
**aggregate,
"retrieval_seconds": round(elapsed, 3),
"queries_per_second": round(len(population) / elapsed, 2) if elapsed else None,
}
)
print(f"[dev] k1={k1:<4} b={b:<5} NDCG@10={aggregate['NDCG@10']:.4f} "
f"NDCG@5={aggregate['NDCG@5']:.4f} ({elapsed:.1f}s)")
grid = pd.DataFrame(rows)
# deterministic selection: best NDCG@10, then best NDCG@5, then closest to the
# conventional defaults, then lowest k1 and lowest b.
grid["_default_distance"] = (grid["k1"] - DEFAULT_K1).abs() + (grid["b"] - DEFAULT_B).abs()
ranked = grid.sort_values(
["NDCG@10", "NDCG@5", "_default_distance", "k1", "b"],
ascending=[False, False, True, True, True],
kind="mergesort",
).reset_index(drop=True)
best = ranked.iloc[0]
sel_k1, sel_b = float(best["k1"]), float(best["b"])
selected = {
"k1": sel_k1,
"b": sel_b,
"selection_metric": SELECTION_METRIC,
"selection_value": float(best["NDCG@10"]),
"selection_split": "dev",
"tie_break_rule": (
"highest dev NDCG@10, then highest dev NDCG@5, then smallest distance to "
"the conventional default (k1=1.2, b=0.75), then lowest k1 and b"
),
"grid": {"k1": list(K1_GRID), "b": list(B_GRID)},
"configurations_evaluated": int(len(grid)),
"default_configuration": {"k1": DEFAULT_K1, "b": DEFAULT_B},
"selected_is_default": bool(
abs(sel_k1 - DEFAULT_K1) < 1e-12 and abs(sel_b - DEFAULT_B) < 1e-12
),
"optimum_on_grid_boundary": bool(
sel_k1 in (K1_GRID[0], K1_GRID[-1]) or sel_b in (B_GRID[0], B_GRID[-1])
),
}
grid = ranked.drop(columns=["_default_distance"]).reset_index(drop=True)
grid["selected"] = (
(grid["k1"] == selected["k1"]) & (grid["b"] == selected["b"])
)
grid["n_queries"] = len(population)
grid.to_csv(RAW / "dev_grid.csv", index=False)
(RAW / "selected_config.json").write_text(json.dumps(selected, indent=2))
# paired bootstrap on dev: tuned vs default NDCG@10 (selection-stability evidence)
rng = np.random.default_rng(RANDOM_SEED)
d_default = np.array([per_query_store[(DEFAULT_K1, DEFAULT_B)][q] for q in population])
d_tuned = np.array([per_query_store[(selected["k1"], selected["b"])][q] for q in population])
diffs = [float(np.mean(rng.choice(d_tuned - d_default, size=len(population), replace=True)))
for _ in range(1000)]
selected["dev_default_vs_tuned_bootstrap_note"] = (
"bootstrap CI is computed in analysis/build_evidence.py for the test split; "
"this interval is dev-only and is not used for any claim"
)
selected["dev_bootstrap_mean_difference_ndcg10"] = {
"mean_difference": round(float(np.mean(d_tuned - d_default)), 6),
"ci95_low": round(float(np.percentile(diffs, 2.5)), 6),
"ci95_high": round(float(np.percentile(diffs, 97.5)), 6),
"replicates": 1000,
}
(RAW / "selected_config.json").write_text(json.dumps(selected, indent=2))
return selected, grid
# --------------------------------------------------------------------------- #
# TREC output
# --------------------------------------------------------------------------- #
def write_trec(run_df: pd.DataFrame, path: Path, run_id: str) -> int:
rows = 0
with path.open("w", encoding="utf-8") as fh:
for qid, grp in run_df.sort_values(["qid", "rank"]).groupby("qid", sort=True):
for docno, rank, score in zip(grp["docno"], grp["rank"], grp["score"]):
fh.write(f"{qid} Q0 {docno} {int(rank) + 1} {float(score):.6f} {run_id}\n")
rows += 1
return rows
# --------------------------------------------------------------------------- #
# efficiency
# --------------------------------------------------------------------------- #
def benchmark(pt, index, queries: pd.DataFrame, k1: float, b: float, label: str,
warmup: int = 20) -> dict:
"""Retrieval latency/throughput with a warm cache and per-query timing."""
retriever = index.bm25(k1=k1, b=b, num_results=RETRIEVAL_DEPTH)
topics = topics_frame(queries)
for _, row in topics.head(warmup).iterrows():
retriever.search(row["query"])
latencies = []
empty = 0
t_all = time.perf_counter()
for _, row in topics.iterrows():
t0 = time.perf_counter()
res = retriever.search(row["query"])
latencies.append(time.perf_counter() - t0)
if len(res) == 0:
empty += 1
total = time.perf_counter() - t_all
arr = np.array(latencies) * 1000.0
return {
"configuration": label,
"k1": k1,
"b": b,
"queries_benchmarked": int(len(topics)),
"warmup_queries": int(min(warmup, len(topics))),
"total_seconds": round(total, 3),
"throughput_queries_per_second": round(len(topics) / total, 2),
"latency_ms_mean": round(float(arr.mean()), 3),
"latency_ms_median": round(float(np.median(arr)), 3),
"latency_ms_p95": round(float(np.percentile(arr, 95)), 3),
"queries_with_zero_results": int(empty),
"zero_result_proportion": round(empty / len(topics), 4),
"method": "time.perf_counter around single-query search(); dataset download, "
"indexing and JVM start-up excluded; warm-up queries discarded",
}
# --------------------------------------------------------------------------- #
# main
# --------------------------------------------------------------------------- #
def main() -> int:
ap = argparse.ArgumentParser(description="BM25 recovery experiment (Milestone 1)")
ap.add_argument("--rebuild-index", action="store_true", help="force index rebuild")
ap.add_argument("--skip-benchmark", action="store_true")
args = ap.parse_args()
RAW.mkdir(parents=True, exist_ok=True)
started = datetime.now(timezone.utc)
validation = validate_metrics()
print(f"[validate] metric self-test all_passed={validation['all_passed']}")
if not validation["all_passed"]:
print("[validate] FAILED - refusing to run with an unvalidated evaluator", file=sys.stderr)
return 2
pt = import_pyterrier()
build_info = build_index(pt, force=args.rebuild_index)
index = open_index(pt)
stats = index_stats(pt, index, build_info)
print(f"[index] docs={stats['documents_indexed']} vocab={stats['vocabulary_size']} "
f"mean_len={stats['mean_document_length_tokens']} "
f"disk={stats['index_disk_mb']}MB build={stats['build_seconds']}s")
dev_queries, dev_qrels = load_split("dev")
test_queries, test_qrels = load_split("test")
dev_q = qrels_dict(dev_qrels)
test_q = qrels_dict(test_qrels)
dev_pop = indexed_population(dev_q)
test_pop = indexed_population(test_q)
test_all = sorted(test_queries["id"].astype(str))
print(f"[data] dev population={len(dev_pop)} test population={len(test_pop)} "
f"(published test queries={len(test_all)})")
selected, _grid = dev_grid_search(pt, index, dev_queries, dev_q, dev_pop)
print(f"[dev] selected k1={selected['k1']} b={selected['b']} "
f"(dev NDCG@10={selected['selection_value']:.4f})")
# ---------------- frozen final evaluation on the test split ----------------
results = {}
per_query_frames = []
for label, (k1, b), fname, run_id in [
("default", (DEFAULT_K1, DEFAULT_B), "test_default.trec", "bm25_default"),
("tuned", (selected["k1"], selected["b"]), "test_tuned.trec", "bm25_tuned"),
]:
retriever = index.bm25(k1=k1, b=b, num_results=RETRIEVAL_DEPTH)
aggregate, per_query, elapsed, run_df = evaluate_with_selection_metric(
retriever, test_queries, test_q, test_pop
)
# every published test query is written to the run file, even if unjudged
write_trec(run_df, RAW / fname, run_id)
run = run_dict(run_df, RETRIEVAL_DEPTH)
cross = cross_check_with_ir_measures(test_q, run, test_pop)
results[label] = {
"k1": k1,
"b": b,
"metrics": aggregate,
"retrieval_seconds": round(elapsed, 3),
"cross_check_ir_measures": cross,
"truncation": truncation_effect(run, RETRIEVAL_DEPTH),
"run_file": fname,
"run_id": run_id,
}
pq = pd.DataFrame(
[
{"query_id": q, **{f"{label}_{m}": per_query[q][m] for m in METRIC_ORDER}}
for q in test_pop
]
)
per_query_frames.append(pq)
print(f"[test:{label}] k1={k1} b={b} " + " ".join(
f"{m}={aggregate[m]:.4f}" for m in METRIC_ORDER))
# per-query table over ALL published test queries; unjudged queries stay visible
pq = per_query_frames[0].merge(per_query_frames[1], on="query_id", how="outer")
all_q = pd.DataFrame({"query_id": test_all})
all_q["has_positive_qrel"] = all_q["query_id"].isin(test_pop)
pq = all_q.merge(pq, on="query_id", how="left")
run_counts = {}
for label, fname in [("default", "test_default.trec"), ("tuned", "test_tuned.trec")]:
df = pd.read_csv(RAW / fname, sep=" ", header=None,
names=["qid", "Q0", "docno", "rank", "score", "runid"])
run_counts[label] = df.groupby("qid").size().to_dict()
pq["n_retrieved_default"] = pq["query_id"].map(run_counts["default"]).fillna(0).astype(int)
pq["n_retrieved_tuned"] = pq["query_id"].map(run_counts["tuned"]).fillna(0).astype(int)
pq.to_csv(RAW / "test_per_query.csv", index=False)
# sensitivity analysis: all published test queries, unjudged counted as zero
sensitivity = {}
for label in ("default", "tuned"):
vals = {}
for m in METRIC_ORDER:
col = f"{label}_{m}"
vals[m] = round(float(pq[col].fillna(0.0).mean()), 6)
sensitivity[label] = vals
deltas = {
m: round(results["tuned"]["metrics"][m] - results["default"]["metrics"][m], 6)
for m in METRIC_ORDER
}
summary = {
"generated_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"evaluation_depth": RETRIEVAL_DEPTH,
"primary_population": {
"name": "test queries with at least one positive judgment",
"n_queries": len(test_pop),
"published_test_queries": len(test_all),
"unjudged_test_queries": len(test_all) - len(test_pop),
},
"qrels": {
"graded": False,
"grades": sorted({v for judged in test_q.values() for v in judged.values()}),
"positive_judgments": int(sum(len(v) for v in test_q.values())),
},
"metric_definitions": {
"NDCG@5": "pytrec_eval ndcg_cut_5 (trec_eval: linear gain = relevance grade)",
"NDCG@10": "pytrec_eval ndcg_cut_10 (linear gain)",
"MRR@10": "pytrec_eval recip_rank on the run truncated to the top 10 ranks",
"MAP": "pytrec_eval map_cut_1000 (declared depth 1000)",
"Recall@100": "pytrec_eval recall_100 (all judged relevant documents)",
},
"results": {
label: {
"k1": r["k1"],
"b": r["b"],
"metrics": r["metrics"],
"retrieval_seconds": r["retrieval_seconds"],
"truncation": r["truncation"],
"cross_check_ir_measures": r["cross_check_ir_measures"],
"run_file": r["run_file"],
}
for label, r in results.items()
},
"absolute_delta_tuned_minus_default": deltas,
"sensitivity_all_published_test_queries": sensitivity,
"selected_configuration": selected,
}
(RAW / "test_summary.json").write_text(json.dumps(summary, indent=2))
benchmarks = []
if not args.skip_benchmark:
benchmarks.append(benchmark(pt, index, test_queries, DEFAULT_K1, DEFAULT_B, "default"))
benchmarks.append(
benchmark(pt, index, test_queries, selected["k1"], selected["b"], "tuned")
)
for b_ in benchmarks:
print(f"[bench:{b_['configuration']}] {b_['throughput_queries_per_second']} q/s "
f"mean={b_['latency_ms_mean']}ms p95={b_['latency_ms_p95']}ms")
cpu = platform.processor() or platform.machine()
manifest = {
"experiment": "MedIR-RAG Milestone 1 - BM25 lexical baseline",
"run_started_utc": started.isoformat(timespec="seconds"),
"run_finished_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"dataset": {
"name": "DinoStackAI/bioasq-rag-13b-resplit",
"revision": "ade805f1df0b16dbf19385597861146bdb0d9904",
"subsets_used": ["corpus", "queries", "qrels"],
"subsets_not_used": ["answers", "retrieved_docs"],
"audit_file": "results/raw/data_audit.json",
},
"index": stats,
"index_build": build_info,
"retrieval": {
"model": "Terrier BM25 (org.terrier.matching.models.BM25)",
"depth": RETRIEVAL_DEPTH,
"default": {"k1": DEFAULT_K1, "b": DEFAULT_B},
"tuned": {"k1": selected["k1"], "b": selected["b"]},
"selection_split": "dev",
"random_seed": RANDOM_SEED,
"threads": 1,
},
"evaluation": {
"library": "pytrec_eval (pytrec_eval-terrier)",
"measures": {label: m for m, label in MEASURES.items()} | {"MRR@10": "recip_rank@10"},
"primary_population_queries": len(test_pop),
},
"efficiency": benchmarks,
"environment": {
"python": sys.version.split()[0],
"platform": platform.platform(),
"cpu": cpu,
"cpu_count": os.cpu_count(),
"java": _java_version(),
"packages": _versions(
["pyterrier", "pytrec_eval-terrier", "datasets", "pandas", "numpy",
"scipy", "matplotlib", "ir_measures", "huggingface_hub", "pyjnius"]
),
},
"metric_validation": {
"file": "results/raw/metric_validation.json",
"all_passed": validation["all_passed"],
},
"outputs": {
"dev_grid": "results/raw/dev_grid.csv",
"selected_config": "results/raw/selected_config.json",
"test_default_run": "results/raw/test_default.trec",
"test_tuned_run": "results/raw/test_tuned.trec",
"test_per_query": "results/raw/test_per_query.csv",
"test_summary": "results/raw/test_summary.json",
},
}
(RAW / "experiment_manifest.json").write_text(json.dumps(manifest, indent=2))
print("[done] wrote results/raw/{dev_grid.csv,selected_config.json,test_*.trec,"
"test_per_query.csv,test_summary.json,experiment_manifest.json}")
if not validation["all_passed"]:
return 2
return 0
def _java_version() -> str:
if not os.environ.get("JAVA_HOME"):
ensure_java()
import subprocess
try:
out = subprocess.run(
[str(Path(os.environ["JAVA_HOME"]) / "bin" / "java.exe"), "-version"],
capture_output=True, text=True, timeout=60,
)
return (out.stderr or out.stdout).splitlines()[0].strip()
except Exception as exc: # pragma: no cover
return f"unavailable ({exc})"
if __name__ == "__main__":
raise SystemExit(main())