ragbench-eval 1.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ragbench/__init__.py +25 -0
- ragbench/__main__.py +3 -0
- ragbench/cli.py +206 -0
- ragbench/compare.py +69 -0
- ragbench/datasets.py +103 -0
- ragbench/download.py +124 -0
- ragbench/gate.py +108 -0
- ragbench/metrics.py +69 -0
- ragbench/report.py +28 -0
- ragbench/retriever.py +124 -0
- ragbench/retrievers/__init__.py +11 -0
- ragbench/retrievers/bm25.py +102 -0
- ragbench/retrievers/dense.py +80 -0
- ragbench/runner.py +181 -0
- ragbench/stats.py +66 -0
- ragbench_eval-1.1.1.dist-info/METADATA +259 -0
- ragbench_eval-1.1.1.dist-info/RECORD +20 -0
- ragbench_eval-1.1.1.dist-info/WHEEL +4 -0
- ragbench_eval-1.1.1.dist-info/entry_points.txt +2 -0
- ragbench_eval-1.1.1.dist-info/licenses/LICENSE +21 -0
ragbench/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""RAGBench: a small, dependency-free harness for evaluating retrievers on BEIR-format data."""
|
|
2
|
+
|
|
3
|
+
from ragbench.datasets import Dataset, Document, load_beir
|
|
4
|
+
from ragbench.metrics import mrr_at_k, ndcg_at_k, recall_at_k
|
|
5
|
+
from ragbench.retriever import Hit, Retriever
|
|
6
|
+
from ragbench.runner import RunResult, evaluate
|
|
7
|
+
from ragbench.stats import bootstrap_ci, paired_bootstrap
|
|
8
|
+
|
|
9
|
+
__version__ = "1.1.1"
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"Dataset",
|
|
13
|
+
"Document",
|
|
14
|
+
"Hit",
|
|
15
|
+
"Retriever",
|
|
16
|
+
"RunResult",
|
|
17
|
+
"__version__",
|
|
18
|
+
"bootstrap_ci",
|
|
19
|
+
"evaluate",
|
|
20
|
+
"load_beir",
|
|
21
|
+
"mrr_at_k",
|
|
22
|
+
"ndcg_at_k",
|
|
23
|
+
"paired_bootstrap",
|
|
24
|
+
"recall_at_k",
|
|
25
|
+
]
|
ragbench/__main__.py
ADDED
ragbench/cli.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""``ragbench`` command line: download, info, run, compare, gate, report."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import shlex
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from ragbench import __version__
|
|
13
|
+
from ragbench.compare import compare_runs
|
|
14
|
+
from ragbench.datasets import load_beir
|
|
15
|
+
from ragbench.download import KNOWN, download
|
|
16
|
+
from ragbench.gate import MODES, gate
|
|
17
|
+
from ragbench.report import DEFAULT_METRICS, markdown_table
|
|
18
|
+
from ragbench.retriever import load_retriever, parse_params
|
|
19
|
+
from ragbench.runner import RunResult, evaluate
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _cmd_download(args: argparse.Namespace) -> int:
|
|
23
|
+
folder = download(args.name, args.dest, url=args.url, source=args.source, split=args.split)
|
|
24
|
+
print(json.dumps(load_beir(folder, args.split).summary()))
|
|
25
|
+
return 0
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _cmd_info(args: argparse.Namespace) -> int:
|
|
29
|
+
if args.data is None:
|
|
30
|
+
for name, about in KNOWN.items():
|
|
31
|
+
print(f"{name:<12} {about}")
|
|
32
|
+
return 0
|
|
33
|
+
print(json.dumps(load_beir(args.data, args.split).summary(), indent=2))
|
|
34
|
+
return 0
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _cmd_run(args: argparse.Namespace) -> int:
|
|
38
|
+
dataset = load_beir(args.data, args.split)
|
|
39
|
+
params = parse_params(args.param)
|
|
40
|
+
retriever = load_retriever(args.retriever, params)
|
|
41
|
+
name = args.name or args.retriever.rpartition(":")[2]
|
|
42
|
+
|
|
43
|
+
def progress(i: int, n: int) -> None:
|
|
44
|
+
if not args.quiet and (i == n or i % 100 == 0):
|
|
45
|
+
print(f" {i}/{n} queries", file=sys.stderr, flush=True)
|
|
46
|
+
|
|
47
|
+
result = evaluate(
|
|
48
|
+
retriever,
|
|
49
|
+
dataset,
|
|
50
|
+
name=name,
|
|
51
|
+
depth=args.depth,
|
|
52
|
+
limit=args.limit,
|
|
53
|
+
bootstrap_rounds=args.rounds,
|
|
54
|
+
seed=args.seed,
|
|
55
|
+
progress=progress,
|
|
56
|
+
ignore_identical_ids=not args.keep_identical_ids,
|
|
57
|
+
meta={
|
|
58
|
+
"retriever": args.retriever,
|
|
59
|
+
"params": params,
|
|
60
|
+
"command": "ragbench " + shlex.join(args.argv),
|
|
61
|
+
},
|
|
62
|
+
)
|
|
63
|
+
out = Path(args.out) if args.out else Path("results") / f"{dataset.name}__{name}.json"
|
|
64
|
+
result.save(out)
|
|
65
|
+
print(markdown_table([result]), end="")
|
|
66
|
+
print(f"wrote {out}", file=sys.stderr)
|
|
67
|
+
return 0
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _cmd_compare(args: argparse.Namespace) -> int:
|
|
71
|
+
base, cand = RunResult.load(args.baseline), RunResult.load(args.candidate)
|
|
72
|
+
metrics = args.metric or ["ndcg@10"]
|
|
73
|
+
rows = [compare_runs(base, cand, m, rounds=args.rounds, seed=args.seed) for m in metrics]
|
|
74
|
+
if args.json:
|
|
75
|
+
print(json.dumps([r.as_dict() for r in rows], indent=2))
|
|
76
|
+
return 0
|
|
77
|
+
for r in rows:
|
|
78
|
+
flag = "significant" if r.significant else "not significant"
|
|
79
|
+
print(
|
|
80
|
+
f"{r.metric}: {r.baseline} {r.baseline_mean:.4f} -> "
|
|
81
|
+
f"{r.candidate} {r.candidate_mean:.4f}, "
|
|
82
|
+
f"diff {r.diff.mean:+.4f} (95% CI {r.diff.low:+.4f} to {r.diff.high:+.4f}, "
|
|
83
|
+
f"{r.queries} queries, {flag})"
|
|
84
|
+
)
|
|
85
|
+
return 0
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _cmd_gate(args: argparse.Namespace) -> int:
|
|
89
|
+
base, cand = RunResult.load(args.baseline), RunResult.load(args.candidate)
|
|
90
|
+
result = gate(
|
|
91
|
+
base,
|
|
92
|
+
cand,
|
|
93
|
+
metrics=args.metric or ["ndcg@10"],
|
|
94
|
+
max_drop=args.max_drop,
|
|
95
|
+
mode=args.mode,
|
|
96
|
+
rounds=args.rounds,
|
|
97
|
+
seed=args.seed,
|
|
98
|
+
)
|
|
99
|
+
for check in result.checks:
|
|
100
|
+
print(check.line())
|
|
101
|
+
summary = args.summary or os.environ.get("GITHUB_STEP_SUMMARY")
|
|
102
|
+
if summary:
|
|
103
|
+
with open(summary, "a", encoding="utf-8") as fh:
|
|
104
|
+
fh.write(result.markdown())
|
|
105
|
+
return 0 if result.passed else 1
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _cmd_report(args: argparse.Namespace) -> int:
|
|
109
|
+
runs = [RunResult.load(p) for p in args.results]
|
|
110
|
+
runs.sort(key=lambda r: (r.dataset.get("name", ""), r.name))
|
|
111
|
+
print(markdown_table(runs, args.metric or DEFAULT_METRICS), end="")
|
|
112
|
+
return 0
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
116
|
+
parser = argparse.ArgumentParser(prog="ragbench", description=__doc__.split("\n")[0])
|
|
117
|
+
parser.add_argument("--version", action="version", version=f"ragbench {__version__}")
|
|
118
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
119
|
+
|
|
120
|
+
p = sub.add_parser("download", help="download a BEIR dataset")
|
|
121
|
+
p.add_argument("name", help="BEIR dataset name, e.g. scifact (see `ragbench info`)")
|
|
122
|
+
p.add_argument("--dest", default="data")
|
|
123
|
+
p.add_argument("--split", default="test")
|
|
124
|
+
p.add_argument("--url", default=None, help="override the archive URL")
|
|
125
|
+
p.add_argument("--source", choices=["auto", "ukp", "hf"], default="auto")
|
|
126
|
+
p.set_defaults(func=_cmd_download)
|
|
127
|
+
|
|
128
|
+
p = sub.add_parser("info", help="list known datasets, or summarise one folder")
|
|
129
|
+
p.add_argument("data", nargs="?", type=Path)
|
|
130
|
+
p.add_argument("--split", default="test")
|
|
131
|
+
p.set_defaults(func=_cmd_info)
|
|
132
|
+
|
|
133
|
+
p = sub.add_parser("run", help="evaluate a retriever on a dataset")
|
|
134
|
+
p.add_argument("--data", required=True, type=Path, help="BEIR-format dataset folder")
|
|
135
|
+
p.add_argument("--retriever", required=True, help="module:Name or path/file.py:Name")
|
|
136
|
+
p.add_argument("--param", action="append", default=[], metavar="KEY=VALUE")
|
|
137
|
+
p.add_argument("--name", default=None, help="label for this run (default: Name)")
|
|
138
|
+
p.add_argument("--split", default="test")
|
|
139
|
+
p.add_argument("--depth", type=int, default=100, help="results requested per query")
|
|
140
|
+
p.add_argument("--limit", type=int, default=None, help="only the first N queries")
|
|
141
|
+
p.add_argument("--rounds", type=int, default=2000, help="bootstrap resamples")
|
|
142
|
+
p.add_argument("--seed", type=int, default=0)
|
|
143
|
+
p.add_argument("--out", default=None, help="result JSON path")
|
|
144
|
+
p.add_argument(
|
|
145
|
+
"--keep-identical-ids",
|
|
146
|
+
action="store_true",
|
|
147
|
+
help="score a retrieved document whose id equals the query id (BEIR drops these)",
|
|
148
|
+
)
|
|
149
|
+
p.add_argument("--quiet", action="store_true")
|
|
150
|
+
p.set_defaults(func=_cmd_run)
|
|
151
|
+
|
|
152
|
+
p = sub.add_parser("compare", help="paired bootstrap between two result files")
|
|
153
|
+
p.add_argument("baseline", type=Path)
|
|
154
|
+
p.add_argument("candidate", type=Path)
|
|
155
|
+
p.add_argument("--metric", action="append", default=None)
|
|
156
|
+
p.add_argument("--rounds", type=int, default=2000)
|
|
157
|
+
p.add_argument("--seed", type=int, default=0)
|
|
158
|
+
p.add_argument("--json", action="store_true")
|
|
159
|
+
p.set_defaults(func=_cmd_compare)
|
|
160
|
+
|
|
161
|
+
p = sub.add_parser(
|
|
162
|
+
"gate",
|
|
163
|
+
help="exit 1 when a candidate run drops below a baseline (for CI)",
|
|
164
|
+
description="Compare a candidate run with a baseline run on the same queries and "
|
|
165
|
+
"exit 1 if any metric dropped by more than --max-drop.",
|
|
166
|
+
)
|
|
167
|
+
p.add_argument("baseline", type=Path)
|
|
168
|
+
p.add_argument("candidate", type=Path)
|
|
169
|
+
p.add_argument("--metric", action="append", default=None, help="repeatable; ndcg@10")
|
|
170
|
+
p.add_argument("--max-drop", type=float, default=0.01, help="allowed drop in the metric (0.01)")
|
|
171
|
+
p.add_argument(
|
|
172
|
+
"--mode",
|
|
173
|
+
choices=list(MODES),
|
|
174
|
+
default="mean",
|
|
175
|
+
help="mean: fail on the mean change; ci: fail only if the whole 95%% CI is below",
|
|
176
|
+
)
|
|
177
|
+
p.add_argument("--rounds", type=int, default=2000)
|
|
178
|
+
p.add_argument("--seed", type=int, default=0)
|
|
179
|
+
p.add_argument(
|
|
180
|
+
"--summary",
|
|
181
|
+
default=None,
|
|
182
|
+
help="append a Markdown summary here (default: $GITHUB_STEP_SUMMARY if set)",
|
|
183
|
+
)
|
|
184
|
+
p.set_defaults(func=_cmd_gate)
|
|
185
|
+
|
|
186
|
+
p = sub.add_parser("report", help="Markdown table of result files")
|
|
187
|
+
p.add_argument("results", nargs="+", type=Path)
|
|
188
|
+
p.add_argument("--metric", action="append", default=None)
|
|
189
|
+
p.set_defaults(func=_cmd_report)
|
|
190
|
+
return parser
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def main(argv: list[str] | None = None) -> int:
|
|
194
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
195
|
+
parser = build_parser()
|
|
196
|
+
args = parser.parse_args(argv)
|
|
197
|
+
args.argv = argv
|
|
198
|
+
try:
|
|
199
|
+
return args.func(args)
|
|
200
|
+
except (FileNotFoundError, ValueError, KeyError, TypeError, ImportError) as exc:
|
|
201
|
+
print(f"ragbench: error: {exc}", file=sys.stderr)
|
|
202
|
+
return 2
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
if __name__ == "__main__":
|
|
206
|
+
raise SystemExit(main())
|
ragbench/compare.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Compare two runs on the same queries with a paired bootstrap."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
from ragbench.runner import RunResult
|
|
8
|
+
from ragbench.stats import Interval, paired_bootstrap
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class Comparison:
|
|
13
|
+
metric: str
|
|
14
|
+
baseline: str
|
|
15
|
+
candidate: str
|
|
16
|
+
baseline_mean: float
|
|
17
|
+
candidate_mean: float
|
|
18
|
+
diff: Interval
|
|
19
|
+
queries: int
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def significant(self) -> bool:
|
|
23
|
+
"""True when the interval for the difference excludes zero."""
|
|
24
|
+
return self.diff.low > 0 or self.diff.high < 0
|
|
25
|
+
|
|
26
|
+
def as_dict(self) -> dict:
|
|
27
|
+
return {
|
|
28
|
+
"metric": self.metric,
|
|
29
|
+
"baseline": self.baseline,
|
|
30
|
+
"candidate": self.candidate,
|
|
31
|
+
"baseline_mean": round(self.baseline_mean, 4),
|
|
32
|
+
"candidate_mean": round(self.candidate_mean, 4),
|
|
33
|
+
"diff": self.diff.as_dict(),
|
|
34
|
+
"queries": self.queries,
|
|
35
|
+
"significant": self.significant,
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def compare_runs(
|
|
40
|
+
baseline: RunResult,
|
|
41
|
+
candidate: RunResult,
|
|
42
|
+
metric: str = "ndcg@10",
|
|
43
|
+
rounds: int = 2000,
|
|
44
|
+
seed: int = 0,
|
|
45
|
+
) -> Comparison:
|
|
46
|
+
if baseline.dataset.get("name") != candidate.dataset.get("name"):
|
|
47
|
+
raise ValueError(
|
|
48
|
+
f"runs are on different datasets: {baseline.dataset.get('name')} "
|
|
49
|
+
f"vs {candidate.dataset.get('name')}"
|
|
50
|
+
)
|
|
51
|
+
for run in (baseline, candidate):
|
|
52
|
+
if metric not in run.per_query:
|
|
53
|
+
raise KeyError(f"{run.name} has no {metric!r}; it has {sorted(run.per_query)}")
|
|
54
|
+
a, b = baseline.per_query[metric], candidate.per_query[metric]
|
|
55
|
+
if set(a) != set(b):
|
|
56
|
+
raise ValueError(
|
|
57
|
+
f"runs scored different queries ({len(a)} vs {len(b)}, {len(set(a) ^ set(b))} differ)"
|
|
58
|
+
)
|
|
59
|
+
qids = sorted(a)
|
|
60
|
+
xs, ys = [a[q] for q in qids], [b[q] for q in qids]
|
|
61
|
+
return Comparison(
|
|
62
|
+
metric=metric,
|
|
63
|
+
baseline=baseline.name,
|
|
64
|
+
candidate=candidate.name,
|
|
65
|
+
baseline_mean=sum(xs) / len(xs),
|
|
66
|
+
candidate_mean=sum(ys) / len(ys),
|
|
67
|
+
diff=paired_bootstrap(xs, ys, rounds=rounds, seed=seed),
|
|
68
|
+
queries=len(qids),
|
|
69
|
+
)
|
ragbench/datasets.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""BEIR-format datasets: ``corpus.jsonl``, ``queries.jsonl`` and ``qrels/<split>.tsv``.
|
|
2
|
+
|
|
3
|
+
The layout is the one the BEIR benchmark publishes (Thakur et al., 2021), so any
|
|
4
|
+
BEIR dataset, or your own data written the same way, loads without conversion.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class Document:
|
|
16
|
+
"""One corpus entry. ``text`` is what a retriever should index."""
|
|
17
|
+
|
|
18
|
+
id: str
|
|
19
|
+
title: str
|
|
20
|
+
body: str
|
|
21
|
+
|
|
22
|
+
@property
|
|
23
|
+
def text(self) -> str:
|
|
24
|
+
return f"{self.title}\n\n{self.body}".strip() if self.title else self.body.strip()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Dataset:
|
|
29
|
+
"""A corpus, its queries and graded relevance judgements.
|
|
30
|
+
|
|
31
|
+
``qrels[query_id][doc_id]`` is the relevance grade. Grades of 0 or below mean
|
|
32
|
+
"judged not relevant" and are dropped at load time, as BEIR's own evaluation does.
|
|
33
|
+
Only queries with at least one relevant document are kept.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
name: str
|
|
37
|
+
corpus: dict[str, Document]
|
|
38
|
+
queries: dict[str, str]
|
|
39
|
+
qrels: dict[str, dict[str, int]]
|
|
40
|
+
split: str = "test"
|
|
41
|
+
meta: dict = field(default_factory=dict)
|
|
42
|
+
|
|
43
|
+
def relevant(self, query_id: str) -> set[str]:
|
|
44
|
+
return set(self.qrels.get(query_id, {}))
|
|
45
|
+
|
|
46
|
+
def summary(self) -> dict:
|
|
47
|
+
judgements = sum(len(v) for v in self.qrels.values())
|
|
48
|
+
return {
|
|
49
|
+
"name": self.name,
|
|
50
|
+
"split": self.split,
|
|
51
|
+
"documents": len(self.corpus),
|
|
52
|
+
"queries": len(self.queries),
|
|
53
|
+
"judgements": judgements,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _read_jsonl(path: Path) -> list[dict]:
|
|
58
|
+
with path.open(encoding="utf-8") as fh:
|
|
59
|
+
return [json.loads(line) for line in fh if line.strip()]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def read_qrels(path: Path) -> dict[str, dict[str, int]]:
|
|
63
|
+
"""Read a BEIR qrels TSV (``query-id corpus-id score``, header row optional)."""
|
|
64
|
+
qrels: dict[str, dict[str, int]] = {}
|
|
65
|
+
with path.open(encoding="utf-8") as fh:
|
|
66
|
+
for line_no, line in enumerate(fh, start=1):
|
|
67
|
+
parts = line.rstrip("\n").split("\t")
|
|
68
|
+
if len(parts) < 3 or not parts[0]:
|
|
69
|
+
continue
|
|
70
|
+
query_id, doc_id, score = parts[0], parts[1], parts[2]
|
|
71
|
+
try:
|
|
72
|
+
grade = int(float(score))
|
|
73
|
+
except ValueError:
|
|
74
|
+
if line_no == 1: # header row
|
|
75
|
+
continue
|
|
76
|
+
raise ValueError(f"{path}:{line_no}: score {score!r} is not a number") from None
|
|
77
|
+
if grade > 0:
|
|
78
|
+
qrels.setdefault(query_id, {})[doc_id] = grade
|
|
79
|
+
return qrels
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def load_beir(folder: str | Path, split: str = "test") -> Dataset:
|
|
83
|
+
"""Load a BEIR-format dataset folder."""
|
|
84
|
+
folder = Path(folder)
|
|
85
|
+
for required in ("corpus.jsonl", "queries.jsonl", f"qrels/{split}.tsv"):
|
|
86
|
+
if not (folder / required).exists():
|
|
87
|
+
raise FileNotFoundError(f"{folder / required} not found (expected BEIR layout)")
|
|
88
|
+
|
|
89
|
+
corpus = {
|
|
90
|
+
str(d["_id"]): Document(str(d["_id"]), d.get("title") or "", d.get("text") or "")
|
|
91
|
+
for d in _read_jsonl(folder / "corpus.jsonl")
|
|
92
|
+
}
|
|
93
|
+
all_queries = {str(q["_id"]): q["text"] for q in _read_jsonl(folder / "queries.jsonl")}
|
|
94
|
+
qrels = read_qrels(folder / "qrels" / f"{split}.tsv")
|
|
95
|
+
|
|
96
|
+
missing = sorted(qid for qid in qrels if qid not in all_queries)
|
|
97
|
+
if missing:
|
|
98
|
+
raise ValueError(
|
|
99
|
+
f"{len(missing)} judged queries are missing from queries.jsonl: {missing[:5]}"
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
queries = {qid: all_queries[qid] for qid in sorted(qrels)}
|
|
103
|
+
return Dataset(folder.name, corpus, queries, qrels, split=split)
|
ragbench/download.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Download a BEIR dataset.
|
|
2
|
+
|
|
3
|
+
Two sources, tried in order with ``source="auto"``:
|
|
4
|
+
|
|
5
|
+
* ``ukp``: the BEIR project's own zip mirror at TU Darmstadt (standard library only).
|
|
6
|
+
* ``hf``: the BEIR copies on the Hugging Face Hub (``BeIR/<name>`` and
|
|
7
|
+
``BeIR/<name>-qrels``), converted to the standard layout. Needs ``pyarrow``
|
|
8
|
+
(``pip install 'ragbench-eval[hf]'``).
|
|
9
|
+
|
|
10
|
+
Either way the result is ``dest/<name>/{corpus.jsonl, queries.jsonl, qrels/<split>.tsv}``.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import io
|
|
16
|
+
import json
|
|
17
|
+
import shutil
|
|
18
|
+
import sys
|
|
19
|
+
import tempfile
|
|
20
|
+
import urllib.error
|
|
21
|
+
import urllib.request
|
|
22
|
+
import zipfile
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
BEIR_URL = "https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/{name}.zip"
|
|
26
|
+
HF = "https://huggingface.co"
|
|
27
|
+
|
|
28
|
+
# Public BEIR datasets that ship with a test split in the standard layout. The big
|
|
29
|
+
# ones (msmarco, climate-fever, ...) work too; these are the ones worth starting with.
|
|
30
|
+
KNOWN = {
|
|
31
|
+
"scifact": "5,183 scientific abstracts, 300 test claims",
|
|
32
|
+
"nfcorpus": "3,633 medical documents, 323 test queries, graded judgements",
|
|
33
|
+
"arguana": "8,674 arguments, 1,406 test queries (counter-argument retrieval)",
|
|
34
|
+
"fiqa": "57,638 financial forum posts, 648 test questions",
|
|
35
|
+
"scidocs": "25,657 papers, 1,000 test queries",
|
|
36
|
+
"trec-covid": "171,332 COVID-19 papers, 50 test queries, graded judgements",
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _fetch(url: str, timeout: float) -> bytes:
|
|
41
|
+
with urllib.request.urlopen(url, timeout=timeout) as response: # noqa: S310
|
|
42
|
+
return response.read()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _from_zip(name: str, target: Path, url: str, timeout: float) -> None:
|
|
46
|
+
with tempfile.TemporaryDirectory(prefix="ragbench-") as tmp:
|
|
47
|
+
archive = Path(tmp) / f"{name}.zip"
|
|
48
|
+
with urllib.request.urlopen(url, timeout=timeout) as response, archive.open("wb") as fh: # noqa: S310
|
|
49
|
+
shutil.copyfileobj(response, fh)
|
|
50
|
+
with zipfile.ZipFile(archive) as zf:
|
|
51
|
+
root = Path(tmp) / "unzipped"
|
|
52
|
+
for member in zf.namelist():
|
|
53
|
+
resolved = (root / member).resolve()
|
|
54
|
+
if not resolved.is_relative_to(root.resolve()):
|
|
55
|
+
raise ValueError(f"unsafe path in archive: {member}")
|
|
56
|
+
zf.extractall(root)
|
|
57
|
+
found = next(root.rglob("corpus.jsonl"), None)
|
|
58
|
+
if found is None:
|
|
59
|
+
raise ValueError(f"{url} has no corpus.jsonl")
|
|
60
|
+
shutil.move(str(found.parent), str(target))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _hf_files(repo: str, folder: str, timeout: float) -> list[str]:
|
|
64
|
+
listing = json.loads(_fetch(f"{HF}/api/datasets/{repo}/tree/main/{folder}", timeout))
|
|
65
|
+
files = sorted(f["path"] for f in listing if f.get("type") == "file")
|
|
66
|
+
if not files:
|
|
67
|
+
raise ValueError(f"no files under {repo}/{folder}")
|
|
68
|
+
return files
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _from_hf(name: str, target: Path, split: str, timeout: float) -> None:
|
|
72
|
+
try:
|
|
73
|
+
import pyarrow.parquet as pq
|
|
74
|
+
except ImportError as exc:
|
|
75
|
+
raise ImportError(
|
|
76
|
+
"downloading from Hugging Face needs: pip install 'ragbench-eval[hf]'"
|
|
77
|
+
) from exc
|
|
78
|
+
|
|
79
|
+
with tempfile.TemporaryDirectory(prefix="ragbench-") as tmp:
|
|
80
|
+
staging = Path(tmp) / name
|
|
81
|
+
(staging / "qrels").mkdir(parents=True)
|
|
82
|
+
for part in ("corpus", "queries"):
|
|
83
|
+
with (staging / f"{part}.jsonl").open("w", encoding="utf-8") as out:
|
|
84
|
+
for path in _hf_files(f"BeIR/{name}", part, timeout):
|
|
85
|
+
if not path.endswith(".parquet"):
|
|
86
|
+
continue
|
|
87
|
+
data = _fetch(f"{HF}/datasets/BeIR/{name}/resolve/main/{path}", timeout)
|
|
88
|
+
for row in pq.read_table(io.BytesIO(data)).to_pylist():
|
|
89
|
+
out.write(json.dumps(row) + "\n")
|
|
90
|
+
qrels = _fetch(f"{HF}/datasets/BeIR/{name}-qrels/resolve/main/{split}.tsv", timeout)
|
|
91
|
+
(staging / "qrels" / f"{split}.tsv").write_bytes(qrels)
|
|
92
|
+
shutil.move(str(staging), str(target))
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def download(
|
|
96
|
+
name: str,
|
|
97
|
+
dest: str | Path = "data",
|
|
98
|
+
url: str | None = None,
|
|
99
|
+
source: str = "auto",
|
|
100
|
+
split: str = "test",
|
|
101
|
+
timeout: float = 60,
|
|
102
|
+
) -> Path:
|
|
103
|
+
"""Fetch a BEIR dataset into ``dest/<name>`` and return that folder.
|
|
104
|
+
|
|
105
|
+
``url`` overrides the zip location (and implies ``source="ukp"``).
|
|
106
|
+
"""
|
|
107
|
+
dest = Path(dest)
|
|
108
|
+
target = dest / name
|
|
109
|
+
if (target / "corpus.jsonl").exists():
|
|
110
|
+
return target
|
|
111
|
+
if source not in ("auto", "ukp", "hf"):
|
|
112
|
+
raise ValueError(f"source must be auto, ukp or hf, not {source!r}")
|
|
113
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
114
|
+
|
|
115
|
+
if url or source in ("auto", "ukp"):
|
|
116
|
+
try:
|
|
117
|
+
_from_zip(name, target, url or BEIR_URL.format(name=name), timeout)
|
|
118
|
+
return target
|
|
119
|
+
except (urllib.error.URLError, TimeoutError, OSError) as exc:
|
|
120
|
+
if url or source == "ukp":
|
|
121
|
+
raise
|
|
122
|
+
print(f"BEIR mirror unavailable ({exc}); trying Hugging Face", file=sys.stderr)
|
|
123
|
+
_from_hf(name, target, split, timeout)
|
|
124
|
+
return target
|
ragbench/gate.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Pass or fail a candidate run against a baseline, for use as a CI check.
|
|
2
|
+
|
|
3
|
+
A gate compares two runs on the same queries with the paired bootstrap from
|
|
4
|
+
:mod:`ragbench.compare` and fails when a metric dropped by more than an
|
|
5
|
+
allowed amount. Two modes decide what "dropped" means:
|
|
6
|
+
|
|
7
|
+
``mean``
|
|
8
|
+
Fail when the mean change is below ``-max_drop``. Simple and strict, so a
|
|
9
|
+
noisy run can fail by chance.
|
|
10
|
+
``ci``
|
|
11
|
+
Fail only when the whole 95% interval for the change is below
|
|
12
|
+
``-max_drop``, so the drop is unlikely to be noise. Small query sets will
|
|
13
|
+
rarely fail in this mode.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
|
|
20
|
+
from ragbench.compare import Comparison, compare_runs
|
|
21
|
+
from ragbench.runner import RunResult
|
|
22
|
+
|
|
23
|
+
MODES = ("mean", "ci")
|
|
24
|
+
# Settings that change what a score means. Runs that differ on any of these are
|
|
25
|
+
# not comparable, so the gate refuses them rather than report a false result.
|
|
26
|
+
MUST_MATCH = ("depth", "ndcg_k", "ignore_identical_ids")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class Check:
|
|
31
|
+
comparison: Comparison
|
|
32
|
+
max_drop: float
|
|
33
|
+
mode: str
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def passed(self) -> bool:
|
|
37
|
+
d = self.comparison.diff
|
|
38
|
+
edge = d.high if self.mode == "ci" else d.mean
|
|
39
|
+
return edge >= -self.max_drop
|
|
40
|
+
|
|
41
|
+
def line(self) -> str:
|
|
42
|
+
c, d = self.comparison, self.comparison.diff
|
|
43
|
+
verdict = "pass" if self.passed else "FAIL"
|
|
44
|
+
return (
|
|
45
|
+
f"{verdict} {c.metric}: {c.baseline_mean:.4f} -> {c.candidate_mean:.4f}, "
|
|
46
|
+
f"change {d.mean:+.4f} (95% CI {d.low:+.4f} to {d.high:+.4f}, "
|
|
47
|
+
f"{c.queries} queries), allowed drop {self.max_drop:.4f}, mode {self.mode}"
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class GateResult:
|
|
53
|
+
checks: list[Check]
|
|
54
|
+
dataset: str
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def passed(self) -> bool:
|
|
58
|
+
return all(c.passed for c in self.checks)
|
|
59
|
+
|
|
60
|
+
def markdown(self) -> str:
|
|
61
|
+
head = "passed" if self.passed else "failed"
|
|
62
|
+
rows = [
|
|
63
|
+
f"### ragbench gate {head} on {self.dataset}",
|
|
64
|
+
"",
|
|
65
|
+
"| metric | baseline | candidate | change (95% CI) | allowed drop | result |",
|
|
66
|
+
"|---|---|---|---|---|---|",
|
|
67
|
+
]
|
|
68
|
+
for ch in self.checks:
|
|
69
|
+
c, d = ch.comparison, ch.comparison.diff
|
|
70
|
+
rows.append(
|
|
71
|
+
f"| {c.metric} | {c.baseline_mean:.4f} | {c.candidate_mean:.4f} | "
|
|
72
|
+
f"{d.mean:+.4f} ({d.low:+.4f} to {d.high:+.4f}) | {ch.max_drop:.4f} "
|
|
73
|
+
f"({ch.mode}) | {'pass' if ch.passed else 'fail'} |"
|
|
74
|
+
)
|
|
75
|
+
queries = self.checks[0].comparison.queries if self.checks else 0
|
|
76
|
+
rows += ["", f"{queries} queries, paired bootstrap."]
|
|
77
|
+
return "\n".join(rows) + "\n"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _check_settings(baseline: RunResult, candidate: RunResult) -> None:
|
|
81
|
+
a, b = baseline.dataset.get("split"), candidate.dataset.get("split")
|
|
82
|
+
if a != b:
|
|
83
|
+
raise ValueError(f"runs are on different splits ({a!r} vs {b!r})")
|
|
84
|
+
for key in MUST_MATCH:
|
|
85
|
+
a, b = baseline.settings.get(key), candidate.settings.get(key)
|
|
86
|
+
if a != b:
|
|
87
|
+
raise ValueError(f"runs differ on {key} ({a!r} vs {b!r}), so they aren't comparable")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def gate(
|
|
91
|
+
baseline: RunResult,
|
|
92
|
+
candidate: RunResult,
|
|
93
|
+
metrics: list[str] | tuple[str, ...] = ("ndcg@10",),
|
|
94
|
+
max_drop: float = 0.01,
|
|
95
|
+
mode: str = "mean",
|
|
96
|
+
rounds: int = 2000,
|
|
97
|
+
seed: int = 0,
|
|
98
|
+
) -> GateResult:
|
|
99
|
+
if mode not in MODES:
|
|
100
|
+
raise ValueError(f"mode must be one of {MODES}, not {mode!r}")
|
|
101
|
+
if max_drop < 0:
|
|
102
|
+
raise ValueError("max_drop can't be negative")
|
|
103
|
+
_check_settings(baseline, candidate)
|
|
104
|
+
checks = [
|
|
105
|
+
Check(compare_runs(baseline, candidate, m, rounds=rounds, seed=seed), max_drop, mode)
|
|
106
|
+
for m in metrics
|
|
107
|
+
]
|
|
108
|
+
return GateResult(checks=checks, dataset=str(baseline.dataset.get("name")))
|