← Back to Table of Contents

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.
MMLU at a Glance
Dataset
14,042 multiple-choice questions across 57 subjects from elementary to professional level (Hendrycks et al., 2020)
Metric
Accuracy (%) β€” fraction of questions answered correctly. Higher is better ↑
Evaluation Protocol
5-shot prompting with log-likelihood scoring over tokens A, B, C, D
Typical Scores
Random: 25% Β· GPT-2: ~26% Β· LLaMA-3-8B: ~66% Β· GPT-4: ~86% Β· Claude 3.5 Sonnet: ~89%
MMLU Category Breakdown (57 Subjects)
STEM (17 subjects)
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 (13 subjects)
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 (12 subjects)
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 (15 subjects)
Business ethics, clinical knowledge, college medicine, global facts, human aging, management, marketing, medical genetics, miscellaneous, nutrition, professional medicine, virology

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** (most common for base models) 1. Construct the full prompt: 5-shot examples + test question + "Answer:" 2. Run a single forward pass through the model 3. Look at the **logits at the last token position** (the position right after "Answer:") 4. Extract logits for token IDs corresponding to "A", "B", "C", "D" 5. Select the choice with the **highest logit** $$ \hat{y} = \underset{c \in \{A, B, C, D\}}{\text{argmax}} \; z_{\text{last}}[c] $$ where $z_{\text{last}} \in \mathbb{R}^{|V|}$ is the logit vector at the last token position. **Advantages**: Deterministic, fast (single forward pass), no generation overhead.
**Generation Method** (for instruct/chat models) 1. Construct the prompt (often wrapped in a chat template) 2. Generate a response using the model's generate function 3. Parse the generated text to extract the answer letter (A, B, C, or D) 4. Handle edge cases: model outputs "The answer is B" or just "B" $$ \hat{y} = \text{parse}\!\big(\text{generate}(\text{prompt})\big) $$ **Advantages**: Natural for instruct models, can capture chain-of-thought reasoning. **Disadvantages**: Slower (multiple forward passes per question), parsing failures, non-deterministic with sampling.

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

MMLU 5-Shot Prompt Construction and Answer Extraction 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

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:

  1. Batched inference β€” processes multiple prompts simultaneously for GPU efficiency
  2. Automatic prompt truncation β€” handles prompts that exceed the model’s context window
  3. Proper token normalization β€” carefully handles space-prefixed tokens and BOS tokens
  4. Log-probability extraction β€” uses log-softmax rather than raw logits for numerical stability
  5. 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% Google
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

MMLU Score Ranges
25–40%
Near random. Model has minimal knowledge. Typical for very small models (<1B) or poorly trained models.
40–60%
Below average. Some knowledge but significant gaps. Typical for 3–7B base models.
60–75%
Solid performance. Good general knowledge. Typical for well-trained 7–13B models.
75–85%
Strong. Expert-level on many subjects. Typical for 30–70B models or top small models.
85–90%
Excellent. Near human expert. Typical for frontier models (GPT-4, Claude 3.5, LLaMA-3.1-405B).
90%+
State of the art. Exceeds average human expert performance on many subjects. Only the best frontier models.

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"] vs logit["B"] vs logit["C"] vs logit["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:

  1. Instruct fine-tuning shifts the probability mass toward answering after β€œAnswer:” in chat context
  2. 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

### βœ… When to Use MMLU - **Broad knowledge assessment** β€” quickly gauge how much a model "knows" across 57 diverse fields - **Model comparison** β€” compare models on a standardized benchmark with well-established baselines - **Pre-training evaluation** β€” track knowledge acquisition during training - **Scaling law analysis** β€” study how accuracy improves with model size and data - **Regression testing** β€” ensure a fine-tuned model hasn't lost general knowledge
### ❌ When NOT to Use MMLU - **Measuring reasoning depth** β€” MMLU tests knowledge recall more than multi-step reasoning (use GSM8K, MATH, or ARC-Challenge instead) - **Evaluating chat quality** β€” MMLU doesn't measure conversation ability (use Chatbot Arena, MT-Bench) - **Domain-specific assessment** β€” for specialized domains, use domain-specific benchmarks (e.g., MedQA for medicine, LegalBench for law) - **Instruction following** β€” MMLU doesn't test whether a model can follow complex instructions (use IFEval) - **Safety evaluation** β€” MMLU doesn't measure harmful outputs (use TruthfulQA, BBQ, or custom red-teaming)

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.


Papers

Dataset

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