EllaNAM's picture
Add editable evaluation notebooks and their Python source
46e547f verified
Raw History Blame Contribute Delete
2.17 kB
"""Compare base and trained BGE with the original cascade answer prompt."""
from contextlib import closing
import gc
import json
from pathlib import Path
import torch
from local_followup import atomic_json, batches, HFGenerator, ProcessedCorpus, exact_match, evaluate
from rag_assignment.generator.prompt import SYSTEM_PROMPT
def compare_readers(qa, settings, output, ranking):
variants = {}
reader = HFGenerator(settings["models"]["qwen"], device="cuda", fp16=True, batch_size=1, system_prompt=SYSTEM_PROMPT)
with closing(ProcessedCorpus(Path(settings["corpus"]))) as corpus:
from passage_vote import PassageVoteReader
for variant in ("bge-trained", "bge-base", "bge-trained-vote"):
generator = PassageVoteReader(reader) if variant.endswith("-vote") else reader
folder = output / ("cascade-reader-" + variant)
rows = ranking[variant.removesuffix("-vote")]
if not (folder / "predictions.jsonl").exists():
predictions = []
for batch, hits in zip(batches(qa), batches(rows), strict=True):
contexts = [[corpus.get(str(pid)).as_doc() for pid in row["prompt_pids"]] for row in hits]
answers = generator.batch_generate([q.question for q in batch], contexts)
predictions.extend({"qid": q.qid, "question": q.question, **a._asdict()} for q,a in zip(batch, answers, strict=True))
atomic_json(folder / "retrieval.jsonl", rows, jsonl=True)
atomic_json(folder / "predictions.jsonl", predictions, jsonl=True)
scores, details = evaluate(folder, qa, Path(settings["official_corpus"]), kvalues=[5,100])
variants[variant] = {"recall@100":scores["recall_at_k"][100], "recall@5":scores["recall_at_k"][5],
"span_em":scores["span_em"], "f1":scores["f1"],
"em":sum(exact_match(item.pred_answer, item.answers) for item in details)/len(details)}
del reader
gc.collect()
torch.cuda.empty_cache()
atomic_json(output / "cascade-reader-comparison.json", variants)
return variants