File size: 9,089 Bytes
2ab2b76 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | """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,
)
|