Download evaluation/evaluate.py from continuum-oss/ccrb: direct link, hf CLI and curl.
- Browser
- Download file 10.3 kB
-
https://huggingface.co/datasets/continuum-oss/ccrb/resolve/main/evaluation/evaluate.py
- Command line
-
hf download hf://datasets/continuum-oss/ccrb/evaluation/evaluate.py
-
curl -L -o evaluate.py https://huggingface.co/datasets/continuum-oss/ccrb/resolve/main/evaluation/evaluate.py
10.3 kB
| """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()) | |