interplane.Get Omega
Read in your language

MojoLlama

Archived Mojo/MAX quantizer and serving research repository (read-only history)

Brought by drakestapleton

branch main Branches Tags History

MojoLlama / src / mojollama / eval / ceval.py

159 lines · 5140 bytes Raw Blame History
1"""CEval — Chinese Evaluation benchmark.
2
352 subjects, multiple choice evaluation in Chinese.
4Uses ceval/ceval-exam dataset format.
5"""
6
7import json
8import re
9import time
10from typing import Optional
11
12from .base import BaseBenchmark, LlamaCppEvaluator, extract_letter_answer
13from .dataset import get_dataset_stream, get_subjects
14
15
16# Few-shot examples for CEval
17CEVAL_FEW_SHOT = [
18 {
19 "question": "中国的首都是哪个城市?",
20 "choices": ["A. 上海", "B. 北京", "C. 广州", "D. 深圳"],
21 "answer": "B"
22 },
23 {
24 "question": "太阳从哪个方向升起?",
25 "choices": ["A. 西方", "B. 南方", "C. 北方", "D. 东方"],
26 "answer": "D"
27 },
28 {
29 "question": "一年有多少个月?",
30 "choices": ["A. 10个月", "B. 11个月", "C. 12个月", "D. 13个月"],
31 "answer": "C"
32 },
33 {
34 "question": "以下哪个是中国的四大发明?",
35 "choices": ["A. 造纸术", "B. 蒸汽机", "C. 电灯", "D. 手机"],
36 "answer": "A"
37 },
38 {
39 "question": "水的化学式是什么?",
40 "choices": ["A. CO2", "B. H2O", "C. NaCl", "D. O2"],
41 "answer": "B"
42 }
43]
44
45
46def _build_ceval_prompt(question, choices, few_shot=None):
47 """Build a CEval prompt in Chinese with few-shot examples."""
48 if few_shot is None:
49 few_shot = CEVAL_FEW_SHOT
50
51 prompt_lines = [
52 "以下是选择题(请选择正确的答案)。",
53 ""
54 ]
55 for ex in few_shot:
56 prompt_lines.append(ex["question"])
57 for ch in ex["choices"]:
58 prompt_lines.append(ch)
59 prompt_lines.append(f"答案: {ex['answer']}")
60 prompt_lines.append("")
61
62 prompt_lines.append(question)
63 for ch in choices:
64 prompt_lines.append(ch)
65 prompt_lines.append("答案:")
66
67 return "\n".join(prompt_lines)
68
69
70class CEvalBenchmark(BaseBenchmark):
71 """CEval benchmark — 52 subjects, Chinese multiple choice."""
72
73 @property
74 def name(self) -> str:
75 return "CEval"
76
77 def run(self, backend_url: str, model_name: str,
78 max_samples: int = 0, subjects: Optional[list] = None,
79 **kwargs) -> dict:
80 evaluator = LlamaCppEvaluator(backend_url, temperature=0.0, max_tokens=50)
81 t0 = time.time()
82
83 all_subjects = subjects or get_subjects("ceval")
84 per_category = {}
85 total_correct = 0
86 total_all = 0
87
88 for subject in all_subjects:
89 records = get_dataset_stream("ceval", subject)
90 if not records:
91 print(f" ⚠ No data for {subject}, skipping")
92 continue
93
94 if max_samples > 0:
95 records = records[:max_samples]
96
97 subject_correct = 0
98 subject_total = 0
99
100 for record in records:
101 question = record.get("question", "")
102 choices = record.get("choices", [])
103 answer_idx = record.get("answer", -1)
104
105 labels = ["A", "B", "C", "D"]
106 answer_letter = labels[answer_idx] if 0 <= answer_idx < len(labels) else None
107 if answer_letter is None:
108 continue
109
110 formatted_choices = [
111 f"{labels[i]}. {choices[i]}"
112 for i in range(len(choices))
113 ]
114
115 prompt = _build_ceval_prompt(question, formatted_choices)
116
117 try:
118 generated = evaluator.complete(prompt, max_tokens=32)
119 predicted = extract_letter_answer(generated)
120 if predicted is None:
121 m = re.search(r'\b([A-D])\b', generated)
122 if m:
123 predicted = m.group(1)
124 if predicted == answer_letter:
125 subject_correct += 1
126 except Exception as e:
127 pass
128
129 subject_total += 1
130
131 per_category[subject] = {
132 "correct": subject_correct,
133 "total": subject_total,
134 "accuracy": subject_correct / subject_total if subject_total > 0 else 0
135 }
136 total_correct += subject_correct
137 total_all += subject_total
138
139 pct = (subject_correct / subject_total * 100) if subject_total > 0 else 0
140 print(f" {subject:40s} {pct:6.2f}% ({subject_correct}/{subject_total})")
141
142 elapsed = time.time() - t0
143 stats = evaluator.get_stats()
144
145 return {
146 "name": "CEval",
147 "accuracy": total_correct / total_all if total_all > 0 else 0,
148 "correct": total_correct,
149 "total": total_all,
150 "per_category": per_category,
151 "metrics": {
152 "elapsed": elapsed,
153 "api_calls": stats["api_calls"],
154 "api_errors": stats["api_errors"],
155 "total_tokens": stats["total_tokens"],
156 "subjects_evaluated": len([s for s in per_category if per_category[s]["total"] > 0])
157 },
158 "samples": total_all
159 }