02 β MMLU
Introduction
MMLU stands for Massive Multitask Language Understanding. It is one of the most widely cited benchmarks for evaluating the breadth and depth of knowledge in large language models. Rather than testing a single skill, MMLU spans 57 academic and professional subjects β from abstract algebra to world religions β forcing the model to demonstrate broad knowledge acquired during pre-training.
Source: Dan Hendrycks, Collin Burns, Steven Basart, Andy Zou, Mantas Mazeika, Dawn Song, and Jacob Steinhardt at UC Berkeley.
Paper: βMeasuring Massive Multitask Language Understandingβ (ICLR 2021).
Primary metric: Accuracy (%) β the percentage of questions answered correctly out of the total. Higher is better.
What MMLU measures: Given a multiple-choice question with 4 options (A, B, C, D), the model must select the correct answer. Questions range from elementary-level knowledge to advanced professional-level problems across 57 subjects. The standard evaluation protocol uses 5-shot prompting β the model sees 5 worked examples before each test question.
- 57 subjects spanning STEM, humanities, social sciences, and professional/other domains.
- ~14,042 multiple-choice test questions, each with exactly 4 answer choices (A, B, C, D).
- 5-shot evaluation is the standard protocol β 5 labelled examples from the dev set precede each question.
- Random baseline: 25% (uniform guess over 4 choices).
- A model scoring 25% has learned nothing; a model scoring 90%+ demonstrates expert-level knowledge across many fields.
Formula & Intuition
The Core Metric
MMLU accuracy is conceptually simple β count the number of correct answers and divide by total questions:
\[\text{Accuracy} = \frac{\text{Number Correct}}{\text{Total Questions}} \times 100\%\]For MMLUβs 14,042 test questions, if a model gets 11,234 correct:
\[\text{Accuracy} = \frac{11{,}234}{14{,}042} \times 100\% = 80.0\%\]How the Model Picks an Answer
There are two primary evaluation methods:
Log-Likelihood Method in Detail
This is the most widely used approach and the one implemented in lm-eval-harness. Here is exactly what happens:
Step 1 β Construct the prompt:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
The following are multiple choice questions (with answers) about {subject}.
Q: {few_shot_question_1}
A. {choice_A}
B. {choice_B}
C. {choice_C}
D. {choice_D}
Answer: {correct_letter}
... (4 more few-shot examples) ...
Q: {test_question}
A. {choice_A}
B. {choice_B}
C. {choice_C}
D. {choice_D}
Answer:
Step 2 β Tokenize and run forward pass:
The prompt is tokenized to input_ids of shape (1, seq_len), then passed through the model to produce logits of shape (1, seq_len, vocab_size).
Step 3 β Extract choice logits:
At the final token position (immediately after βAnswer:β), we extract the logits for the four answer tokens:
\[z_A = \text{logits}[0, -1, \text{tok}(\text{"A"})]\] \[z_B = \text{logits}[0, -1, \text{tok}(\text{"B"})]\] \[z_C = \text{logits}[0, -1, \text{tok}(\text{"C"})]\] \[z_D = \text{logits}[0, -1, \text{tok}(\text{"D"})]\]Step 4 β Pick the answer:
\[\hat{y} = \underset{c \in \{A,B,C,D\}}{\text{argmax}}(z_A, z_B, z_C, z_D)\]Random Baseline and Normalized Accuracy
Since each question has 4 choices, random guessing yields 25%. To account for this floor, some papers report normalized accuracy:
\[\text{Normalized Accuracy} = \frac{\text{Accuracy} - 25}{75} \times 100\%\]This rescales the range so that random guessing maps to 0% and perfect performance maps to 100%. For example, a raw accuracy of 62.5% becomes:
\[\frac{62.5 - 25}{75} \times 100\% = 50\%\]Dataset Details
Quantitative Overview
| Split | Purpose | Questions | Notes |
|---|---|---|---|
| dev | Few-shot exemplars | 285 (5 per subject) | Used as in-context examples; never evaluated |
| validation | Development testing | 1,531 | For hyperparameter tuning |
| test | Final evaluation | 14,042 | The reported number |
| Total | β | 15,858 | Across all splits |
Subject-Level Detail
All 57 subjects with their category assignments and approximate test-set question counts:
| # | Subject | Category | Test Questions |
|---|---|---|---|
| 1 | Abstract Algebra | STEM | 100 |
| 2 | Anatomy | STEM | 135 |
| 3 | Astronomy | STEM | 152 |
| 4 | Business Ethics | Other | 100 |
| 5 | Clinical Knowledge | Other | 265 |
| 6 | College Biology | STEM | 144 |
| 7 | College Chemistry | STEM | 100 |
| 8 | College Computer Science | STEM | 100 |
| 9 | College Mathematics | STEM | 100 |
| 10 | College Medicine | Other | 173 |
| 11 | College Physics | STEM | 102 |
| 12 | Computer Security | STEM | 100 |
| 13 | Conceptual Physics | STEM | 235 |
| 14 | Econometrics | Social Sciences | 114 |
| 15 | Electrical Engineering | STEM | 145 |
| 16 | Elementary Mathematics | STEM | 378 |
| 17 | Formal Logic | Humanities | 126 |
| 18 | Global Facts | Other | 100 |
| 19 | High School Biology | STEM | 310 |
| 20 | High School Chemistry | STEM | 203 |
| 21 | High School Computer Science | STEM | 100 |
| 22 | High School European History | Humanities | 165 |
| 23 | High School Geography | Social Sciences | 198 |
| 24 | High School Government and Politics | Social Sciences | 193 |
| 25 | High School Macroeconomics | Social Sciences | 390 |
| 26 | High School Mathematics | STEM | 270 |
| 27 | High School Microeconomics | Social Sciences | 238 |
| 28 | High School Physics | STEM | 151 |
| 29 | High School Psychology | Social Sciences | 545 |
| 30 | High School Statistics | STEM | 216 |
| 31 | High School US History | Humanities | 204 |
| 32 | High School World History | Humanities | 237 |
| 33 | Human Aging | Other | 223 |
| 34 | Human Sexuality | Social Sciences | 131 |
| 35 | International Law | Humanities | 121 |
| 36 | Jurisprudence | Humanities | 108 |
| 37 | Logical Fallacies | Humanities | 163 |
| 38 | Machine Learning | STEM | 112 |
| 39 | Management | Other | 103 |
| 40 | Marketing | Other | 234 |
| 41 | Medical Genetics | Other | 100 |
| 42 | Miscellaneous | Other | 783 |
| 43 | Moral Disputes | Humanities | 346 |
| 44 | Moral Scenarios | Humanities | 895 |
| 45 | Nutrition | Other | 306 |
| 46 | Philosophy | Humanities | 311 |
| 47 | Prehistory | Humanities | 324 |
| 48 | Professional Accounting | Social Sciences | 282 |
| 49 | Professional Law | Humanities | 1,534 |
| 50 | Professional Medicine | Other | 272 |
| 51 | Professional Psychology | Social Sciences | 612 |
| 52 | Public Relations | Social Sciences | 110 |
| 53 | Security Studies | Social Sciences | 245 |
| 54 | Sociology | Social Sciences | 201 |
| 55 | US Foreign Policy | Social Sciences | 100 |
| 56 | Virology | Other | 166 |
| 57 | World Religions | Humanities | 171 |
Question Format
Every question follows the same structure:
1
2
3
4
5
6
Question: <question text>
A. <choice A>
B. <choice B>
C. <choice C>
D. <choice D>
Answer: <correct letter>
Difficulty ranges from elementary (e.g., βWhat is the capital of France?β) to advanced professional-level (e.g., medical board exam questions, bar exam questions).
MMLU-Pro: The Successor
MMLU-Pro (Wang et al., 2024) is the next-generation version of MMLU with key improvements:
- 10 answer choices (A through J) instead of 4, reducing the random baseline from 25% to 10%
- Harder questions with more reasoning-intensive problems
- Fewer noisy/trivial questions β curated to remove ambiguous or overly simple items
- Used by the Open LLM Leaderboard v2 as a replacement for original MMLU
Figure 1 β MMLU prompt structure: the system header and 5 few-shot examples from the dev split are prepended to each test question. The modelβs logits for tokens A, B, C, D at the last position determine the answer.
Tensor Shapes at Every Stage
The full pipeline from raw text to accuracy score, with tensor shapes annotated at every step. We use LLaMA-3-8B as a concrete example (vocab size = 128,256).
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
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Step 1: Construct prompt (string) β
β β
β prompt = header + 5 few-shot examples + test question β
β prompt: str β
β (typically 300β800 tokens after tokenization) β
ββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Step 2: Tokenize β
β β
β input_ids: (1, seq_len) # e.g., (1, 512) β
β attention_mask: (1, seq_len) # e.g., (1, 512) β
β β
β Each value in input_ids is an integer in [0, vocab_size) β
ββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Step 3: Forward pass through transformer β
β β
β # Internal representations (for reference): β
β embeddings: (1, 512, 4096) # hidden_size = 4096 β
β layer_0_out: (1, 512, 4096) # after first layer β
β ... β
β layer_31_out: (1, 512, 4096) # after last layer β
β β
β # Output: β
β logits: (1, 512, 128256) # (batch, seq, vocab) β
β β
β This is a HUGE tensor: 1 Γ 512 Γ 128,256 = ~65.7M floats β
β At float32: ~262 MB; at bfloat16: ~131 MB β
ββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Step 4: Extract logits at last position β
β β
β last_token_logits = logits[0, -1, :] β
β last_token_logits: (128256,) # one logit per vocab ID β
ββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Step 5: Get token IDs for "A", "B", "C", "D" β
β β
β # These depend on the tokenizer! β
β # LLaMA-3 tokenizer examples: β
β tok("A") β 32 tok("B") β 33 β
β tok("C") β 34 tok("D") β 35 β
β β
β choice_token_ids: (4,) # e.g., tensor([32,33,34,35]) β
β β
β # Index into last_token_logits: β
β choice_logits = last_token_logits[choice_token_ids] β
β choice_logits: (4,) # one logit per choice β
β β
β # Example values: β
β # choice_logits = tensor([2.14, 5.87, 1.03, -0.42]) β
β # A B C D β
ββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Step 6: Select answer β
β β
β prediction = argmax(choice_logits) β
β prediction: scalar (int) # 0=A, 1=B, 2=C, 3=D β
β β
β # In our example: argmax([2.14, 5.87, 1.03, -0.42]) = 1 β
β # So the model predicts "B" β
ββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Step 7: Compare with ground truth β
β β
β ground_truth: scalar (int) # 0=A, 1=B, 2=C, 3=D β
β correct = (prediction == ground_truth) β
β correct: bool # True or False β
ββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Step 8: Aggregate over all 14,042 questions β
β β
β all_correct: (14042,) # boolean array β
β total_correct = sum(all_correct) β
β total_correct: scalar (int) # e.g., 9268 β
β β
β accuracy = total_correct / 14042 Γ 100 β
β accuracy: scalar (float) # e.g., 66.0% β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Per-Subject Aggregation
1
2
3
4
5
6
7
8
9
10
11
# For each of the 57 subjects:
subject_correct[i]: scalar (int) # correct count for subject i
subject_total[i]: scalar (int) # total questions for subject i
subject_accuracy[i]: scalar (float) # subject_correct[i] / subject_total[i] Γ 100
# Category-level:
category_accuracy: (4,) # mean accuracy per category (STEM, Humanities, Social Sci, Other)
# Overall:
overall_accuracy: scalar (float) # sum of all correct / sum of all questions Γ 100
macro_average: scalar (float) # mean of 57 subject accuracies (weights each subject equally)
Note: The standard MMLU score is the macro average over subjects (each subject weighted equally regardless of question count), though some implementations report the micro average (total correct / total questions). These differ slightly because subjects have different numbers of questions.
Evaluation Procedure (Pseudocode)
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
FUNCTION evaluate_mmlu(model, tokenizer, num_fewshot=5):
subjects β list of all 57 MMLU subjects
subject_scores β empty dict
total_correct β 0
total_questions β 0
FOR each subject IN subjects:
# Load data
dev_set β load("cais/mmlu", subject, split="dev") # 5 examples
test_set β load("cais/mmlu", subject, split="test") # N questions
# Build few-shot prefix (same for all questions in this subject)
header β "The following are multiple choice questions (with answers) "
"about {format_subject(subject)}.\n\n"
few_shot_prefix β header
FOR i FROM 0 TO min(num_fewshot, len(dev_set)) - 1:
few_shot_prefix += format_example(dev_set[i], include_answer=True)
END FOR
subject_correct β 0
FOR each example IN test_set:
# Construct prompt
prompt β few_shot_prefix + format_example(example, include_answer=False)
prompt += "Answer:"
# Tokenize
input_ids β tokenizer.encode(prompt) # shape: (1, seq_len)
# Forward pass (no gradient computation)
WITH torch.no_grad():
logits β model(input_ids).logits # shape: (1, seq_len, vocab_size)
# Extract answer logits
last_logits β logits[0, -1, :] # shape: (vocab_size,)
# Get token IDs for choices
choice_ids β [tokenizer.encode("A")[0],
tokenizer.encode("B")[0],
tokenizer.encode("C")[0],
tokenizer.encode("D")[0]]
choice_logits β last_logits[choice_ids] # shape: (4,)
# Predict
prediction β argmax(choice_logits) # scalar: 0, 1, 2, or 3
# Check correctness
IF prediction == example["answer"]:
subject_correct += 1
END IF
END FOR
# Record subject accuracy
subject_scores[subject] β subject_correct / len(test_set) Γ 100
total_correct += subject_correct
total_questions += len(test_set)
PRINT f"{subject}: {subject_scores[subject]:.1f}%"
+ f" ({subject_correct}/{len(test_set)})"
END FOR
# Aggregate
micro_avg β total_correct / total_questions Γ 100
macro_avg β mean(subject_scores.values())
# Category averages
FOR each category IN [STEM, Humanities, Social Sciences, Other]:
cat_subjects β subjects belonging to category
cat_avg β mean([subject_scores[s] for s in cat_subjects])
PRINT f"{category}: {cat_avg:.1f}%"
END FOR
PRINT f"Overall (micro): {micro_avg:.1f}%"
PRINT f"Overall (macro): {macro_avg:.1f}%"
RETURN macro_avg, subject_scores
FUNCTION format_subject(subject_name):
# Convert "abstract_algebra" β "abstract algebra"
RETURN subject_name.replace("_", " ")
FUNCTION format_example(example, include_answer):
choices β ["A", "B", "C", "D"]
prompt β f"Q: {example['question']}\n"
FOR i, choice IN enumerate(example['choices']):
prompt += f"{choices[i]}. {choice}\n"
IF include_answer:
prompt += f"Answer: {choices[example['answer']]}\n\n"
RETURN prompt
Reference Implementation
Standalone Implementation
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
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from datasets import load_dataset
SUBJECTS = [
"abstract_algebra", "anatomy", "astronomy", "business_ethics",
"clinical_knowledge", "college_biology", "college_chemistry",
"college_computer_science", "college_mathematics", "college_medicine",
"college_physics", "computer_security", "conceptual_physics",
"econometrics", "electrical_engineering", "elementary_mathematics",
"formal_logic", "global_facts", "high_school_biology",
"high_school_chemistry", "high_school_computer_science",
"high_school_european_history", "high_school_geography",
"high_school_government_and_politics", "high_school_macroeconomics",
"high_school_mathematics", "high_school_microeconomics",
"high_school_physics", "high_school_psychology",
"high_school_statistics", "high_school_us_history",
"high_school_world_history", "human_aging", "human_sexuality",
"international_law", "jurisprudence", "logical_fallacies",
"machine_learning", "management", "marketing", "medical_genetics",
"miscellaneous", "moral_disputes", "moral_scenarios", "nutrition",
"philosophy", "prehistory", "professional_accounting",
"professional_law", "professional_medicine", "professional_psychology",
"public_relations", "security_studies", "sociology",
"us_foreign_policy", "virology", "world_religions",
]
CHOICES = ["A", "B", "C", "D"]
CATEGORIES = {
"STEM": [
"abstract_algebra", "anatomy", "astronomy", "college_biology",
"college_chemistry", "college_computer_science",
"college_mathematics", "college_physics", "computer_security",
"conceptual_physics", "electrical_engineering",
"elementary_mathematics", "high_school_biology",
"high_school_chemistry", "high_school_computer_science",
"high_school_mathematics", "high_school_physics",
"high_school_statistics", "machine_learning",
],
"Humanities": [
"formal_logic", "high_school_european_history",
"high_school_us_history", "high_school_world_history",
"international_law", "jurisprudence", "logical_fallacies",
"moral_disputes", "moral_scenarios", "philosophy", "prehistory",
"professional_law", "world_religions",
],
"Social Sciences": [
"econometrics", "high_school_geography",
"high_school_government_and_politics",
"high_school_macroeconomics", "high_school_microeconomics",
"high_school_psychology", "human_sexuality",
"professional_accounting", "professional_psychology",
"public_relations", "security_studies", "sociology",
"us_foreign_policy",
],
"Other": [
"business_ethics", "clinical_knowledge", "college_medicine",
"global_facts", "human_aging", "management", "marketing",
"medical_genetics", "miscellaneous", "nutrition",
"professional_medicine", "virology",
],
}
def format_subject(subject: str) -> str:
"""Convert 'abstract_algebra' to 'abstract algebra'."""
return subject.replace("_", " ")
def format_example(example: dict, include_answer: bool = True) -> str:
"""Format a single MMLU example as a string."""
prompt = f"Q: {example['question']}\n"
for i, choice in enumerate(example["choices"]):
prompt += f"{CHOICES[i]}. {choice}\n"
if include_answer:
prompt += f"Answer: {CHOICES[example['answer']]}\n\n"
return prompt
def build_few_shot_prompt(subject: str, dev_set, num_fewshot: int = 5) -> str:
"""Build the few-shot prefix for a given subject."""
header = (
f"The following are multiple choice questions (with answers) "
f"about {format_subject(subject)}.\n\n"
)
prompt = header
for i in range(min(num_fewshot, len(dev_set))):
prompt += format_example(dev_set[i], include_answer=True)
return prompt
def get_choice_token_ids(tokenizer) -> list[int]:
"""Get the token IDs for 'A', 'B', 'C', 'D'.
Handles tokenizers that produce ' A' (with leading space) vs 'A'.
"""
choice_ids = []
for letter in CHOICES:
# Try encoding just the letter
ids = tokenizer.encode(letter, add_special_tokens=False)
if len(ids) == 1:
choice_ids.append(ids[0])
else:
# Some tokenizers need the space-prefixed version
ids = tokenizer.encode(f" {letter}", add_special_tokens=False)
choice_ids.append(ids[-1])
return choice_ids
def evaluate_mmlu(
model_id: str,
device: str = "cuda",
dtype: torch.dtype = torch.bfloat16,
num_fewshot: int = 5,
) -> tuple[float, dict[str, float]]:
"""Evaluate a model on the full MMLU benchmark.
Args:
model_id: HuggingFace model identifier.
device: Device to run on ("cuda" or "cpu").
dtype: Model precision (torch.bfloat16, torch.float16, etc.).
num_fewshot: Number of few-shot examples (default: 5).
Returns:
Tuple of (overall_accuracy, per_subject_accuracy_dict).
"""
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
model_id, torch_dtype=dtype, device_map=device
)
model.eval()
choice_ids = get_choice_token_ids(tokenizer)
# choice_ids: list of 4 ints β token IDs for A, B, C, D
results: dict[str, float] = {}
total_correct = 0
total_questions = 0
for subject in SUBJECTS:
dev = load_dataset("cais/mmlu", subject, split="dev")
test = load_dataset("cais/mmlu", subject, split="test")
few_shot_prompt = build_few_shot_prompt(subject, dev, num_fewshot)
subject_correct = 0
for example in test:
# Build full prompt
prompt = few_shot_prompt + format_example(example, include_answer=False)
prompt += "Answer:"
# Tokenize
input_ids = tokenizer(
prompt, return_tensors="pt"
).input_ids.to(device)
# input_ids: (1, seq_len)
with torch.no_grad():
logits = model(input_ids).logits
# logits: (1, seq_len, vocab_size)
# Extract logits at the last position
last_logits = logits[0, -1, :]
# last_logits: (vocab_size,)
# Get logits for A, B, C, D
choice_logits = last_logits[choice_ids]
# choice_logits: (4,)
pred = choice_logits.argmax().item()
# pred: int in {0, 1, 2, 3}
if pred == example["answer"]:
subject_correct += 1
subject_acc = subject_correct / len(test) * 100
results[subject] = subject_acc
total_correct += subject_correct
total_questions += len(test)
print(f"{format_subject(subject):>40s}: "
f"{subject_acc:5.1f}% ({subject_correct}/{len(test)})")
# Overall scores
micro_avg = total_correct / total_questions * 100
macro_avg = sum(results.values()) / len(results)
# Category scores
for cat_name, cat_subjects in CATEGORIES.items():
cat_acc = sum(results[s] for s in cat_subjects) / len(cat_subjects)
print(f"\n{cat_name}: {cat_acc:.1f}%")
print(f"\nOverall (micro avg): {micro_avg:.1f}%")
print(f"Overall (macro avg): {macro_avg:.1f}%")
return macro_avg, results
Using lm-eval-harness (Recommended)
The easiest way to evaluate MMLU is via EleutherAIβs lm-eval-harness:
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
# Install
pip install lm-eval
# Run MMLU 5-shot evaluation on a local model
lm_eval --model hf \
--model_args pretrained=meta-llama/Meta-Llama-3-8B,dtype=bfloat16 \
--tasks mmlu \
--num_fewshot 5 \
--batch_size auto \
--output_path ./mmlu_results/
# Run on a specific subject
lm_eval --model hf \
--model_args pretrained=meta-llama/Meta-Llama-3-8B \
--tasks mmlu_abstract_algebra \
--num_fewshot 5
# Run 0-shot evaluation
lm_eval --model hf \
--model_args pretrained=meta-llama/Meta-Llama-3-8B \
--tasks mmlu \
--num_fewshot 0
# Run with VLLM backend for faster inference
lm_eval --model vllm \
--model_args pretrained=meta-llama/Meta-Llama-3-8B,dtype=bfloat16 \
--tasks mmlu \
--num_fewshot 5 \
--batch_size auto
Key Differences from lm-eval-harness
The standalone implementation above is simplified. The lm-eval-harness version includes:
- Batched inference β processes multiple prompts simultaneously for GPU efficiency
- Automatic prompt truncation β handles prompts that exceed the modelβs context window
- Proper token normalization β carefully handles space-prefixed tokens and BOS tokens
- Log-probability extraction β uses log-softmax rather than raw logits for numerical stability
- Caching β avoids redundant computation of the few-shot prefix across questions in the same subject
Caveats & Pitfalls
1. Prompt Format Sensitivity
Different prompt templates can swing results by 2β5%. The standard format is:
1
The following are multiple choice questions (with answers) about {subject}.
Variations like βAnswer the following question about {subject}β or omitting the subject name entirely can produce meaningfully different results. Always report the exact prompt template used.
2. Token ID Extraction
The tokens βAβ, βBβ, βCβ, βDβ may tokenize differently across tokenizers:
| Tokenizer | encode("A") |
encode(" A") |
Correct ID |
|---|---|---|---|
| LLaMA-2 | [319] |
[319] |
319 |
| LLaMA-3 | [32] |
[362, 32] |
32 |
| GPT-2 | [32] |
[317] |
Depends on context |
| Mistral | [330] |
[330] |
330 |
Some tokenizers produce " A" (with a leading space) as a single token, while others split it. The correct approach is to check both encode("A") and encode(" A") and use whichever produces a single token β or, more robustly, look at how the answer letter appears when the full prompt is tokenized.
3. Log-Likelihood vs. Generation
Base models are evaluated with log-likelihood (compare logits for A/B/C/D). Instruct models may perform better with generation (produce text, parse answer). These two methods can give different scores for the same model, so results are not directly comparable across methods.
4. Few-Shot Count
The number of few-shot examples significantly impacts performance:
| Few-Shot | Typical Impact |
|---|---|
| 0-shot | 5β15% lower than 5-shot |
| 1-shot | 2β8% lower than 5-shot |
| 5-shot | Standard (most reported) |
| 10-shot | Marginal improvement, may exceed context window |
Always report the few-shot count. βMMLU: 72%β is ambiguous without it.
5. Subject-Level Variance
Some subjects have as few as 100 questions (e.g., abstract algebra, global facts). With only 100 questions, a single correct/incorrect answer changes the subject accuracy by 1 percentage point. Individual subject scores can be noisy β always look at category averages and overall scores rather than single-subject results.
6. Data Contamination
MMLU questions have been publicly available since 2020. Models trained on web-scraped data may have inadvertently seen some questions during training, leading to inflated scores. Some mitigation strategies:
- Canary strings: Check for memorized answers
- Rephrased questions: Test with paraphrased versions
- MMLU-Pro: Uses newer, harder questions less likely to be contaminated
7. MMLU vs. MMLU-Pro
| Feature | MMLU | MMLU-Pro |
|---|---|---|
| Choices | 4 (AβD) | 10 (AβJ) |
| Random baseline | 25% | 10% |
| Question difficulty | Mixed | Harder |
| Question count | 14,042 | 12,032 |
| Preferred by | Legacy benchmarks | Open LLM Leaderboard v2 |
MMLU-Pro significantly reduces the guessing advantage and better discriminates between strong models.
8. Evaluation Speed
A rough guide to wall-clock time on a single A100 GPU:
| Model Size | Approx. Time | Notes |
|---|---|---|
| 1β3B | 15β30 min | Fast |
| 7β8B | 30β60 min | Standard |
| 13B | 45β90 min | Moderate |
| 70B | 3β6 hours | Slow; consider tensor parallelism |
| 405B | 12β24 hours | Multi-GPU required |
Each of the 14,042 questions requires tokenizing ~300β800 tokens and running a full forward pass. Batched inference (as in lm-eval-harness) can reduce time by 2β5Γ.
9. Chat Template
Instruct/chat models require proper chat template wrapping. Forgetting to apply the chat template β or applying the wrong one β can drop scores by 10β20%. For example:
1
2
3
4
5
6
# WRONG β raw prompt to an instruct model
prompt = "The following are multiple choice questions..."
# CORRECT β wrapped in chat template
messages = [{"role": "user", "content": "The following are multiple choice questions..."}]
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
10. Macro-Average vs. Micro-Average
There are two ways to compute the βoverallβ MMLU score:
- Micro-average:
total_correct / total_questionsβ treats all 14,042 questions equally regardless of subject - Macro-average:
mean(per_subject_accuracy)β averages the accuracy of each of the 57 subjects equally
These give different numbers because subjects have different numbers of questions. A subject with 1,000 questions has much more weight in micro-average but equal weight in macro-average.
| Method | Score Example | Used By |
|---|---|---|
| Micro-average | 72.4% | HuggingFace leaderboard, most papers |
| Macro-average | 73.1% | Some papers and frameworks |
Always clarify which averaging method was used. The original MMLU paper uses macro-average. lm-eval-harness defaults to macro-average for MMLU.
11. Answer Calibration / Normalization
Some evaluation frameworks normalize logits by the token length of each choice before comparing. For example:
1
2
3
4
5
# Unnormalized (most common):
score = logit["A"]
# Length-normalized (some frameworks):
score = logit["A"] / len(tokenizer.encode("A"))
For MMLU, where all choices are single letters (A, B, C, D), this makes no difference. But for benchmarks with free-text choices (e.g., βTrueβ vs βFalseβ vs βNone of the aboveβ), normalization matters significantly. Be aware of this distinction when comparing across frameworks.
12. Tied Logits
Occasionally, two or more choices may have nearly identical logits. Different frameworks handle ties differently:
- Random tiebreak: randomly choose among tied options β adds noise
- Lexicographic tiebreak: pick βAβ over βBβ over βCβ over βDβ β systematic bias
- First-occurrence tiebreak: pick the first tied option in the ordering
Ties are rare but can affect a few questions per run. This is another reason PPL-based scores may vary slightly between frameworks even with identical models.
13. Wrong Split for Dev Examples
The dev split (5 examples per subject, 285 total) contains the answers. Some implementations accidentally use the validation or test split for few-shot examples. Using test examples as few-shot demonstrations is data leakage β those questions will appear in the evaluation set, and the model effectively sees the answer. Always use only the dev split for few-shot examples.
Leaderboard Reference
Note: All scores below are approximate and based on publicly reported 5-shot results. Scores may vary by 1β3% depending on the evaluation framework and prompt format used.
Small Models (<10B parameters)
| Model | Params | MMLU (5-shot) | Notes |
|---|---|---|---|
| GPT-2 XL | 1.5B | ~26% | Near random baseline |
| Phi-2 | 2.7B | ~56% | Microsoft; punches above weight |
| Gemma-2-2B | 2.6B | ~52% | |
| LLaMA-2-7B | 7B | ~46% | Meta |
| Mistral-7B-v0.3 | 7.2B | ~63% | Mistral AI |
| LLaMA-3-8B | 8B | ~66% | Meta |
| Qwen-2.5-7B | 7B | ~74% | Alibaba; strong for size |
Medium Models (10Bβ50B parameters)
| Model | Params | MMLU (5-shot) | Notes |
|---|---|---|---|
| LLaMA-2-13B | 13B | ~55% | Meta |
| Mixtral-8x7B | 46.7B (12.9B active) | ~71% | Mixture of Experts |
| Mistral-Small-22B | 22B | ~77% | Mistral AI |
Large Models (50B+ parameters)
| Model | Params | MMLU (5-shot) | Notes |
|---|---|---|---|
| LLaMA-2-70B | 70B | ~69% | Meta |
| LLaMA-3-70B | 70B | ~79% | Meta |
| LLaMA-3.1-405B | 405B | ~88% | Meta; largest open model |
| GPT-4 | ~1.8T (est.) | ~86% | OpenAI |
| Claude 3.5 Sonnet | Unknown | ~89% | Anthropic |
Score Interpretation Guide
Parameters: Deep Dive
Every parameter in MMLU evaluation has a clear reason for existing and measurable effects on results. This section explains each one in depth.
num_fewshot (Number of Few-Shot Examples)
Why it exists: MMLU questions are standalone multiple-choice questions with no inherent context. Few-shot examples from the dev split (5 per subject, 285 total) serve as in-context demonstrations showing the model the expected format: question β choice listing β βAnswer: Xβ.
Values: 0 (zero-shot), 1, 2, 3, 5 (standard), 10, 25
num_fewshot |
Typical Accuracy (7B model) | Prompt Length | Use Case |
|---|---|---|---|
| 0 | ~48β58% | ~150 tokens | Testing pure memorization; very fast |
| 1 | ~52β60% | ~280 tokens | Minimal format demonstration |
| 5 | ~55β65% | ~500β700 tokens | Standard β widely reported |
| 10 | ~56β66% | ~900β1200 tokens | Diminishing returns |
Why 5-shot is standard: The dev split provides exactly 5 examples per subject. Using 5-shot ensures every subject has the same number of demonstrations. More than 5 requires examples from other splits, introducing variance.
Impact of 0-shot vs 5-shot: The gap is 5β15 percentage points for most models. This is mostly a formatting effect β the model needs to see the βAnswer: Xβ pattern to know it should output a single letter. Without demonstrations, some models output long explanations rather than a single letter.
Pitfall: Comparing a 0-shot result against a 5-shot result without noting this in your analysis is a common mistake that makes models appear weaker or stronger than they are. Always report the few-shot count.
prompt_format (Question Formatting Template)
Why it exists: There is no single canonical MMLU prompt β the original paper defined a format, but different frameworks implement subtle variations.
Standard format (from the original paper):
1
2
3
4
5
6
7
8
The following are multiple choice questions (with answers) about {subject}.
Question: {question}
A. {choice_A}
B. {choice_B}
C. {choice_C}
D. {choice_D}
Answer:
Common variations and their impact:
| Variation | Impact |
|---|---|
| Omitting subject name | β1 to β3% accuracy |
| βAnswer the followingβ¦β vs βThe following areβ¦β | Β±1β2% |
| Lettering: βA)β vs βA.β vs β(A)β | Β±0.5β1% (tokenizer-dependent) |
| Adding βPlease answer with a single letter.β | Β±1β2% for some models |
| Newlines between choices vs. inline | Β±0.5% |
Pitfall: If you use a different prompt format than the reference comparison, results can differ by 2β5%. The lm-eval-harness format is the de facto standard for reproducible comparisons. Check the exact format used before comparing results.
method (Log-Likelihood vs. Generation)
Why it exists: There are two fundamentally different ways to extract an answer from an LLM:
Log-Likelihood Method (base models):
- Run ONE forward pass over the full prompt
- Extract logits at the last token position (after βAnswer:β)
- Compare
logit["A"]vslogit["B"]vslogit["C"]vslogit["D"] - This is equivalent to the model βchoosingβ the most likely continuation
- Fast: single forward pass per question
Generation Method (instruct/chat models):
- Run autoregressive generation starting from βAnswer:β
- Parse the first generated token (or first letter in the output)
- Slower: multiple forward passes per question
- Can incorporate chain-of-thought: let the model reason before answering
Why they produce different results: The log-likelihood method measures the modelβs raw probability for continuation tokens. The generation method can produce better results for instruct models because:
- Instruct fine-tuning shifts the probability mass toward answering after βAnswer:β in chat context
- Chain-of-thought generation allows the model to βthinkβ before committing to an answer
Impact: For instruct models, generation can be 3β8% higher than log-likelihood. Results from different methods are NOT directly comparable.
| Method | Speed (7B, A100) | Best For | Notes |
|---|---|---|---|
| log-likelihood | ~40 min for 14K Q | Base models | Standard, reproducible |
| generate | ~2β4Γ slower | Instruct models | Requires answer parsing |
chat_template (Instruct Model Wrapping)
Why it exists: Instruction-tuned models are fine-tuned to respond in a specific dialogue format. Without the correct template, the model sees an unusual input distribution and may produce garbage or reduced-quality outputs.
Example β LLaMA-3 Instruct template:
1
2
3
4
5
6
7
# Without template (WRONG for instruct models):
prompt = "The following are multiple choice questions about physics...\nAnswer:"
# With template (CORRECT for instruct models):
messages = [{"role": "user", "content": "The following are multiple choice questions about physics...\nAnswer:"}]
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
# Produces: "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\nThe following...<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"
Impact: Wrong or missing chat template β 10β20% accuracy drop for instruct models. This is the single largest source of βmy model performs badly on MMLUβ reports.
Values:
None/ no template: for base (non-instruct) models- Model-specific template: apply via
tokenizer.apply_chat_template() - Manual templates: custom system prompts (use with caution β may not match training)
token_id_extraction (A/B/C/D Token IDs)
Why it exists: Different tokenizers encode the letters βAβ, βBβ, βCβ, βDβ as different token IDs. The log-likelihood method needs to know exactly which token IDs to compare.
Values depend on tokenizer:
| Tokenizer | encode("A") |
encode(" A") |
Recommended |
|---|---|---|---|
| LLaMA-2 | [319] |
[319] |
319 |
| LLaMA-3 | [32] |
[362] |
32 |
| GPT-2 | [32] |
[317] |
317 (with space) |
| Mistral | [330] |
[330] |
330 |
The βAnswer: β prefix means the letter appears after a space, so " A" is the correct context in most cases. The right approach is to check which single-token ID appears in the context of a fully tokenized prompt.
Pitfall: Using encode("A") without checking context may give you a different token ID than what actually appears after βAnswer: β. The lm-eval-harness handles this correctly β if youβre rolling your own, always verify with a full prompt tokenization.
subjects (Which Subjects to Evaluate)
Why it exists: MMLU has 57 subjects with varying difficulty and question counts. You may want to evaluate a subset for speed or targeted analysis.
Values: All 57 subjects (default), or any subset by category:
- STEM only: 16 subjects
- Humanities only: 13 subjects
- Social sciences only: 12 subjects
- Other (professional): 16 subjects
Impact on score: Evaluating only easy subjects inflates the overall score; evaluating only hard subjects deflates it. Subset results are not representative of the full benchmark.
Speed: Full evaluation (14,042 questions) takes 30β90 minutes for a 7B model. A single subject (~250 questions) takes ~2β5 minutes.
batch_size
Why it exists: Larger batches improve GPU utilization by processing multiple questions simultaneously.
Values: 1, 4, 8, 16, "auto" (lm-eval-harness auto-tunes)
| batch_size | Speed | Accuracy | Notes |
|---|---|---|---|
| 1 | Slowest | Exact | Reference |
| 4β8 | ~2β4Γ faster | Identical | Good balance |
| 16+ | ~4β8Γ faster | Identical | May OOM for large models |
| βautoβ | Optimal | Identical | Recommended in lm-eval |
Why it doesnβt affect accuracy: The log-likelihood method is deterministic and independent per question β there is no cross-question interaction. Different batch sizes give identical results (unlike generation-based evals where sampling is stochastic).
Note: Padding is needed when batching questions of different lengths. lm-eval-harness handles this correctly with a left-padding strategy (so the βAnswer:β position is always the last meaningful token).
dtype
Why it exists: Controls memory usage and compute speed by trading floating-point precision.
Values: float32, float16, bfloat16
Impact on MMLU: Minimal β typically <0.5% accuracy difference between float32 and bfloat16. MMLU is a discrete accuracy metric; small probability differences rarely change which option has the highest logit.
Recommendation: Use bfloat16 on Ampere/Hopper GPUs (A100, H100) for best speed/memory trade-off.
Example Configurations
Standard 5-shot evaluation (most common):
1
lm_eval --model hf --tasks mmlu --num_fewshot 5 --batch_size auto
0-shot evaluation (faster, tests memorization more):
1
lm_eval --model hf --tasks mmlu --num_fewshot 0 --batch_size auto
Instruct model with chat template:
1
2
3
4
lm_eval --model hf \
--model_args pretrained=meta-llama/Llama-3.1-8B-Instruct,apply_chat_template=True \
--tasks mmlu \
--num_fewshot 5
Single-subject deep dive:
1
lm_eval --model hf --tasks mmlu_professional_medicine --num_fewshot 5
Applicability
Complementary Benchmarks
MMLU is best used alongside other benchmarks for a complete picture:
| Skill | Benchmark | Complements MMLU by⦠|
|---|---|---|
| Math reasoning | GSM8K, MATH | Testing multi-step problem solving |
| Code generation | HumanEval, MBPP | Testing programming ability |
| Common-sense reasoning | HellaSwag, WinoGrande | Testing intuitive understanding |
| Truthfulness | TruthfulQA | Testing resistance to misconceptions |
| Instruction following | IFEval | Testing ability to follow instructions |
| Multimodal understanding | MMMU | MMLUβs visual counterpart |
Common Eval Sources
lm-eval-harness (EleutherAI)
The de facto standard for running MMLU evaluations:
1
2
3
4
5
6
7
8
9
10
11
# Full MMLU benchmark
lm_eval --model hf \
--model_args pretrained=<model_name> \
--tasks mmlu \
--num_fewshot 5
# Individual subject
lm_eval --model hf \
--model_args pretrained=<model_name> \
--tasks mmlu_abstract_algebra \
--num_fewshot 5
Task names follow the pattern mmlu_{subject} where subject uses underscores (e.g., mmlu_high_school_physics).
HuggingFace Datasets
1
2
3
4
5
6
7
from datasets import load_dataset
# Load a specific subject
ds = load_dataset("cais/mmlu", "abstract_algebra")
# Available splits: "dev", "validation", "test"
# Each example has: "question", "choices" (list of 4), "answer" (int 0-3)
The cais/mmlu dataset on HuggingFace Hub is the canonical version maintained by the Center for AI Safety.
Open LLM Leaderboard v2
The Open LLM Leaderboard v2 has replaced MMLU with MMLU-Pro as its knowledge benchmark. Older v1 scores used original MMLU.
HELM (Stanford)
Stanfordβs HELM benchmark suite includes MMLU as one of its core evaluations, with standardized prompt formatting and reporting.
Links & References
Papers
- Measuring Massive Multitask Language Understanding β Hendrycks et al., 2020 (ICLR 2021). The original MMLU paper.
- MMLU-Pro: A More Robust and Challenging Multi-Task Language Understanding Benchmark β Wang et al., 2024. The 10-choice successor.
Dataset
- MMLU on HuggingFace β canonical dataset hosted by the Center for AI Safety.
Evaluation Frameworks
- lm-eval-harness β EleutherAIβs evaluation framework; the standard tool for MMLU evaluation.
- HELM β Stanfordβs Holistic Evaluation of Language Models.
Leaderboards
- Open LLM Leaderboard β HuggingFace community leaderboard (v2 uses MMLU-Pro).
- Chatbot Arena β LMSYS crowdsourced model rankings (complements MMLU with human preference data).
β Previous: 01 β Wikitext Perplexity Β· Next: 03 β MMMU β
Last updated: April 2026