|
| 1 | +import json |
| 2 | +import re |
| 3 | +from datetime import datetime, timezone |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | +from datasets import load_dataset |
| 7 | + |
| 8 | +from .constants import DATASET_NAME, MAX_NEW_TOKENS_MULTIPLE_CHOICE |
| 9 | + |
| 10 | + |
| 11 | +def _build_mc_prompt(row: dict) -> str: |
| 12 | + lines = [ |
| 13 | + "You are an expert in additive manufacturing.", |
| 14 | + "Answer the following multiple-choice question by responding with only the letter of the correct answer (A, B, C, or D).", |
| 15 | + "", |
| 16 | + f"Question: {row['question']}", |
| 17 | + "", |
| 18 | + "Choices:", |
| 19 | + ] |
| 20 | + for choice in row["choices"]: |
| 21 | + lines.append(f" {choice['label']}. {choice['text']}") |
| 22 | + lines += [ |
| 23 | + "", |
| 24 | + "Answer (single letter only):", |
| 25 | + ] |
| 26 | + return "\n".join(lines) |
| 27 | + |
| 28 | + |
| 29 | +def _parse_mc_answer(response: str) -> str | None: |
| 30 | + """Extract the first A/B/C/D letter from a model response.""" |
| 31 | + match = re.search(r"\b([A-D])\b", response.strip()) |
| 32 | + return match.group(1) if match else None |
| 33 | + |
| 34 | + |
| 35 | +def _benchmark_general_knowledge_multiple_choice( |
| 36 | + runner, |
| 37 | + model: str, |
| 38 | + num_proc: int, |
| 39 | + out_path: Path | None, |
| 40 | +) -> dict: |
| 41 | + config = "general_knowledge_multiple_choice" |
| 42 | + print(f"\n[{config}] Loading dataset...") |
| 43 | + train_data = load_dataset(DATASET_NAME, config, num_proc=num_proc)["train"] |
| 44 | + |
| 45 | + prompts = [_build_mc_prompt(row) for row in train_data] |
| 46 | + responses = runner(prompts, MAX_NEW_TOKENS_MULTIPLE_CHOICE) |
| 47 | + |
| 48 | + results = [] |
| 49 | + correct_count = 0 |
| 50 | + no_response_count = 0 |
| 51 | + |
| 52 | + for i, row in enumerate(train_data): |
| 53 | + predicted = _parse_mc_answer(responses[i]) |
| 54 | + correct = row["correct_answer"] |
| 55 | + is_correct = predicted == correct if predicted is not None else False |
| 56 | + if predicted is None: |
| 57 | + no_response_count += 1 |
| 58 | + if is_correct: |
| 59 | + correct_count += 1 |
| 60 | + |
| 61 | + results.append( |
| 62 | + { |
| 63 | + "source": row["source"], |
| 64 | + "process": row["process"], |
| 65 | + "question": row["question"], |
| 66 | + "choices": row["choices"], |
| 67 | + "correct_answer": correct, |
| 68 | + "response": responses[i], |
| 69 | + "predicted": predicted, |
| 70 | + "is_correct": is_correct, |
| 71 | + } |
| 72 | + ) |
| 73 | + |
| 74 | + total = len(results) |
| 75 | + answered = total - no_response_count |
| 76 | + accuracy = round(correct_count / total, 4) if total else 0.0 |
| 77 | + |
| 78 | + report = { |
| 79 | + "model": model, |
| 80 | + "dataset": DATASET_NAME, |
| 81 | + "config": config, |
| 82 | + "timestamp": datetime.now(timezone.utc).isoformat(), |
| 83 | + "total_questions": total, |
| 84 | + "no_response": no_response_count, |
| 85 | + "answered": answered, |
| 86 | + "correct": correct_count, |
| 87 | + "accuracy": accuracy, |
| 88 | + "results": results, |
| 89 | + } |
| 90 | + |
| 91 | + _print_gkmc_report(report) |
| 92 | + |
| 93 | + if out_path is not None: |
| 94 | + report_file = Path(out_path) / f"{config}.json" |
| 95 | + with open(report_file, "w") as f: |
| 96 | + json.dump(report, f, indent=2) |
| 97 | + print(f"Report saved to: {report_file}") |
| 98 | + |
| 99 | + return report |
| 100 | + |
| 101 | + |
| 102 | +def _print_gkmc_report(report: dict): |
| 103 | + sep = "-" * 60 |
| 104 | + print(sep) |
| 105 | + print("General Knowledge Multiple Choice — Report") |
| 106 | + print(sep) |
| 107 | + print(f"Model: {report['model']}") |
| 108 | + print(f"Total questions: {report['total_questions']}") |
| 109 | + print(f"No response: {report['no_response']}") |
| 110 | + print(f"Answered: {report['answered']}") |
| 111 | + print(f"Correct: {report['correct']}") |
| 112 | + print(f"Accuracy: {report['accuracy']:.2%}") |
| 113 | + print(sep) |
| 114 | + for i, r in enumerate(report["results"], 1): |
| 115 | + mark = "✓" if r["is_correct"] else "✗" |
| 116 | + print(f"[{i:>3}] {mark} {r['source']} ({r['process']})") |
| 117 | + print(f" Q: {r['question'][:100]}") |
| 118 | + print(f" Predicted: {r['predicted']} Correct: {r['correct_answer']}") |
| 119 | + print(sep) |
| 120 | + print( |
| 121 | + f"Accuracy: {report['accuracy']:.2%} ({report['correct']}/{report['total_questions']})" |
| 122 | + ) |
| 123 | + print(sep) |
0 commit comments