Spaces:
Running
Running
Download scripts/evaluate_retrieval.py from phaethon-order/tech-trans-rag: direct link, hf CLI and curl.
- Browser
- Download file 9.92 kB
-
https://huggingface.co/spaces/phaethon-order/tech-trans-rag/resolve/main/scripts/evaluate_retrieval.py
- Command line
-
hf download hf://spaces/phaethon-order/tech-trans-rag/scripts/evaluate_retrieval.py
-
curl -L -o evaluate_retrieval.py https://huggingface.co/spaces/phaethon-order/tech-trans-rag/resolve/main/scripts/evaluate_retrieval.py
9.92 kB
| """Evaluate retrieval against a versioned, domain-reviewed JSONL benchmark.""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import math | |
| import time | |
| from collections import defaultdict | |
| from pathlib import Path | |
| from typing import Any | |
| import jsonschema | |
| from infrastructure.database import search_vector_candidates | |
| from infrastructure.embeddings import DEFAULT_MODEL, generate_embedding | |
| from infrastructure.logger import get_logger, setup_logger | |
| from infrastructure.vector_search import find_nearest_neighbors | |
| logger = get_logger() | |
| REQUIRED_CATEGORIES = { | |
| "paraphrase", | |
| "defined_term", | |
| "section_reference", | |
| "metadata_filter", | |
| "cross_document", | |
| "insufficient_context", | |
| } | |
| def _identity(item: dict[str, Any]) -> tuple[str, int]: | |
| return str(item.get("document_sha256") or ""), int(item["chunk_index"]) | |
| def retrieval_metrics( | |
| results: list[dict[str, Any]], relevant: list[dict[str, Any]], *, k: int = 5 | |
| ) -> dict[str, float]: | |
| """Compute Recall, reciprocal rank, and graded nDCG at K.""" | |
| ranked = [_identity(item) for item in results[:k]] | |
| grades = {_identity(item): int(item["grade"]) for item in relevant} | |
| if not grades: | |
| empty_score = 1.0 if not ranked else 0.0 | |
| return {"recall": empty_score, "mrr": empty_score, "ndcg": empty_score} | |
| hits = [identity for identity in ranked if identity in grades] | |
| recall = len(set(hits)) / len(grades) | |
| first_rank = next( | |
| (rank for rank, identity in enumerate(ranked, start=1) if identity in grades), | |
| None, | |
| ) | |
| mrr = 1.0 / first_rank if first_rank is not None else 0.0 | |
| dcg = sum( | |
| (2 ** grades[identity] - 1) / math.log2(rank + 1) | |
| for rank, identity in enumerate(ranked, start=1) | |
| if identity in grades | |
| ) | |
| ideal = sum( | |
| (2**grade - 1) / math.log2(rank + 1) | |
| for rank, grade in enumerate(sorted(grades.values(), reverse=True)[:k], start=1) | |
| ) | |
| return {"recall": recall, "mrr": mrr, "ndcg": dcg / ideal if ideal else 0.0} | |
| def _average(rows: list[dict[str, float]]) -> dict[str, float]: | |
| if not rows: | |
| return {"recall": 0.0, "mrr": 0.0, "ndcg": 0.0} | |
| return { | |
| metric: sum(row[metric] for row in rows) / len(rows) | |
| for metric in ("recall", "mrr", "ndcg") | |
| } | |
| def _percentile(values: list[float], percentile: float) -> float: | |
| if not values: | |
| return 0.0 | |
| ordered = sorted(values) | |
| index = max(0, math.ceil(percentile * len(ordered)) - 1) | |
| return ordered[index] | |
| def _retrieve(row: dict[str, Any], *, top_k: int, mode: str) -> list[dict[str, Any]]: | |
| filters = row.get("filters") or {} | |
| if mode == "vector-baseline": | |
| query_vector = generate_embedding(row["query"], model=DEFAULT_MODEL) | |
| return ( | |
| search_vector_candidates( | |
| query_vector, | |
| model=DEFAULT_MODEL, | |
| limit=top_k, | |
| filters=filters, | |
| ) | |
| if query_vector | |
| else [] | |
| ) | |
| return find_nearest_neighbors(row["query"], top_k, where=filters) | |
| def _filter_leaks(results: list[dict[str, Any]], filters: dict[str, Any]) -> int: | |
| leaks = 0 | |
| for result in results: | |
| for name, expected in filters.items(): | |
| if name == "doc_id": | |
| matches = int(result.get("doc_id") or 0) == int(expected) | |
| else: | |
| values = { | |
| value.strip().casefold() | |
| for value in str(result.get(name) or "").split(",") | |
| if value.strip() | |
| } | |
| matches = str(expected).strip().casefold() in values | |
| if not matches: | |
| leaks += 1 | |
| break | |
| return leaks | |
| def load_benchmark(path: Path, *, allow_small: bool = False) -> list[dict[str, Any]]: | |
| """Load and validate approved benchmark rows.""" | |
| schema_path = Path(__file__).parents[1] / "evals/retrieval/benchmark.schema.json" | |
| schema = json.loads(schema_path.read_text(encoding="utf-8")) | |
| rows: list[dict[str, Any]] = [] | |
| for line_number, line in enumerate( | |
| path.read_text(encoding="utf-8").splitlines(), 1 | |
| ): | |
| if not line.strip(): | |
| continue | |
| row = json.loads(line) | |
| try: | |
| jsonschema.validate(row, schema) | |
| except jsonschema.ValidationError as exc: | |
| raise ValueError( | |
| f"invalid benchmark row {line_number}: {exc.message}" | |
| ) from exc | |
| rows.append(row) | |
| if not allow_small and len(rows) < 40: | |
| raise ValueError("acceptance benchmark must contain at least 40 approved rows") | |
| if not allow_small: | |
| missing_categories = REQUIRED_CATEGORIES - { | |
| str(row["category"]) for row in rows | |
| } | |
| if missing_categories: | |
| raise ValueError( | |
| "acceptance benchmark is missing categories: " | |
| + ", ".join(sorted(missing_categories)) | |
| ) | |
| if len({row["query_id"] for row in rows}) != len(rows): | |
| raise ValueError("benchmark query_id values must be unique") | |
| return rows | |
| def evaluate( | |
| rows: list[dict[str, Any]], | |
| *, | |
| top_k: int = 5, | |
| mode: str = "hybrid", | |
| verify_determinism: bool = True, | |
| ) -> dict[str, Any]: | |
| """Run retrieval and aggregate benchmark metrics.""" | |
| if top_k < 1 or top_k > 20: | |
| raise ValueError("top_k must be from 1 to 20") | |
| query_reports: list[dict[str, Any]] = [] | |
| latencies: list[float] = [] | |
| if rows: | |
| _retrieve(rows[0], top_k=top_k, mode=mode) | |
| for row in rows: | |
| started = time.perf_counter() | |
| results = _retrieve(row, top_k=top_k, mode=mode) | |
| latency_ms = (time.perf_counter() - started) * 1000 | |
| latencies.append(latency_ms) | |
| repeat_ids: list[int] | None = None | |
| if verify_determinism: | |
| repeat_ids = [ | |
| int(item["chunk_id"]) for item in _retrieve(row, top_k=top_k, mode=mode) | |
| ] | |
| result_ids = [int(item["chunk_id"]) for item in results] | |
| metrics = retrieval_metrics(results, row["relevant"], k=top_k) | |
| query_reports.append( | |
| { | |
| "query_id": row["query_id"], | |
| "category": row["category"], | |
| "latency_ms": latency_ms, | |
| "filter_leaks": _filter_leaks(results, row.get("filters") or {}), | |
| "deterministic": repeat_ids is None or repeat_ids == result_ids, | |
| **metrics, | |
| } | |
| ) | |
| by_category: dict[str, list[dict[str, float]]] = defaultdict(list) | |
| for report in query_reports: | |
| by_category[report["category"]].append(report) | |
| return { | |
| "query_count": len(rows), | |
| "top_k": top_k, | |
| "mode": mode, | |
| "overall": _average(query_reports), | |
| "categories": { | |
| category: _average(category_rows) | |
| for category, category_rows in sorted(by_category.items()) | |
| }, | |
| "latency_ms": { | |
| "p50": _percentile(latencies, 0.50), | |
| "p95": _percentile(latencies, 0.95), | |
| }, | |
| "filter_leaks": sum(report["filter_leaks"] for report in query_reports), | |
| "deterministic": all(report["deterministic"] for report in query_reports), | |
| "queries": query_reports, | |
| } | |
| def compare(candidate: dict[str, Any], baseline: dict[str, Any]) -> dict[str, Any]: | |
| """Apply the approved quality and latency acceptance thresholds.""" | |
| category_drops = { | |
| category: candidate["categories"].get(category, {}).get("ndcg", 0.0) | |
| - metrics["ndcg"] | |
| for category, metrics in baseline.get("categories", {}).items() | |
| } | |
| checks = { | |
| "ndcg_gain_at_least_0_05": ( | |
| candidate["overall"]["ndcg"] - baseline["overall"]["ndcg"] >= 0.05 | |
| ), | |
| "recall_not_lower": ( | |
| candidate["overall"]["recall"] >= baseline["overall"]["recall"] | |
| ), | |
| "mrr_not_lower": candidate["overall"]["mrr"] >= baseline["overall"]["mrr"], | |
| "no_category_ndcg_drop_over_0_05": all( | |
| difference >= -0.05 for difference in category_drops.values() | |
| ), | |
| "zero_filter_leakage": candidate.get("filter_leaks") == 0, | |
| "deterministic_repeat_rankings": candidate.get("deterministic") is True, | |
| "p95_under_one_second": candidate["latency_ms"]["p95"] < 1000, | |
| "p95_no_more_than_twice_baseline": ( | |
| candidate["latency_ms"]["p95"] <= 2 * max(baseline["latency_ms"]["p95"], 1) | |
| ), | |
| } | |
| return {"passed": all(checks.values()), "checks": checks} | |
| def _parser() -> argparse.ArgumentParser: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("benchmark", type=Path) | |
| parser.add_argument("--output", type=Path, required=True) | |
| parser.add_argument("--baseline", type=Path) | |
| parser.add_argument("--top-k", type=int, default=5) | |
| parser.add_argument( | |
| "--mode", choices=("hybrid", "vector-baseline"), default="hybrid" | |
| ) | |
| parser.add_argument("--skip-determinism-check", action="store_true") | |
| parser.add_argument("--allow-small", action="store_true", help=argparse.SUPPRESS) | |
| return parser | |
| def main() -> int: | |
| setup_logger() | |
| args = _parser().parse_args() | |
| rows = load_benchmark(args.benchmark, allow_small=args.allow_small) | |
| report = evaluate( | |
| rows, | |
| top_k=args.top_k, | |
| mode=args.mode, | |
| verify_determinism=not args.skip_determinism_check, | |
| ) | |
| if args.baseline: | |
| baseline = json.loads(args.baseline.read_text(encoding="utf-8")) | |
| report["acceptance"] = compare(report, baseline) | |
| args.output.write_text( | |
| json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8" | |
| ) | |
| logger.info("Wrote retrieval benchmark report to %s", args.output) | |
| return 0 if report.get("acceptance", {}).get("passed", True) else 1 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |