Download evaluation/inference_eval.py from EllaNAM/rag-assignment-processed-bm25: direct link, hf CLI and curl.
- Browser
- Download file 13.6 kB
-
https://huggingface.co/datasets/EllaNAM/rag-assignment-processed-bm25/resolve/main/evaluation/inference_eval.py
- Command line
-
hf download hf://datasets/EllaNAM/rag-assignment-processed-bm25/evaluation/inference_eval.py
-
curl -L -o inference_eval.py https://huggingface.co/datasets/EllaNAM/rag-assignment-processed-bm25/resolve/main/evaluation/inference_eval.py
13.6 kB
| #!/usr/bin/env python3 | |
| """BM25 (100), MiniLM (50), BGE (5), Qwen generation, and official-compatible scoring.""" | |
| from __future__ import annotations | |
| import argparse | |
| from dataclasses import dataclass | |
| import json | |
| import math | |
| from pathlib import Path | |
| from typing import Callable | |
| from rag_assignment.corpus import ProcessedCorpus | |
| from rag_assignment.grading import EfficiencyTracker | |
| from rag_assignment.grading.metrics import answer_recall_at_k, f1_score, has_answer, normalize_answer | |
| from rag_assignment.pipeline import RAGPipeline | |
| from rag_assignment.retriever.bm25 import BM25Retriever, Candidate, OfficialBM25Baseline | |
| from rag_assignment.utils import load_qa_dataset | |
| RETRIEVER_MODE = "lexical" | |
| RETRIEVAL_K = 100 | |
| CASCADE_K = 50 | |
| CONTEXT_K = 5 | |
| MINILM = "cross-encoder/ms-marco-MiniLM-L-6-v2" | |
| MINILM_REVISION = "233902d25c440f23af6f7d6e94d2946bac0bee0a" | |
| GENERATOR = "Qwen/Qwen2.5-1.5B-Instruct" | |
| GENERATOR_REVISION = "989aa7980e4cf806f80c7fef2b1adb7bc71aa306" | |
| BASELINE_PROMPT = ("You are a helpful assistant that answers the question. " | |
| "Answer with a short phrase only, without any explanation.") | |
| PROMPT_ORDER = (0, 2, 4, 3, 1) | |
| PairScorer = Callable[[list[tuple[str, str]]], list[float]] | |
| class CrossEncoderScorer: | |
| def __init__(self, checkpoint: str | Path, *, device: str, batch_size: int, | |
| max_length: int | None, fp16: bool = True, revision: str | None = None): | |
| import torch | |
| from transformers import AutoModelForSequenceClassification, AutoTokenizer | |
| self.torch = torch | |
| self.device = torch.device(device) | |
| self.batch_size = batch_size | |
| dtype = torch.float16 if fp16 and self.device.type == "cuda" else torch.float32 | |
| self.tokenizer = AutoTokenizer.from_pretrained(str(checkpoint), revision=revision) | |
| self.model = AutoModelForSequenceClassification.from_pretrained( | |
| str(checkpoint), dtype=dtype, revision=revision | |
| ) | |
| self.model.to(self.device).eval() | |
| if self.model.config.num_labels != 1: | |
| raise ValueError(f"Expected one relevance logit per pair for {checkpoint}") | |
| self.max_length = max_length or getattr(self.model.config, "reranker_max_length", 384) | |
| def __call__(self, pairs: list[tuple[str, str]]) -> list[float]: | |
| result = [] | |
| with self.torch.inference_mode(): | |
| for start in range(0, len(pairs), self.batch_size): | |
| queries, docs = zip(*pairs[start:start + self.batch_size]) | |
| inputs = self.tokenizer( | |
| list(queries), list(docs), padding=True, truncation=True, | |
| max_length=self.max_length, return_tensors="pt", | |
| ).to(self.device) | |
| logits = self.model(**inputs).logits.flatten() | |
| result.extend(logits.float().cpu().tolist()) | |
| return result | |
| class RankedHit: | |
| candidate: Candidate | |
| score: float | |
| class CascadeResult: | |
| reranked_50: list[RankedHit] | |
| omitted: list[Candidate] | |
| def prompt_hits(self) -> list[RankedHit]: | |
| return [self.reranked_50[i] for i in PROMPT_ORDER if i < len(self.reranked_50)] | |
| def min_max(values: list[float]) -> list[float]: | |
| if not values: | |
| return [] | |
| low, high = min(values), max(values) | |
| return [(value - low) / (high - low) if high > low else 0.0 for value in values] | |
| def score_candidate_batches( | |
| questions: list[str], batches: list[list[Candidate]], scorer: PairScorer, | |
| ) -> list[list[float]]: | |
| pairs = [ | |
| (question, hit.passage.pair_text) | |
| for question, hits in zip(questions, batches, strict=True) for hit in hits | |
| ] | |
| scores = scorer(pairs) | |
| if len(scores) != len(pairs) or not all(map(math.isfinite, scores)): | |
| raise ValueError("Cross-encoder must return one finite score per question-passage pair") | |
| grouped = [] | |
| offset = 0 | |
| for hits in batches: | |
| grouped.append(scores[offset:offset + len(hits)]) | |
| offset += len(hits) | |
| return grouped | |
| def cascade_rerank( | |
| questions: list[str], bm25_hits: list[list[Candidate]], fast: PairScorer, precise: PairScorer, | |
| ) -> list[CascadeResult]: | |
| fast_scores = score_candidate_batches(questions, bm25_hits, fast) | |
| shortlist = [] | |
| omitted = [] | |
| for hits, scores in zip(bm25_hits, fast_scores, strict=True): | |
| ordered = sorted(zip(hits, scores), key=lambda item: (-item[1], item[0].bm25_rank)) | |
| selected = [hit for hit, _ in ordered[:CASCADE_K]] | |
| selected_ranks = {hit.bm25_rank for hit in selected} | |
| shortlist.append(selected) | |
| omitted.append([hit for hit in hits if hit.bm25_rank not in selected_ranks]) | |
| precise_scores = score_candidate_batches(questions, shortlist, precise) | |
| results = [] | |
| for hits, scores, tail in zip(shortlist, precise_scores, omitted, strict=True): | |
| original = min_max([hit.bm25_score for hit in hits]) | |
| reranker = min_max(scores) | |
| ranked = [ | |
| RankedHit(hit, 0.8 * precise_score + 0.2 * bm25_score + (0.04 if hit.passage.position_idx == 0 else 0.0)) | |
| for hit, precise_score, bm25_score in zip(hits, reranker, original, strict=True) | |
| ] | |
| ranked.sort(key=lambda hit: (-hit.score, hit.candidate.bm25_rank)) | |
| results.append(CascadeResult(ranked, tail)) | |
| return results | |
| def exact_match(prediction: str, answers: list[str]) -> bool: | |
| normalized = normalize_answer(prediction) | |
| return bool(normalized) and any(normalized == normalize_answer(answer) for answer in answers) | |
| def run_evaluation( | |
| qa, retriever, fast: PairScorer | None, precise: PairScorer | None, | |
| generator, output_dir: Path, question_batch_size: int, *, experiment: str = "cascade", | |
| ) -> dict: | |
| if not qa or question_batch_size < 1: | |
| raise ValueError("Evaluation requires questions and a positive question batch size") | |
| if len({entry.qid for entry in qa}) != len(qa): | |
| raise ValueError("Duplicate qid in dev_qa") | |
| if (fast is None) != (precise is None): | |
| raise ValueError("Provide both cross-encoders together") | |
| use_cascade = fast is not None and precise is not None | |
| tracker = EfficiencyTracker(num_questions=len(qa)) | |
| records, predictions, per_question = [], [], [] | |
| for start in range(0, len(qa), question_batch_size): | |
| batch = qa[start:start + question_batch_size] | |
| questions = [row.question for row in batch] | |
| with tracker.measure("bm25"): | |
| bm25_hits = retriever.batch_candidates(questions, RETRIEVAL_K) | |
| if any(len(hits) != RETRIEVAL_K for hits in bm25_hits): | |
| raise ValueError("The fixed evaluation requires 100 BM25 candidates per question") | |
| if use_cascade: | |
| with tracker.measure("reranking"): | |
| cascaded = cascade_rerank(questions, bm25_hits, fast, precise) | |
| final_hits = [ | |
| [hit.candidate for hit in result.reranked_50] + result.omitted | |
| for result in cascaded | |
| ] | |
| scores_by_question = [ | |
| [hit.score for hit in result.reranked_50] + [None] * len(result.omitted) | |
| for result in cascaded | |
| ] | |
| prompt_hits = [[hit.candidate for hit in result.prompt_hits] for result in cascaded] | |
| else: | |
| final_hits = bm25_hits | |
| scores_by_question = [[hit.bm25_score for hit in row] for row in bm25_hits] | |
| prompt_hits = [row[:CONTEXT_K] for row in bm25_hits] | |
| with tracker.measure("generation"): | |
| contexts = [[hit.passage.as_doc() for hit in row] for row in prompt_hits] | |
| generated = generator.batch_generate(questions, contexts) | |
| for entry, initial, all_hits, scores, context_hits, out in zip( | |
| batch, bm25_hits, final_hits, scores_by_question, prompt_hits, generated, strict=True | |
| ): | |
| records.append({ | |
| "qid": entry.qid, "pids": [hit.passage.pid for hit in all_hits], | |
| "scores": scores, | |
| "bm25_pids": [hit.passage.pid for hit in initial], | |
| "bm25_scores": [hit.bm25_score for hit in initial], | |
| "prompt_pids": [hit.passage.pid for hit in context_hits], | |
| }) | |
| predictions.append({"qid": entry.qid, "question": entry.question, **out._asdict()}) | |
| metrics = answer_recall_at_k( | |
| [hit.passage.original_text for hit in all_hits], entry.answers, [5, 100] | |
| ) | |
| per_question.append({ | |
| "qid": entry.qid, "recall@5": metrics[5], "recall@100": metrics[100], | |
| "em": exact_match(out.text, entry.answers), "f1": f1_score(out.text, entry.answers), | |
| "span_em": has_answer(out.text, entry.answers), | |
| }) | |
| efficiency = tracker.result() | |
| summary = { | |
| "questions": len(qa), | |
| "experiment": experiment, | |
| "generator_model": GENERATOR, | |
| "generator_revision": GENERATOR_REVISION, | |
| "minilm_revision": MINILM_REVISION if use_cascade else None, | |
| "retriever_mode": RETRIEVER_MODE, | |
| "retrieval_k": RETRIEVAL_K, "cascade_k": CASCADE_K if use_cascade else None, "context_k": CONTEXT_K, | |
| **{key: sum(row[key] for row in per_question) / len(qa) | |
| for key in ("recall@100", "recall@5", "em", "f1", "span_em")}, | |
| "seconds_per_question": efficiency.seconds_per_question, | |
| } | |
| RAGPipeline.save_results(records, predictions, efficiency, output_dir) | |
| (output_dir / "inference_summary.json").write_text( | |
| json.dumps(summary, indent=2) + "\n", encoding="utf-8" | |
| ) | |
| with (output_dir / "metrics_by_question.jsonl").open("w", encoding="utf-8") as stream: | |
| for row in per_question: | |
| stream.write(json.dumps(row) + "\n") | |
| return summary | |
| def parse_args(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--corpus", type=Path, default=Path("data/processed_corpus.jsonl")) | |
| parser.add_argument("--experiment", choices=("official-bm25", "processed-bm25", "cascade"), default="cascade") | |
| parser.add_argument("--dev", type=Path, default=Path("data/dev_qa.jsonl")) | |
| parser.add_argument("--index-dir", type=Path, default=Path("data/index/bm25-sparse")) | |
| parser.add_argument("--reranker-dir", type=Path, default=Path("models/finetuned-bge-reranker")) | |
| parser.add_argument("--output-dir", type=Path, default=Path("outputs/bm25-cascade-dev")) | |
| parser.add_argument("--query-batch-size", type=int, default=8) | |
| parser.add_argument("--minilm-batch-size", type=int, default=64) | |
| parser.add_argument("--bge-batch-size", type=int, default=32) | |
| parser.add_argument("--generation-batch-size", type=int, default=4) | |
| parser.add_argument("--fp16", action=argparse.BooleanOptionalAction, default=True) | |
| parser.add_argument("--device", default="auto") | |
| parser.add_argument("--limit", type=int, help="Use a prefix of dev for an integration check") | |
| args = parser.parse_args() | |
| if min(args.query_batch_size, args.minilm_batch_size, args.bge_batch_size, args.generation_batch_size, | |
| args.limit if args.limit is not None else 1) < 1: | |
| parser.error("Batch sizes and optional question limit must be positive") | |
| return args | |
| def main(): | |
| import torch | |
| from rag_assignment.generator import HFGenerator | |
| args = parse_args() | |
| use_cascade = args.experiment == "cascade" | |
| official_baseline = args.experiment == "official-bm25" | |
| if use_cascade and not (args.reranker_dir / "config.json").is_file(): | |
| raise FileNotFoundError(f"Train the local BGE reranker first: {args.reranker_dir}") | |
| device = ("cuda" if torch.cuda.is_available() else "cpu") if args.device == "auto" else args.device | |
| qa = load_qa_dataset(args.dev)[:args.limit] | |
| with ProcessedCorpus(args.corpus, raw=official_baseline) as corpus: | |
| checkpoint_summary = args.reranker_dir / "training_summary.json" | |
| if use_cascade and checkpoint_summary.is_file(): | |
| trained = json.loads(checkpoint_summary.read_text(encoding="utf-8")) | |
| evidence_hash = trained.get("evidence_sha256") | |
| matches = (evidence_hash == corpus.evidence_sha256 if evidence_hash | |
| else trained.get("corpus_sha256") == corpus.sha256) | |
| if not matches: | |
| raise ValueError("Corpus evidence differs from the evidence used to train this reranker") | |
| retriever = OfficialBM25Baseline() if official_baseline else BM25Retriever() | |
| retriever.load(args.index_dir, corpus) | |
| fast = precise = None | |
| if use_cascade: | |
| fast = CrossEncoderScorer(MINILM, device=device, batch_size=args.minilm_batch_size, | |
| max_length=256, fp16=args.fp16, revision=MINILM_REVISION) | |
| precise = CrossEncoderScorer(args.reranker_dir, device=device, batch_size=args.bge_batch_size, | |
| max_length=None, fp16=args.fp16) | |
| generator = HFGenerator( | |
| GENERATOR, max_seq_length=2048, max_ans_length=32, | |
| batch_size=args.generation_batch_size, fp16=args.fp16, device=device, | |
| system_prompt=BASELINE_PROMPT if official_baseline else None, | |
| revision=GENERATOR_REVISION, | |
| ) | |
| summary = run_evaluation( | |
| qa, retriever, fast, precise, generator, args.output_dir, args.query_batch_size, | |
| experiment=args.experiment, | |
| ) | |
| print(json.dumps(summary, indent=2), flush=True) | |
| if __name__ == "__main__": | |
| main() | |