File size: 10,259 Bytes
8510f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
"""Reproducible evaluation runner for CCRB retrieval runs."""

from __future__ import annotations

import argparse
import json
import sys
from datetime import date
from pathlib import Path
from typing import Any

_REPO_ROOT = Path(__file__).resolve().parent.parent
if str(_REPO_ROOT) not in sys.path:
    sys.path.insert(0, str(_REPO_ROOT))

try:
    import yaml  # type: ignore[import-not-found]
except ImportError:
    yaml = None

from evaluation.metrics import evaluate_track, macro_average_tracks
from scripts.pipeline_utils import TRACKS, load_jsonl, load_qrels


def _parse_scalar(raw: str) -> Any:
    cleaned = raw.split("#", 1)[0].strip()
    if cleaned in {"true", "True"}:
        return True
    if cleaned in {"false", "False"}:
        return False
    if (cleaned.startswith('"') and cleaned.endswith('"')) or (
        cleaned.startswith("'") and cleaned.endswith("'")
    ):
        return cleaned[1:-1]
    try:
        return int(cleaned)
    except ValueError:
        return cleaned


def _load_config(path: Path) -> dict[str, Any]:
    text = path.read_text(encoding="utf-8")
    if yaml is not None:
        loaded = yaml.safe_load(text)
        return loaded if isinstance(loaded, dict) else {}

    # Minimal YAML fallback for simple nested mappings and lists in config.yaml.
    root: dict[str, Any] = {}
    stack: list[tuple[int, Any]] = [(-1, root)]
    lines = text.splitlines()
    for idx, raw_line in enumerate(lines):
        stripped = raw_line.split("#", 1)[0].rstrip()
        if not stripped.strip():
            continue
        indent = len(raw_line) - len(raw_line.lstrip(" "))
        content = stripped.strip()
        while len(stack) > 1 and indent <= stack[-1][0]:
            stack.pop()
        parent = stack[-1][1]
        if content.startswith("- "):
            if isinstance(parent, list):
                parent.append(_parse_scalar(content[2:]))
            continue
        key, sep, val = content.partition(":")
        if not sep:
            continue
        key = key.strip()
        val = val.strip()
        if val:
            if isinstance(parent, dict):
                parent[key] = _parse_scalar(val)
        else:
            next_is_list = False
            for next_line in lines[idx + 1 :]:
                next_stripped = next_line.split("#", 1)[0].strip()
                if next_stripped:
                    next_is_list = next_stripped.startswith("- ")
                    break
            container: Any = [] if next_is_list else {}
            if isinstance(parent, dict):
                parent[key] = container
            stack.append((indent, container))
    return root


def load_run_file(path: Path) -> dict[str, list[str]]:
    """Load a retrieval run file in JSONL or TREC-style TSV format.

    Supported formats:
      1) JSONL (`.jsonl`): {"query_id": "...", "results": [{"document_id": "...", "score": 0.9}, ...]}
         or {"query_id": "...", "document_ids": ["...", ...]}
      2) TREC TSV/space-delimited (`.tsv` / `.trec` / `.txt`):
         query_id  Q0  document_id  rank  score  run_id
    """
    if path.suffix.lower() == ".jsonl":
        rankings: dict[str, list[str]] = {}
        for line_no, obj in load_jsonl(path):
            qid = obj.get("query_id")
            if not isinstance(qid, str) or not qid:
                raise ValueError(f"{path}:{line_no}: missing 'query_id'")
            if "document_ids" in obj and isinstance(obj["document_ids"], list):
                rankings[qid] = [str(did) for did in obj["document_ids"]]
            elif "results" in obj and isinstance(obj["results"], list):
                sorted_hits = sorted(
                    obj["results"],
                    key=lambda item: float(item.get("score", 0.0)),
                    reverse=True,
                )
                rankings[qid] = [str(item["document_id"]) for item in sorted_hits]
            else:
                raise ValueError(
                    f"{path}:{line_no}: expected 'results' or 'document_ids' list"
                )
        return rankings

    scored: dict[str, list[tuple[float, int, str]]] = {}
    with path.open("r", encoding="utf-8") as handle:
        for line_no, raw in enumerate(handle, start=1):
            stripped = raw.strip()
            if not stripped:
                continue
            parts = stripped.split()
            if len(parts) < 5:
                raise ValueError(
                    f"{path}:{line_no}: expected at least 5 columns (TREC format)"
                )
            qid, _q0, did, rank_raw, score_raw = parts[:5]
            scored.setdefault(qid, []).append((float(score_raw), int(rank_raw), did))

    return {
        qid: [
            did
            for _score, _rank, did in sorted(
                entries, key=lambda item: (-item[0], item[1])
            )
        ]
        for qid, entries in scored.items()
    }


def _find_run_file(runs_dir: Path, track: str) -> Path | None:
    for ext in (".jsonl", ".tsv", ".trec", ".txt"):
        candidate = runs_dir / f"{track}{ext}"
        if candidate.exists():
            return candidate
    return None


