Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/MojoLlama/blob/main/src/mojollama/eval/arc.py # MojoLlama Archived Mojo/MAX quantizer and serving research repository (read-only history) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `MojoLlama / src / mojollama / eval / arc.py` 189 lines · 6456 bytes Raw Blame History 1 """ARC — AI2 Reasoning Challenge benchmark. 2 3 Multiple choice science questions (Challenge and Easy sets). 4 Uses ai2_arc dataset. 5 """ 6 7 import json 8 import re 9 import time 10 from typing import Optional 11 12 from .base import BaseBenchmark, LlamaCppEvaluator, extract_letter_answer 13 from .dataset import get_dataset_path 14 15 16 FEW_SHOT_EXAMPLES = [ 17 { 18 "question": "Which of the following is an example of a chemical change?", 19 "choices": ["A. Ice melting", "B. Paper burning", "C. Water boiling", "D. Sugar dissolving"], 20 "answer": "B" 21 }, 22 { 23 "question": "What force keeps planets in orbit around the Sun?", 24 "choices": ["A. Magnetism", "B. Friction", "C. Gravity", "D. Electricity"], 25 "answer": "C" 26 }, 27 { 28 "question": "Which organ pumps blood through the human body?", 29 "choices": ["A. Lungs", "B. Liver", "C. Heart", "D. Brain"], 30 "answer": "C" 31 }, 32 { 33 "question": "What is the largest planet in our solar system?", 34 "choices": ["A. Mars", "B. Venus", "C. Saturn", "D. Jupiter"], 35 "answer": "D" 36 }, 37 { 38 "question": "Which of these is a renewable energy source?", 39 "choices": ["A. Coal", "B. Natural gas", "C. Solar power", "D. Oil"], 40 "answer": "C" 41 } 42 ] 43 44 45 def _build_prompt(question, choices): 46 prompt_lines = [ 47 "The following are science questions (with answers).", 48 "" 49 ] 50 for ex in FEW_SHOT_EXAMPLES: 51 prompt_lines.append(ex["question"]) 52 for ch in ex["choices"]: 53 prompt_lines.append(ch) 54 prompt_lines.append(f"Answer: {ex['answer']}") 55 prompt_lines.append("") 56 57 prompt_lines.append(question) 58 for ch in choices: 59 prompt_lines.append(ch) 60 prompt_lines.append("Answer:") 61 return "\n".join(prompt_lines) 62 63 64 def _load_arc_jsonl(path: str) -> list: 65 """Load ARC dataset from JSONL format.""" 66 records = [] 67 try: 68 with open(path, "r") as f: 69 for line in f: 70 line = line.strip() 71 if line: 72 records.append(json.loads(line)) 73 except Exception: 74 pass 75 return records 76 77 78 class ARCBenchmark(BaseBenchmark): 79 """ARC benchmark — AI2 Reasoning Challenge (Challenge + Easy).""" 80 81 @property 82 def name(self) -> str: 83 return "ARC" 84 85 def run(self, backend_url: str, model_name: str, 86 max_samples: int = 0, variant: str = "challenge", 87 **kwargs) -> dict: 88 evaluator = LlamaCppEvaluator(backend_url, temperature=0.0, max_tokens=32) 89 t0 = time.time() 90 91 total_correct = 0 92 total_all = 0 93 per_category = {} 94 95 variants_to_run = ["challenge", "easy"] if variant == "all" else [variant] 96 97 for v in variants_to_run: 98 # Try multiple possible file names 99 possible = [ 100 get_dataset_path("arc", subject=f"ARC-{v.capitalize()}-Test"), 101 None 102 ] 103 import os 104 base = os.path.expanduser("~/.mojollama/eval_datasets") 105 for fname in [ 106 f"ARC-{v.capitalize()}-Test.jsonl", 107 f"arc_{v}_test.jsonl", 108 f"ARC-{v.capitalize()}-Test.json" 109 ]: 110 p = os.path.join(base, fname) 111 if os.path.exists(p): 112 possible.append(p) 113 114 records = [] 115 for p in possible: 116 if p and os.path.exists(p): 117 records = _load_arc_jsonl(p) 118 if records: 119 break 120 121 if not records: 122 print(f" ⚠ ARC-{v.capitalize()} data not found, download first: mojollama-studio evaluate download") 123 per_category[f"arc_{v}"] = {"correct": 0, "total": 0, "accuracy": 0} 124 continue 125 126 if max_samples > 0: 127 records = records[:max_samples] 128 129 correct = 0 130 total = 0 131 labels = ["A", "B", "C", "D"] 132 133 for record in records: 134 question = record.get("question", "") 135 choices_raw = record.get("choices", {}) 136 answer_key = record.get("answerKey", "") 137 138 # Handle different ARC formats 139 if isinstance(choices_raw, dict): 140 choice_labels = choices_raw.get("label", []) 141 choice_texts = choices_raw.get("text", []) 142 choices = [f"{l}. {t}" for l, t in zip(choice_labels, choice_texts)] 143 elif isinstance(choices_raw, list): 144 choices = [] 145 for i, c in enumerate(choices_raw): 146 if isinstance(c, dict): 147 label = c.get("label", labels[i] if i < len(labels) else chr(65+i)) 148 text = c.get("text", str(c)) 149 choices.append(f"{label}. {text}") 150 else: 151 choices.append(f"{labels[i]}. {c}") 152 else: 153 continue 154 155 prompt = _build_prompt(question, choices) 156 157 try: 158 generated = evaluator.complete(prompt, max_tokens=16) 159 predicted = extract_letter_answer(generated) 160 if predicted is None: 161 m = re.search(r'\b([A-D])\b', generated) 162 if m: 163 predicted = m.group(1) 164 if predicted and predicted == answer_key: 165 correct += 1 166 except Exception: 167 pass 168 169 total += 1 170 171 acc = correct / total if total > 0 else 0 172 per_category[f"arc_{v}"] = {"correct": correct, "total": total, "accuracy": acc} 173 total_correct += correct 174 total_all += total 175 print(f" ARC-{v.capitalize()}: {acc*100:.2f}% ({correct}/{total})") 176 177 elapsed = time.time() - t0 178 stats = evaluator.get_stats() 179 overall_acc = total_correct / total_all if total_all > 0 else 0 180 181 return { 182 "name": "ARC", 183 "accuracy": overall_acc, 184 "correct": total_correct, 185 "total": total_all, 186 "per_category": per_category, 187 "metrics": {"elapsed": elapsed, "api_calls": stats["api_calls"], "api_errors": stats["api_errors"]}, 188 "samples": total_all 189 }