Download scripts/run_e2e_eval.py from Estarcode/campusdesk-ai: direct link, hf CLI and curl.
- Browser
- Download file 9.09 kB
-
https://huggingface.co/Estarcode/campusdesk-ai/resolve/main/scripts/run_e2e_eval.py
- Command line
-
hf download hf://Estarcode/campusdesk-ai/scripts/run_e2e_eval.py
-
curl -L -o run_e2e_eval.py https://huggingface.co/Estarcode/campusdesk-ai/resolve/main/scripts/run_e2e_eval.py
9.09 kB
| """Run all 24 held-out bilingual prompts through CampusDesk AI and save outputs for evaluation.""" | |
| import argparse | |
| import csv | |
| import gc | |
| import json | |
| import time | |
| from pathlib import Path | |
| import torch | |
| from src.amendments.resolver import resolve_amendments | |
| from src.classification import classifier as cls_mod | |
| from src.config import ( | |
| DEFAULT_DEPLOYED_CLASSIFIER, | |
| E2E_RESULTS_PATH, | |
| GOLD_ANSWERS_PATH, | |
| TEST_SCENARIOS_CSV_PATH, | |
| TOP_K_PASSAGES, | |
| ) | |
| from src.generation.answer_generator import get_generator | |
| from src.grounding.citation_validator import validate_and_clean_citations | |
| from src.pipeline.query_planner import plan_query | |
| from src.retrieval import retriever as ret_mod | |
| def export_test_scenarios_csv() -> None: | |
| """Export the 12 bilingual pairs (24 typed prompts) to evaluation/test_scenarios.csv.""" | |
| pairs = json.loads(GOLD_ANSWERS_PATH.read_text(encoding="utf-8")) | |
| TEST_SCENARIOS_CSV_PATH.parent.mkdir(parents=True, exist_ok=True) | |
| with TEST_SCENARIOS_CSV_PATH.open("w", encoding="utf-8", newline="") as f: | |
| writer = csv.DictWriter( | |
| f, | |
| fieldnames=[ | |
| "prompt_id", | |
| "pair_id", | |
| "category", | |
| "primary_intent", | |
| "language", | |
| "prompt", | |
| "required_passage_ids", | |
| "expected_missing_info", | |
| ], | |
| ) | |
| writer.writeheader() | |
| for pair in pairs: | |
| for lang, key, suffix in [ | |
| ("English", "english_prompt", "EN"), | |
| ("Nigerian Pidgin", "pidgin_prompt", "PCM"), | |
| ]: | |
| writer.writerow( | |
| { | |
| "prompt_id": f"{pair['pair_id']}-{suffix}", | |
| "pair_id": pair["pair_id"], | |
| "category": pair["category"], | |
| "primary_intent": pair["primary_intent"], | |
| "language": lang, | |
| "prompt": pair[key], | |
| "required_passage_ids": ";".join(pair["required_passage_ids"]), | |
| "expected_missing_info": pair["expected_missing_info"], | |
| } | |
| ) | |
| def run_eval( | |
| output_path: Path = E2E_RESULTS_PATH, | |
| classifier_choice: str = DEFAULT_DEPLOYED_CLASSIFIER, | |
| use_subquery_fusion: bool = True, | |
| intent_bonus_weight: float = 0.08, | |
| generator_model_id: str | None = None, | |
| resume: bool = False, | |
| ) -> None: | |
| export_test_scenarios_csv() | |
| pairs = json.loads(GOLD_ANSWERS_PATH.read_text(encoding="utf-8")) | |
| output_path.parent.mkdir(parents=True, exist_ok=True) | |
| existing_by_id: dict[str, dict] = {} | |
| if resume and output_path.exists(): | |
| for line in output_path.read_text(encoding="utf-8").splitlines(): | |
| if line.strip(): | |
| rec = json.loads(line) | |
| existing_by_id[rec["prompt_id"]] = rec | |
| print(f"Resuming with {len(existing_by_id)} completed prompts from {output_path}") | |
| # Stage 1: Plan, classify, retrieve, and resolve amendments for all pending prompts, | |
| # then unload encoder/embedding models before loading the causal LM to prevent CPU RAM swap. | |
| clf = cls_mod.get_classifier(classifier_choice) | |
| ret = ret_mod.get_retriever() | |
| staged_inputs = [] | |
| for pair in pairs: | |
| for lang, prompt_key, suffix in [ | |
| ("English", "english_prompt", "EN"), | |
| ("Nigerian Pidgin", "pidgin_prompt", "PCM"), | |
| ]: | |
| prompt_id = f"{pair['pair_id']}-{suffix}" | |
| if prompt_id in existing_by_id: | |
| staged_inputs.append({"cached": existing_by_id[prompt_id]}) | |
| continue | |
| t0 = time.perf_counter() | |
| prompt = pair[prompt_key] | |
| qplan = plan_query(prompt, use_subquery_fusion=use_subquery_fusion) | |
| intent_pred = clf.predict(qplan.original_query) | |
| top_passages = ret.retrieve( | |
| subqueries=qplan.subqueries, | |
| predicted_intent=intent_pred.label, | |
| top_k=TOP_K_PASSAGES, | |
| intent_bonus_weight=intent_bonus_weight, | |
| ) | |
| amendment_notes = resolve_amendments(top_passages) | |
| pre_ms = (time.perf_counter() - t0) * 1000.0 | |
| staged_inputs.append( | |
| { | |
| "prompt_id": prompt_id, | |
| "pair": pair, | |
| "lang": lang, | |
| "qplan": qplan, | |
| "intent_pred": intent_pred, | |
| "top_passages": top_passages, | |
| "amendment_notes": amendment_notes, | |
| "pre_ms": pre_ms, | |
| } | |
| ) | |
| cls_mod._CLASSIFIER_CACHE.clear() | |
| ret_mod._RETRIEVER_INSTANCE = None | |
| del clf, ret | |
| gc.collect() | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() | |
| # Stage 2: Load generator alone in memory and generate incrementally. | |
| pending_count = sum(1 for item in staged_inputs if "cached" not in item) | |
| gen = get_generator(generator_model_id) if pending_count > 0 else None | |
| rows = [] | |
| with output_path.open("w", encoding="utf-8") as f: | |
| for item in staged_inputs: | |
| if "cached" in item: | |
| rec = item["cached"] | |
| rows.append(rec) | |
| f.write(json.dumps(rec, ensure_ascii=False) + "\n") | |
| f.flush() | |
| continue | |
| pair = item["pair"] | |
| qplan = item["qplan"] | |
| intent_pred = item["intent_pred"] | |
| top_passages = item["top_passages"] | |
| amendment_notes = item["amendment_notes"] | |
| raw_grounded = gen.generate( | |
| query=qplan.original_query, | |
| reply_language=item["lang"], | |
| top_passages=top_passages, | |
| amendment_notes=amendment_notes, | |
| ) | |
| validated = validate_and_clean_citations(raw_grounded, top_passages) | |
| top3_ids = [rp.passage.passage_id for rp in top_passages] | |
| req_ids = pair["required_passage_ids"] | |
| recall_at_3 = ( | |
| round(len(set(req_ids) & set(top3_ids)) / len(req_ids), 4) if req_ids else None | |
| ) | |
| total_ms = round(item["pre_ms"] + validated.latency_ms, 2) | |
| record = { | |
| "prompt_id": item["prompt_id"], | |
| "pair_id": pair["pair_id"], | |
| "category": pair["category"], | |
| "primary_intent": pair["primary_intent"], | |
| "language": item["lang"], | |
| "prompt": qplan.original_query, | |
| "gold_facts": pair["gold_facts"], | |
| "expected_missing_info": pair["expected_missing_info"], | |
| "required_passage_ids": req_ids, | |
| "subqueries_used": qplan.subqueries, | |
| "predicted_intent": intent_pred.label, | |
| "intent_confidence": round(intent_pred.confidence, 4), | |
| "top3_passage_ids": top3_ids, | |
| "top3_scores": [rp.score for rp in top_passages], | |
| "auto_recall_at_3": recall_at_3, | |
| "amendment_notes": amendment_notes, | |
| "answer": validated.answer, | |
| "next_steps": validated.next_steps, | |
| "missing_information": validated.missing_information, | |
| "cited_passage_ids": validated.cited_passage_ids, | |
| "citation_warnings": validated.citation_warnings, | |
| "total_latency_ms": total_ms, | |
| "generator_latency_ms": validated.latency_ms, | |
| "human_judgement": { | |
| "supported_answer": None, | |
| "handling_unknowns_ok": None, | |
| "facts_and_dates_accurate": None, | |
| "notes": "Pending manual verification", | |
| }, | |
| } | |
| rows.append(record) | |
| f.write(json.dumps(record, ensure_ascii=False) + "\n") | |
| f.flush() | |
| print( | |
| f"[{record['prompt_id']:8s}] intent={intent_pred.label:18s} " | |
| f"top3={top3_ids} recall@3={recall_at_3} cited={validated.cited_passage_ids} " | |
| f"({total_ms:.0f} ms)", | |
| flush=True, | |
| ) | |
| print(f"\nSaved {len(rows)} evaluation records to {output_path}") | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--output", type=Path, default=E2E_RESULTS_PATH) | |
| parser.add_argument("--classifier", default=DEFAULT_DEPLOYED_CLASSIFIER) | |
| parser.add_argument("--no-subquery-fusion", action="store_true") | |
| parser.add_argument("--intent-bonus", type=float, default=0.08) | |
| parser.add_argument("--gen-model", default=None) | |
| parser.add_argument("--resume", action="store_true") | |
| args = parser.parse_args() | |
| run_eval( | |
| output_path=args.output, | |
| classifier_choice=args.classifier, | |
| use_subquery_fusion=not args.no_subquery_fusion, | |
| intent_bonus_weight=args.intent_bonus, | |
| generator_model_id=args.gen_model, | |
| resume=args.resume, | |
| ) | |