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 / humaneval.py

131 lines · 4370 bytes Raw Blame History
1"""HumanEval — Code generation benchmark.
2
3OpenAI's HumanEval: write function from docstring, pass/fail by unit test.
4Evaluates functional correctness (pass@k).
5"""
6
7import json
8import re
9import time
10from typing import Optional
11
12from .base import BaseBenchmark, LlamaCppEvaluator
13from .dataset import get_dataset_stream
14
15
16FEW_SHOT_EXAMPLES = [
17 {
18 "prompt": 'def add(a, b):\n """Return the sum of a and b."""',
19 "result": ' return a + b'
20 },
21 {
22 "prompt": 'def is_even(n):\n """Return True if n is even, False otherwise."""',
23 "result": ' return n % 2 == 0'
24 },
25 {
26 "prompt": 'def factorial(n):\n """Return n! for n >= 0."""',
27 "result": ' if n <= 1:\n return 1\n return n * factorial(n - 1)'
28 }
29]
30
31
32def _build_humaneval_prompt(prompt_text: str) -> str:
33 """Build HumanEval prompt with few-shot examples."""
34 parts = [
35 "Complete the following Python functions. Return only the function body with proper indentation.",
36 ""
37 ]
38 for ex in FEW_SHOT_EXAMPLES:
39 parts.append(ex["prompt"])
40 parts.append(ex["result"])
41 parts.append("")
42
43 parts.append(prompt_text)
44 return "\n".join(parts)
45
46
47def _extract_code(text: str) -> str:
48 """Extract code from model output, removing markdown fences."""
49 # Remove markdown code blocks
50 text = re.sub(r'```(?:python)?\n?', '', text)
51 # Remove trailing explanations
52 text = re.split(r'\n(?:# |"""|\'\'\'|Explanation)', text)[0]
53 # Get indented body
54 lines = text.strip().split('\n')
55 body = []
56 for line in lines:
57 if line.startswith(' ') or line.startswith('\t') or line.strip() == '':
58 body.append(line)
59 elif not body and line.strip():
60 # First line might be the signature, skip it
61 continue
62 elif body and not line.startswith(' ') and line.strip():
63 # We've moved past the function body
64 break
65 return '\n'.join(body).strip()
66
67
68class HumanEvalBenchmark(BaseBenchmark):
69 """HumanEval — code generation, functional correctness."""
70
71 @property
72 def name(self) -> str:
73 return "HumanEval"
74
75 def run(self, backend_url: str, model_name: str,
76 max_samples: int = 0, **kwargs) -> dict:
77 evaluator = LlamaCppEvaluator(backend_url, temperature=0.2, max_tokens=512)
78 t0 = time.time()
79
80 records = get_dataset_stream("humaneval")
81 if not records:
82 return {"name": "HumanEval", "accuracy": 0, "correct": 0, "total": 0,
83 "per_category": {}, "metrics": {"elapsed": time.time() - t0},
84 "samples": 0, "error": "No dataset. Run download first."}
85
86 if max_samples > 0:
87 records = records[:max_samples]
88
89 correct = 0
90 total = 0
91
92 for record in records:
93 prompt_text = record.get("prompt", "")
94 entry_point = record.get("entry_point", "")
95 test_code = record.get("test", "")
96 canonical = record.get("canonical_solution", "")
97
98 prompt = _build_humaneval_prompt(prompt_text)
99
100 try:
101 generated = evaluator.complete(prompt, max_tokens=384, temperature=0.2)
102 body = _extract_code(generated)
103
104 if body:
105 # Build complete function and run test
106 full_code = f"{prompt_text}\n{body}\n\n{test_code}\ncheck({entry_point})"
107 try:
108 exec_globals = {}
109 exec(full_code, exec_globals)
110 correct += 1
111 except Exception:
112 pass
113 except Exception:
114 pass
115
116 total += 1
117
118 elapsed = time.time() - t0
119 stats = evaluator.get_stats()
120 acc = correct / total if total > 0 else 0
121 print(f" HumanEval: {acc*100:.2f}% pass@1 ({correct}/{total})")
122
123 return {
124 "name": "HumanEval",
125 "accuracy": acc,
126 "correct": correct,
127 "total": total,
128 "per_category": {"python_code_gen": {"correct": correct, "total": total, "accuracy": acc}},
129 "metrics": {"elapsed": elapsed, "api_calls": stats["api_calls"], "api_errors": stats["api_errors"]},
130 "samples": total
131 }