Yu-and-Ai commited on
Commit
cff81ae
·
verified ·
1 Parent(s): 4c54872

Upload scripts/evaluate.py

Browse files
Files changed (1) hide show
  1. scripts/evaluate.py +232 -0
scripts/evaluate.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Evaluate retrieval runs and provide a deterministic lexical smoke baseline."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import math
9
+ import re
10
+ from collections import Counter, defaultdict
11
+ from pathlib import Path
12
+ from typing import Any, Iterable
13
+
14
+ from validate_dataset import ROOT, ValidationError, read_jsonl, validate
15
+
16
+
17
+ TOKEN_RE = re.compile(r"[a-z0-9_]+|[\u3400-\u4dbf\u4e00-\u9fff]", re.IGNORECASE)
18
+ METRIC_KEYS = ("ndcg@10", "recall@5", "success@1", "mrr@10", "hard_negative_inversion")
19
+
20
+
21
+ def tokens(text: str) -> list[str]:
22
+ return TOKEN_RE.findall(text.casefold())
23
+
24
+
25
+ def lexical_rank(
26
+ queries: Iterable[dict[str, Any]],
27
+ corpus: list[dict[str, Any]],
28
+ ) -> dict[str, list[str]]:
29
+ """Rank with a small BM25-style lexical scorer.
30
+
31
+ This intentionally performs no translation. Low cross-lingual scores are an
32
+ honest property of the smoke baseline rather than something hidden by
33
+ query-specific aliases.
34
+ """
35
+
36
+ document_tokens = {row["chunk_id"]: tokens(row["text"]) for row in corpus}
37
+ document_frequencies: Counter[str] = Counter()
38
+ for values in document_tokens.values():
39
+ document_frequencies.update(set(values))
40
+ document_count = len(corpus)
41
+ average_length = sum(map(len, document_tokens.values())) / max(document_count, 1)
42
+ k1 = 1.2
43
+ b = 0.75
44
+
45
+ rankings: dict[str, list[str]] = {}
46
+ for query in queries:
47
+ query_terms = Counter(tokens(query["query"]))
48
+ scored: list[tuple[float, str]] = []
49
+ for chunk_id, values in document_tokens.items():
50
+ frequencies = Counter(values)
51
+ length_normalization = k1 * (1 - b + b * len(values) / max(average_length, 1))
52
+ score = 0.0
53
+ for term, query_count in query_terms.items():
54
+ frequency = frequencies.get(term, 0)
55
+ if frequency == 0:
56
+ continue
57
+ df = document_frequencies[term]
58
+ inverse_document_frequency = math.log(
59
+ 1 + (document_count - df + 0.5) / (df + 0.5)
60
+ )
61
+ score += (
62
+ query_count
63
+ * inverse_document_frequency
64
+ * frequency
65
+ * (k1 + 1)
66
+ / (frequency + length_normalization)
67
+ )
68
+ scored.append((score, chunk_id))
69
+ scored.sort(key=lambda item: (-item[0], item[1]))
70
+ rankings[query["query_id"]] = [chunk_id for _, chunk_id in scored]
71
+ return rankings
72
+
73
+
74
+ def load_run(path: Path, corpus_ids: set[str]) -> dict[str, list[str]]:
75
+ rows = read_jsonl(path)
76
+ rankings: dict[str, list[str]] = {}
77
+ for row in rows:
78
+ query_id = row.get("query_id")
79
+ ranked = row.get("ranked_chunk_ids")
80
+ if not isinstance(query_id, str) or query_id in rankings:
81
+ raise ValidationError(f"run: invalid or duplicate query_id {query_id!r}")
82
+ if not isinstance(ranked, list) or not all(isinstance(value, str) for value in ranked):
83
+ raise ValidationError(f"run {query_id}: ranked_chunk_ids must be a string list")
84
+ if len(ranked) != len(set(ranked)):
85
+ raise ValidationError(f"run {query_id}: duplicate ranked chunk")
86
+ unknown = set(ranked) - corpus_ids
87
+ if unknown:
88
+ raise ValidationError(f"run {query_id}: unknown chunks {sorted(unknown)}")
89
+ rankings[query_id] = ranked
90
+ return rankings
91
+
92
+
93
+ def require_exact_query_set(
94
+ rankings: dict[str, list[str]],
95
+ queries: Iterable[dict[str, Any]],
96
+ ) -> None:
97
+ expected = {query["query_id"] for query in queries}
98
+ observed = set(rankings)
99
+ if observed != expected:
100
+ missing = sorted(expected - observed)
101
+ unexpected = sorted(observed - expected)
102
+ raise ValidationError(
103
+ f"run query set mismatch; missing={missing}, unexpected={unexpected}"
104
+ )
105
+
106
+
107
+ def query_metrics(query: dict[str, Any], ranking: list[str]) -> dict[str, float]:
108
+ grades = {item["chunk_id"]: item["grade"] for item in query["relevance"]}
109
+ binary_relevant = {chunk_id for chunk_id, grade in grades.items() if grade >= 2}
110
+
111
+ def dcg(ordered_grades: Iterable[int], limit: int) -> float:
112
+ return sum(
113
+ (2**grade - 1) / math.log2(rank + 1)
114
+ for rank, grade in enumerate(list(ordered_grades)[:limit], 1)
115
+ )
116
+
117
+ observed_grades = [grades.get(chunk_id, 0) for chunk_id in ranking]
118
+ ideal_grades = sorted(grades.values(), reverse=True)
119
+ ideal = dcg(ideal_grades, 10)
120
+ ndcg = dcg(observed_grades, 10) / ideal if ideal else 0.0
121
+ found_at_five = binary_relevant.intersection(ranking[:5])
122
+ recall = len(found_at_five) / len(binary_relevant) if binary_relevant else 0.0
123
+ success = float(bool(ranking[:1] and ranking[0] in binary_relevant))
124
+
125
+ reciprocal_rank = 0.0
126
+ for rank, chunk_id in enumerate(ranking[:10], 1):
127
+ if chunk_id in binary_relevant:
128
+ reciprocal_rank = 1.0 / rank
129
+ break
130
+
131
+ positions = {chunk_id: rank for rank, chunk_id in enumerate(ranking, 1)}
132
+ missing_rank = len(ranking) + 1
133
+ best_direct = min(
134
+ (positions.get(chunk_id, missing_rank) for chunk_id, grade in grades.items() if grade == 3),
135
+ default=missing_rank,
136
+ )
137
+ best_negative = min(
138
+ (positions.get(chunk_id, missing_rank) for chunk_id in query["hard_negative_chunk_ids"]),
139
+ default=missing_rank,
140
+ )
141
+ inversion = float(best_negative < best_direct)
142
+ return {
143
+ "ndcg@10": ndcg,
144
+ "recall@5": recall,
145
+ "success@1": success,
146
+ "mrr@10": reciprocal_rank,
147
+ "hard_negative_inversion": inversion,
148
+ }
149
+
150
+
151
+ def average(rows: list[dict[str, float]]) -> dict[str, float]:
152
+ if not rows:
153
+ return {key: 0.0 for key in METRIC_KEYS}
154
+ return {
155
+ key: sum(row[key] for row in rows) / len(rows)
156
+ for key in METRIC_KEYS
157
+ }
158
+
159
+
160
+ def evaluate(
161
+ queries: list[dict[str, Any]],
162
+ rankings: dict[str, list[str]],
163
+ run_name: str,
164
+ ) -> dict[str, Any]:
165
+ per_query: list[dict[str, Any]] = []
166
+ by_language: dict[str, list[dict[str, float]]] = defaultdict(list)
167
+ for query in sorted(queries, key=lambda row: row["query_id"]):
168
+ metrics = query_metrics(query, rankings.get(query["query_id"], []))
169
+ per_query.append(
170
+ {
171
+ "query_id": query["query_id"],
172
+ "language": query["language"],
173
+ **metrics,
174
+ }
175
+ )
176
+ by_language[query["language"]].append(metrics)
177
+
178
+ overall = average([{key: row[key] for key in METRIC_KEYS} for row in per_query])
179
+ language_metrics = {
180
+ language: {"count": len(rows), **average(rows)}
181
+ for language, rows in sorted(by_language.items())
182
+ }
183
+ worst_language_ndcg = min(
184
+ (row["ndcg@10"] for row in language_metrics.values()),
185
+ default=0.0,
186
+ )
187
+ english = language_metrics.get("en", {}).get("ndcg@10", 0.0)
188
+ cantonese = language_metrics.get("yue-Hant", {}).get("ndcg@10", 0.0)
189
+ return {
190
+ "run": run_name,
191
+ "query_count": len(queries),
192
+ "primary_metric": "ndcg@10",
193
+ "overall": overall,
194
+ "per_language": language_metrics,
195
+ "worst_language_ndcg@10": worst_language_ndcg,
196
+ "english_minus_cantonese_ndcg@10": english - cantonese,
197
+ "per_query": per_query,
198
+ }
199
+
200
+
201
+ def main() -> int:
202
+ parser = argparse.ArgumentParser()
203
+ parser.add_argument("--split", choices=("validation", "test", "all"), default="validation")
204
+ parser.add_argument("--run", type=Path, help="Optional JSONL retrieval run")
205
+ args = parser.parse_args()
206
+
207
+ try:
208
+ validate()
209
+ corpus = read_jsonl(ROOT / "data" / "corpus.jsonl")
210
+ if args.split == "all":
211
+ queries = read_jsonl(ROOT / "data" / "validation.jsonl") + read_jsonl(
212
+ ROOT / "data" / "test.jsonl"
213
+ )
214
+ else:
215
+ queries = read_jsonl(ROOT / "data" / f"{args.split}.jsonl")
216
+ if args.run:
217
+ rankings = load_run(args.run, {row["chunk_id"] for row in corpus})
218
+ require_exact_query_set(rankings, queries)
219
+ run_name = str(args.run)
220
+ else:
221
+ rankings = lexical_rank(queries, corpus)
222
+ run_name = "stdlib-bm25-style-lexical-smoke"
223
+ result = evaluate(queries, rankings, run_name)
224
+ except (OSError, KeyError, TypeError, ValueError, ValidationError) as error:
225
+ print(f"ERROR: {error}")
226
+ return 1
227
+ print(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True))
228
+ return 0
229
+
230
+
231
+ if __name__ == "__main__":
232
+ raise SystemExit(main())