File size: 4,099 Bytes
12e6aff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
"""Score a run on the strict Doubting MS MARCO dev qrels, or export TREC qrels from the package.

Score:   python evaluate.py --qrels trec/dev.strict.qrels --run run.trec
         run.trec has TREC run lines "query_id Q0 passage_id rank score tag"; a passage is ranked by descending score
         (ties broken by passage id). MRR@10, nDCG@10 (binary gain) and Recall@100 are averaged over the queries with
         at least one relevant pair in the qrels (the strict subset); queries absent from the run score 0.
         Malformed lines, non-finite scores and a passage listed twice for one query are errors.
Export:  python evaluate.py --export-train-qrels train.qrels [--package DIR]
         writes the `qrels` train split as TREC qrels "query_id 0 passage_id grade" (needs pyarrow).
No other packages are needed for scoring.
"""
import argparse
import collections
import glob
import math
import os
import sys


def read_qrels(path):
    rel, seen = collections.defaultdict(dict), set()
    with open(path) as f:
        for n, line in enumerate(f, 1):
            x = line.split()
            if not x:
                continue
            if len(x) != 4 or not x[3].lstrip("-").isdigit():
                raise ValueError(f"{path}:{n}: expected 'query_id 0 passage_id grade'")
            if (x[0], x[2]) in seen:
                raise ValueError(f"{path}:{n}: pair {x[0]} {x[2]} listed twice")
            seen.add((x[0], x[2]))
            if int(x[3]) > 0:
                rel[x[0]][x[2]] = int(x[3])
    return rel


def read_run(path):
    run = collections.defaultdict(dict)
    with open(path) as f:
        for n, line in enumerate(f, 1):
            x = line.split()
            if not x:
                continue
            if len(x) != 6:
                raise ValueError(f"{path}:{n}: expected 'query_id Q0 passage_id rank score tag'")
            score = float(x[4])
            if not math.isfinite(score):
                raise ValueError(f"{path}:{n}: score {x[4]} is not finite")
            if x[2] in run[x[0]]:
                raise ValueError(f"{path}:{n}: passage {x[2]} listed twice for query {x[0]}")
            run[x[0]][x[2]] = score
    return {q: [d for d, _ in sorted(s.items(), key=lambda kv: (-kv[1], kv[0]))] for q, s in run.items()}


def score(qrels, run):
    out = collections.defaultdict(float)
    for q, rel in qrels.items():
        ranked = run.get(q, [])
        rr = next((1.0 / (i + 1) for i, d in enumerate(ranked[:10]) if d in rel), 0.0)
        dcg = sum(1.0 / math.log2(i + 2) for i, d in enumerate(ranked[:10]) if d in rel)
        idcg = sum(1.0 / math.log2(i + 2) for i in range(min(10, len(rel))))
        out["MRR@10"] += rr
        out["nDCG@10"] += dcg / idcg
        out["Recall@100"] += len(set(ranked[:100]) & set(rel)) / len(rel)
    n = len(qrels)
    return {k: v / n for k, v in out.items()}, n


def export_train(package, out):
    import pyarrow.parquet as pq
    n = 0
    with open(out, "w") as f:
        for path in sorted(glob.glob(os.path.join(package, "data", "qrels", "train-*.parquet"))):
            t = pq.read_table(path)
            for q, p, g in zip(t["query_id"].to_pylist(), t["passage_id"].to_pylist(), t["grade"].to_pylist()):
                f.write(f"{q} 0 {p} {g}\n")
                n += 1
    return n


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--qrels")
    ap.add_argument("--run")
    ap.add_argument("--export-train-qrels")
    ap.add_argument("--package", default=os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    a = ap.parse_args()
    if a.export_train_qrels:
        print(f"wrote {export_train(a.package, a.export_train_qrels):,} qrels lines to {a.export_train_qrels}")
        return
    if not (a.qrels and a.run):
        ap.error("give --qrels and --run, or --export-train-qrels")
    try:
        metrics, n = score(read_qrels(a.qrels), read_run(a.run))
    except ValueError as e:
        sys.exit(f"error: {e}")
    for k, v in metrics.items():
        print(f"{k}\t{v:.6f}")
    print(f"queries\t{n}")


if __name__ == "__main__":
    main()