def _filter_qrels_by_split(
    data_dir: Path,
    track: str,
    qrels: dict[str, dict[str, int]],
    split: str | None,
) -> dict[str, dict[str, int]]:
    if not split or split == "all":
        return qrels
    queries_path = data_dir / "queries" / f"{track}.jsonl"
    split_qids = {
        str(obj["query_id"])
        for _ln, obj in load_jsonl(queries_path)
        if obj.get("split") == split
    }
    if not split_qids:
        raise ValueError(
            f"[{track}] requested split={split!r} but no queries carry split={split!r}"
        )
    return {qid: docs for qid, docs in qrels.items() if qid in split_qids}


def run_evaluation(
    *,
    config_path: Path,
    runs_dir: Path,
    data_dir: Path | None = None,
    split: str | None = None,
    output_path: Path | None = None,
    model_metadata: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """Evaluate retrieval runs across configured CCRB tracks and optionally save JSON."""
    config = _load_config(config_path)

    bench_cfg = config.get("benchmark", {})
    eval_cfg = config.get("evaluation", {})
    resolved_data_dir = data_dir or Path(bench_cfg.get("data_dir", "data"))
    configured_tracks = tuple(bench_cfg.get("tracks", TRACKS))
    rel_threshold = int(eval_cfg.get("relevance_threshold", 1))
    effective_split = split if split is not None else bench_cfg.get("split", "all")

    track_results: dict[str, dict[str, Any]] = {}
    track_scores_only: dict[str, dict[str, float]] = {}
    missing_tracks: list[str] = []

    for track in configured_tracks:
        run_path = _find_run_file(runs_dir, track)
        if run_path is None:
            missing_tracks.append(track)
            continue

        qrels_path = resolved_data_dir / "qrels" / f"{track}.tsv"
        qrels = load_qrels(qrels_path)
        qrels = _filter_qrels_by_split(resolved_data_dir, track, qrels, effective_split)
        rankings = load_run_file(run_path)

        scores = evaluate_track(
            rankings,
            qrels,
            relevance_threshold=rel_threshold,
        )
        track_scores_only[track] = scores
        track_results[track] = {
            "num_queries": len(qrels),
            "run_file": run_path.name,
            **scores,
        }

    if not track_scores_only:
        raise FileNotFoundError(
            f"No matching track run files found in {runs_dir} for tracks {configured_tracks}"
        )

    overall = macro_average_tracks(track_scores_only)
    meta = dict(config.get("model_metadata_template", {}))
    if model_metadata:
        meta.update(model_metadata)
    if not meta.get("evaluation_date"):
        meta["evaluation_date"] = date.today().isoformat()

    is_official = len(missing_tracks) == 0 and set(track_scores_only) == set(TRACKS)
    payload: dict[str, Any] = {
        "benchmark_name": bench_cfg.get("name", "Continuum Cyber Retrieval Benchmark (CCRB)"),
        "benchmark_version": bench_cfg.get("version", "0.1.0-dev"),
        "split": effective_split,
        "official": is_official,
        "missing_tracks": missing_tracks,
        "model": meta,
        "overall_macro_average": overall,
        "tracks": track_results,
    }

    if output_path is not None:
        output_path.parent.mkdir(parents=True, exist_ok=True)
        with output_path.open("w", encoding="utf-8") as handle:
            json.dump(payload, handle, indent=2)
            handle.write("\n")

    return payload


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Evaluate retrieval runs on CCRB.")
    parser.add_argument(
        "--config",
        type=Path,
        default=Path("evaluation/config.yaml"),
        help="Path to evaluation config YAML.",
    )
    parser.add_argument(
        "--runs-dir",
        type=Path,
        required=True,
        help="Directory containing <track>.jsonl or <track>.tsv run files.",
    )
    parser.add_argument(
        "--data-dir",
        type=Path,
        default=None,
        help="Override data directory from config.",
    )
    parser.add_argument(
        "--split",
        type=str,
        default=None,
        help="Query split to evaluate ('dev', 'test', or 'all').",
    )
    parser.add_argument(
        "--output",
        type=Path,
        default=None,
        help="Optional path to write JSON evaluation summary.",
    )
    parser.add_argument("--model-name", type=str, default="", help="Model name/identifier.")
    parser.add_argument("--model-revision", type=str, default="", help="Model checkpoint/revision.")
    args = parser.parse_args(argv)

    model_meta = {}
    if args.model_name:
        model_meta["model"] = args.model_name
    if args.model_revision:
        model_meta["revision"] = args.model_revision

    result = run_evaluation(
        config_path=args.config,
        runs_dir=args.runs_dir,
        data_dir=args.data_dir,
        split=args.split,
        output_path=args.output,
        model_metadata=model_meta,
    )
    print(json.dumps(result, indent=2))
    return 0


if __name__ == "__main__":
    sys.exit(main())