Coverage for transformer_lens/evals.py: 85%

227 statements  

« prev     ^ index     » next       coverage.py v7.10.1, created at 2026-11-25 00:28 +0000

1"""Evaluation Helpers. 

2 

3This module contains some rough evals for models, but you are likely better off using the 

4HuggingFace evaluate library if you want to do anything properly. This is however here if you want 

5it and want to eg cheaply and roughly compare models you've trained to baselines. 

6""" 

7 

8import random 

9from typing import Any, Dict, Iterable, List, Optional, Union 

10 

11import einops 

12import torch 

13import tqdm.auto as tqdm 

14from datasets import load_dataset 

15from torch.utils.data import DataLoader, Dataset 

16 

17from transformer_lens import utilities as utils 

18from transformer_lens.utilities import warn_if_mps 

19 

20 

21# %% 

22def sanity_check(model): 

23 """ 

24 Very basic eval - just feeds a string into the model (in this case, the first paragraph of Circuits: Zoom In), and returns the loss. It's a rough and quick sanity check - if the loss is <5 the model is probably OK, if the loss is >7 something's gone wrong. 

25 

26 Note that this is a very basic eval, and doesn't really tell you much about the model's performance. 

27 """ 

28 

29 text = "Many important transition points in the history of science have been moments when science 'zoomed in.' At these points, we develop a visualization or tool that allows us to see the world in a new level of detail, and a new field of science develops to study the world through this lens." 

30 

31 return model(text, return_type="loss") 

32 

33 

34# %% 

35def make_wiki_data_loader(tokenizer, batch_size=8): 

36 """ 

37 Evaluate on Wikitext 2, a dump of Wikipedia articles. (Using the train set because it's larger, I don't really expect anyone to bother with quarantining the validation set nowadays.) 

38 

39 Note there's likely to be dataset leakage into training data (though I believe GPT-2 was explicitly trained on non-Wikipedia data) 

40 """ 

41 wiki_data = load_dataset("wikitext", "wikitext-2-v1", split="train") 

42 print(len(wiki_data)) 

43 dataset = utils.tokenize_and_concatenate(wiki_data, tokenizer) 

44 data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, drop_last=True) 

45 return data_loader 

46 

47 

48def make_owt_data_loader(tokenizer, batch_size=8): 

49 """ 

50 Evaluate on OpenWebText an open source replication of the GPT-2 training corpus (Reddit links with >3 karma) 

51 

52 I think the Mistral models were trained on this dataset, so they get very good performance. 

53 """ 

54 owt_data = load_dataset("stas/openwebtext-10k", split="train") 

55 print(len(owt_data)) 

56 dataset = utils.tokenize_and_concatenate(owt_data, tokenizer) 

57 data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, drop_last=True) 

58 return data_loader 

59 

60 

61def make_pile_data_loader(tokenizer, batch_size=8): 

62 """ 

63 Evaluate on the first 10k texts from The Pile. 

64 

65 The Pile is EleutherAI's general-purpose english dataset, made of 22 subsets 

66 including academic papers, books, internet content... 

67 """ 

68 pile_data = load_dataset("NeelNanda/pile-10k", split="train") 

69 print(len(pile_data)) 

70 dataset = utils.tokenize_and_concatenate(pile_data, tokenizer) 

71 data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, drop_last=True) 

72 return data_loader 

73 

74 

75def make_code_data_loader(tokenizer, batch_size=8): 

76 """ 

77 Evaluate on the CodeParrot dataset, a dump of Python code. 

78 

79 All models seem to get significantly lower loss here (even non-code trained models like GPT-2), 

80 presumably code is much easier to predict than natural language? 

81 """ 

82 code_data = load_dataset("codeparrot/codeparrot-valid-v2-near-dedup", split="train") 

83 print(len(code_data)) 

84 dataset = utils.tokenize_and_concatenate(code_data, tokenizer, column_name="content") 

85 data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, drop_last=True) 

86 return data_loader 

87 

88 

89# All 57 subjects available in the MMLU benchmark 

90MMLU_SUBJECTS = [ 

91 "abstract_algebra", 

92 "anatomy", 

93 "astronomy", 

94 "business_ethics", 

95 "clinical_knowledge", 

96 "college_biology", 

97 "college_chemistry", 

98 "college_computer_science", 

99 "college_mathematics", 

100 "college_medicine", 

101 "college_physics", 

102 "computer_security", 

103 "conceptual_physics", 

104 "econometrics", 

105 "electrical_engineering", 

106 "elementary_mathematics", 

107 "formal_logic", 

108 "global_facts", 

109 "high_school_biology", 

110 "high_school_chemistry", 

111 "high_school_computer_science", 

112 "high_school_european_history", 

113 "high_school_geography", 

114 "high_school_government_and_politics", 

115 "high_school_macroeconomics", 

116 "high_school_mathematics", 

117 "high_school_microeconomics", 

118 "high_school_physics", 

119 "high_school_psychology", 

120 "high_school_statistics", 

121 "high_school_us_history", 

122 "high_school_world_history", 

123 "human_aging", 

124 "human_sexuality", 

125 "international_law", 

126 "jurisprudence", 

127 "logical_fallacies", 

128 "machine_learning", 

129 "management", 

130 "marketing", 

131 "medical_genetics", 

132 "miscellaneous", 

133 "moral_disputes", 

134 "moral_scenarios", 

135 "nutrition", 

136 "philosophy", 

137 "prehistory", 

138 "professional_accounting", 

139 "professional_law", 

140 "professional_medicine", 

141 "professional_psychology", 

142 "public_relations", 

143 "security_studies", 

144 "sociology", 

145 "us_foreign_policy", 

146 "virology", 

147 "world_religions", 

148] 

149 

150MMLU_ANSWER_LETTERS = ["A", "B", "C", "D"] 

151 

152 

153def make_mmlu_data_loader( 

154 subjects: Optional[Union[str, List[str]]] = None, 

155 split: str = "test", 

156 num_samples: Optional[int] = None, 

157): 

158 """ 

159 Load MMLU (Massive Multitask Language Understanding) dataset. 

160 

161 MMLU tests model performance on 57 subjects across STEM, humanities, social sciences, 

162 and more. Each question is multiple choice with 4 options (A, B, C, D). 

163 

164 Paper: https://arxiv.org/abs/2009.03300 

165 Dataset: https://huggingface.co/datasets/cais/mmlu 

166 

167 Args: 

168 subjects: Subject(s) to evaluate on. Can be: 

169 - None: Use all 57 subjects (default) 

170 - str: Single subject name (e.g., "abstract_algebra") 

171 - List[str]: Multiple subjects 

172 split: Which split to use - "test", "validation", or "dev". Default is "test". 

173 num_samples: Optional limit on number of samples per subject. If None, uses all samples. 

174 

175 Returns: 

176 List of dictionaries with MMLU examples, each containing: 

177 - "question": str 

178 - "choices": List[str] (4 choices) 

179 - "answer": int (0-3, correct choice index) 

180 - "subject": str 

181 

182 Examples: 

183 

184 .. code-block:: python 

185 

186 >>> from transformer_lens.evals import make_mmlu_data_loader 

187 

188 >>> # Load specific subject 

189 >>> mmlu_data = make_mmlu_data_loader(subjects="college_mathematics") # doctest: +SKIP 

190 

191 >>> # Load multiple subjects 

192 >>> mmlu_data = make_mmlu_data_loader( # doctest: +SKIP 

193 ... subjects=["abstract_algebra", "astronomy", "college_chemistry"] 

194 ... ) 

195 """ 

196 # Handle subjects parameter 

197 if subjects is None: 197 ↛ 198line 197 didn't jump to line 198 because the condition on line 197 was never true

198 subjects_to_load = MMLU_SUBJECTS 

199 elif isinstance(subjects, str): 

200 subjects_to_load = [subjects] 

201 else: 

202 subjects_to_load = list(subjects) 

203 

204 # Validate subjects 

205 invalid_subjects = set(subjects_to_load) - set(MMLU_SUBJECTS) 

206 if invalid_subjects: 

207 raise ValueError( 

208 f"Invalid subject(s): {invalid_subjects}. " 

209 f"Valid subjects: {', '.join(sorted(MMLU_SUBJECTS))}" 

210 ) 

211 

212 # Load data for each subject 

213 mmlu_data = [] 

214 for subject in subjects_to_load: 

215 try: 

216 # Load dataset for this subject 

217 dataset = load_dataset("cais/mmlu", subject, split=split) 

218 

219 # Limit samples if requested 

220 samples_to_take = ( 

221 len(dataset) if num_samples is None else min(num_samples, len(dataset)) 

222 ) 

223 

224 # Convert to our format 

225 for i in range(samples_to_take): 

226 example = dataset[i] 

227 mmlu_data.append( 

228 { 

229 "question": example["question"], 

230 "choices": example["choices"], 

231 "answer": example["answer"], 

232 "subject": subject, 

233 } 

234 ) 

235 except Exception as e: 

236 print(f"Warning: Could not load subject '{subject}': {e}") 

237 continue 

238 

239 print(f"Loaded {len(mmlu_data)} MMLU examples from {len(subjects_to_load)} subject(s)") 

240 return mmlu_data 

241 

242 

243DATASET_NAMES = ["wiki", "owt", "pile", "code"] 

244DATASET_LOADERS = [ 

245 make_wiki_data_loader, 

246 make_owt_data_loader, 

247 make_pile_data_loader, 

248 make_code_data_loader, 

249] 

250 

251 

252# %% 

253@torch.inference_mode() 

254def evaluate_on_dataset( 

255 model: Any, 

256 data_loader: Iterable[Dict[str, torch.Tensor]], 

257 truncate: int = 100, 

258 device: Optional[Union[str, torch.device]] = None, 

259) -> float: 

260 # Default to the model's device; a hardcoded "cuda" crashes CPU/MPS callers. 

261 if device is None: 

262 device = model.cfg.device 

263 warn_if_mps(device) 

264 running_loss = 0 

265 total = 0 

266 for batch in tqdm.tqdm(data_loader): 266 ↛ 272line 266 didn't jump to line 272 because the loop on line 266 didn't complete

267 loss = model(batch["tokens"].to(device), return_type="loss").mean() 

268 running_loss += loss.item() 

269 total += 1 

270 if total > truncate: 

271 break 

272 return running_loss / total 

273 

274 

275# %% 

276@torch.inference_mode() 

277def induction_loss( 

278 model: Any, 

279 tokenizer: Any = None, 

280 batch_size: int = 4, 

281 subseq_len: int = 384, 

282 prepend_bos: Optional[bool] = None, 

283 device: Optional[Union[str, torch.device]] = None, 

284) -> torch.Tensor: 

285 """ 

286 Generates a batch of random sequences repeated twice, and measures model performance on the second half. Tests whether a model has induction heads. 

287 

288 By default, prepends a beginning of string token (when prepend_bos flag defaults to None, model.cfg.default_prepend_bos is used 

289 whose default is True unless specified otherwise), which is useful to give models a resting position, and sometimes models were trained with this. 

290 

291 Runs on the model's own device unless `device` says otherwise. 

292 """ 

293 if device is None: 

294 device = model.cfg.device 

295 warn_if_mps(device) 

296 # Make the repeated sequence 

297 first_half_tokens = torch.randint(100, 20000, (batch_size, subseq_len)).to(device) 

298 repeated_tokens = einops.repeat(first_half_tokens, "b p -> b (2 p)") 

299 

300 # Use the provided prepend_bos as an override if it's not None; 

301 # otherwise use model.cfg.default_prepend_bos (defaults to True) 

302 prepend_bos = utils.override_or_use_default_value( 

303 model.cfg.default_prepend_bos, override=prepend_bos 

304 ) 

305 

306 # Prepend a Beginning Of String token 

307 if prepend_bos: 307 ↛ 308line 307 didn't jump to line 308 because the condition on line 307 was never true

308 if tokenizer is None: 

309 tokenizer = model.tokenizer 

310 repeated_tokens[:, 0] = tokenizer.bos_token_id 

311 # Run the model, and extract the per token correct log prob 

312 logits = model(repeated_tokens, return_type="logits") 

313 correct_log_probs = utils.lm_cross_entropy_loss(logits, repeated_tokens, per_token=True) 

314 # Take the loss over the second half of the sequence 

315 return correct_log_probs[:, subseq_len + 1 :].mean() 

316 

317 

318# %% 

319@torch.inference_mode() 

320def evaluate( 

321 model: Any, 

322 truncate: int = 100, 

323 batch_size: int = 8, 

324 tokenizer: Any = None, 

325 device: Optional[Union[str, torch.device]] = None, 

326) -> Dict[str, float]: 

327 if tokenizer is None: 327 ↛ 328line 327 didn't jump to line 328 because the condition on line 327 was never true

328 tokenizer = model.tokenizer 

329 losses: Dict[str, float] = {} 

330 for data_name, data_loader_fn in zip(DATASET_NAMES, DATASET_LOADERS): 

331 data_loader = data_loader_fn(tokenizer=tokenizer, batch_size=batch_size) 

332 loss = evaluate_on_dataset(model, data_loader, truncate=truncate, device=device) 

333 print(f"{data_name}: {loss}") 

334 losses[f"{data_name}_loss"] = loss 

335 return losses 

336 

337 

338# %% 

339class IOIDataset(Dataset): 

340 """ 

341 Dataset for Indirect Object Identification tasks. 

342 Paper: https://arxiv.org/pdf/2211.00593.pdf 

343 

344 Example: 

345 

346 .. code-block:: python 

347 

348 >>> from transformer_lens.evals import ioi_eval, IOIDataset 

349 >>> from transformer_lens.model_bridge import TransformerBridge 

350 

351 >>> model = TransformerBridge.boot_transformers("gpt2", device="cpu") 

352 >>> model.enable_compatibility_mode() 

353 

354 >>> # Evaluate on a deterministic dataset (seed makes results reproducible) 

355 >>> ds = IOIDataset(tokenizer=model.tokenizer, num_samples=100, seed=42) 

356 >>> result = ioi_eval(model, dataset=ds)["Logit Difference"] 

357 >>> 2.0 < result < 7.0 # Logit difference should be in a reasonable range 

358 True 

359 

360 >>> # Can use custom dataset 

361 >>> ds = IOIDataset( 

362 ... tokenizer=model.tokenizer, 

363 ... num_samples=100, 

364 ... templates=['[A] met with [B]. [B] gave the [OBJECT] to [A]'], 

365 ... names=['Alice', 'Bob', 'Charlie'], 

366 ... nouns={'OBJECT': ['ball', 'book']}, 

367 ... seed=42, 

368 ... ) 

369 >>> result_custom = ioi_eval(model, dataset=ds)["Logit Difference"] 

370 >>> 2.0 < result_custom < 7.0 # Custom dataset logit difference should be positive 

371 True 

372 """ 

373 

374 def __init__( 

375 self, 

376 tokenizer, 

377 templates: Optional[List[str]] = None, 

378 names: Optional[List[str]] = None, 

379 nouns: Optional[Dict[str, List[str]]] = None, 

380 num_samples: int = 1000, 

381 symmetric: bool = False, 

382 prepend_bos: bool = True, 

383 seed: Optional[int] = None, 

384 ): 

385 """ 

386 Args: 

387 tokenizer: Tokenizer to use for encoding prompts. 

388 templates: List of template strings. Defaults to built-in IOI templates. 

389 names: List of names to sample from. Defaults to ["John", "Mary"]. 

390 nouns: Dict mapping placeholder names to lists of nouns. Defaults to built-in nouns. 

391 num_samples: Number of samples to generate. 

392 symmetric: If True, generate both orderings of each name pair. 

393 prepend_bos: If True, prepend one BOS token to each prompt. Tokenizer-added special 

394 tokens are disabled, so False leaves the prompt without a BOS. 

395 seed: Optional random seed for reproducibility. If None, the current 

396 random state is used (samples will vary across runs). 

397 """ 

398 self.tokenizer = tokenizer 

399 self.prepend_bos = prepend_bos 

400 

401 if seed is not None: 

402 random.seed(seed) 

403 

404 self.templates = templates if templates is not None else self.get_default_templates() 

405 self.names = names if names is not None else self.get_default_names() 

406 self.nouns = nouns if nouns is not None else self.get_default_nouns() 

407 

408 self.samples = [] 

409 for _ in range(num_samples // 2 if symmetric else num_samples): 

410 # If symmetric, get_sample will return two samples 

411 self.samples.extend(self.get_sample(symmetric=symmetric)) 

412 

413 def __len__(self): 

414 return len(self.samples) 

415 

416 def __getitem__(self, idx): 

417 sample = self.samples[idx] 

418 prompt = self.tokenizer.encode(sample["text"], add_special_tokens=False) 

419 if self.prepend_bos: 

420 prompt = [self.tokenizer.bos_token_id] + prompt 

421 

422 return { 

423 "prompt": torch.LongTensor(prompt), 

424 "IO": torch.LongTensor(self.tokenizer.encode(sample["IO"], add_special_tokens=False)), 

425 "S": torch.LongTensor(self.tokenizer.encode(sample["S"], add_special_tokens=False)), 

426 } 

427 

428 def get_sample(self, symmetric=False) -> List[Dict[str, str]]: 

429 template: str = random.choice(self.templates) 

430 for noun_type, noun_list in self.nouns.items(): 

431 template = template.replace(f"[{noun_type}]", random.choice(noun_list)) 

432 

433 samples: List[Dict[str, str]] = [] 

434 

435 # Sample two names without replacement 

436 names = random.sample(self.names, 2) 

437 sample = template.replace("[A]", names[0]) 

438 sample = sample.replace("[B]", names[1]) 

439 # Prepend spaces to IO and S so that the target is e.g. " Mary" and not "Mary" 

440 samples.append({"text": sample, "IO": " " + names[0], "S": " " + names[1]}) 

441 

442 if symmetric: 

443 sample_2 = template.replace("[A]", names[1]) 

444 sample_2 = sample_2.replace("[B]", names[0]) 

445 samples.append({"text": sample_2, "IO": " " + names[1], "S": " " + names[0]}) 

446 

447 return samples 

448 

449 @staticmethod 

450 def get_default_names(): 

451 return ["John", "Mary"] 

452 

453 @staticmethod 

454 def get_default_templates(): 

455 return [ 

456 "[A] and [B] went to the [LOCATION] to buy [OBJECT]. [B] handed the [OBJECT] to [A]", 

457 "Then, [B] and [A] went to the [LOCATION]. [B] gave the [OBJECT] to [A]", 

458 ] 

459 

460 @staticmethod 

461 def get_default_nouns(): 

462 return { 

463 "LOCATION": ["store", "market"], 

464 "OBJECT": ["milk", "eggs", "bread"], 

465 } 

466 

467 

468@torch.inference_mode() 

469def ioi_eval(model, dataset=None, batch_size=8, num_samples=1000, tokenizer=None, symmetric=False): 

470 """Evaluate the Model on the Indirect Object Identification Task. 

471 

472 Args: 

473 model: A TransformerBridge model. 

474 dataset: PyTorch Dataset that returns a dict with keys "prompt", "IO", and "S". 

475 batch_size: Batch size to use. 

476 num_samples: Number of samples to use. 

477 tokenizer: Tokenizer to use. 

478 symmetric: Whether to use the symmetric version of the task. 

479 

480 Returns: 

481 Average logit difference and accuracy. 

482 """ 

483 if tokenizer is None: 

484 tokenizer = model.tokenizer 

485 

486 if dataset is None: 486 ↛ 489line 486 didn't jump to line 489 because the condition on line 486 was always true

487 dataset = IOIDataset(tokenizer, num_samples=num_samples, symmetric=symmetric) 

488 

489 def collate(samples): 

490 prompts = [sample["prompt"] for sample in samples] 

491 padded_prompts = torch.nn.utils.rnn.pad_sequence(prompts, batch_first=True) 

492 return { 

493 "prompt": padded_prompts, 

494 "IO": [sample["IO"] for sample in samples], 

495 "S": [sample["S"] for sample in samples], 

496 "prompt_length": [p.shape[0] for p in prompts], 

497 } 

498 

499 data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, collate_fn=collate) 

500 

501 total_correct = 0 

502 total_logit_diff = 0 

503 for batch in tqdm.tqdm(data_loader): 

504 batch_logits = model(batch["prompt"], return_type="logits") 

505 

506 for i in range(batch_logits.shape[0]): 

507 io = batch["IO"][i] 

508 s = batch["S"][i] 

509 prefix_length = batch["prompt_length"][i] - io.shape[0] 

510 

511 # Trim io and s to the same length 

512 min_len = min(io.shape[0], s.shape[0]) 

513 io = io[:min_len] 

514 s = s[:min_len] 

515 

516 # Remove identical prefixes 

517 start_idx = torch.where(io != s)[0][0] 

518 io = io[start_idx] 

519 s = s[start_idx] 

520 logit_idx = prefix_length + start_idx - 1 

521 

522 # Get the logits for the tokens we care about 

523 logits = batch_logits[i, logit_idx] 

524 correct_logit = logits[io] 

525 incorrect_logit = logits[s] 

526 

527 # Compute stats 

528 logit_diff = correct_logit - incorrect_logit 

529 correct = logit_diff > 0 

530 total_correct += correct.item() 

531 total_logit_diff += logit_diff.item() 

532 

533 return { 

534 "Logit Difference": total_logit_diff / len(dataset), 

535 "Accuracy": total_correct / len(dataset), 

536 } 

537 

538 

539@torch.inference_mode() 

540def mmlu_eval( 

541 model, 

542 tokenizer=None, 

543 subjects: Optional[Union[str, List[str]]] = None, 

544 split: str = "test", 

545 num_samples: Optional[int] = None, 

546): 

547 """Evaluate a model on the MMLU benchmark. 

548 

549 MMLU (Massive Multitask Language Understanding) is a benchmark for evaluating language models 

550 on 57 subjects across STEM, humanities, social sciences, and more. Each question is 

551 multiple-choice with 4 options. 

552 

553 For each question, all four answer choices (A-D) are shown in the prompt and the model's 

554 log probability for each answer letter token is compared. This is a zero-shot evaluation; 

555 standard MMLU benchmarks typically use 5-shot prompting for higher accuracy. 

556 

557 Paper: https://arxiv.org/abs/2009.03300 

558 

559 Args: 

560 model: A TransformerBridge model to evaluate. 

561 tokenizer: Tokenizer to use. If None, uses model.tokenizer. 

562 subjects: Subject(s) to evaluate on. Can be None (all 57 subjects), a single subject 

563 string, or a list of subjects. See :const:`MMLU_SUBJECTS` for valid names. 

564 split: Which split to use - "test", "validation", or "dev". Default is "test". 

565 num_samples: Optional limit on number of samples per subject. If None, uses all samples. 

566 

567 Returns: 

568 Dictionary containing: 

569 - "accuracy": Overall accuracy (0-1) 

570 - "num_correct": Number of correct predictions 

571 - "num_total": Total number of questions 

572 - "subject_scores": Dict mapping subject names to their accuracy 

573 

574 Examples: 

575 

576 .. code-block:: python 

577 

578 >>> from transformer_lens.model_bridge import TransformerBridge 

579 >>> from transformer_lens.evals import mmlu_eval 

580 

581 >>> model = TransformerBridge.boot_transformers("gpt2") # doctest: +SKIP 

582 >>> model.enable_compatibility_mode() # doctest: +SKIP 

583 >>> results = mmlu_eval(model, subjects="abstract_algebra", num_samples=10) # doctest: +SKIP 

584 >>> print(f"Accuracy: {results['accuracy']:.2%}") # doctest: +SKIP 

585 """ 

586 if tokenizer is None: 586 ↛ 590line 586 didn't jump to line 590 because the condition on line 586 was always true

587 tokenizer = model.tokenizer 

588 

589 # Load MMLU data 

590 mmlu_data = make_mmlu_data_loader(subjects=subjects, split=split, num_samples=num_samples) 

591 

592 if len(mmlu_data) == 0: 592 ↛ 593line 592 didn't jump to line 593 because the condition on line 592 was never true

593 raise ValueError("No MMLU data loaded. Check your subjects parameter.") 

594 

595 # Precompute token IDs for answer letters A, B, C, D 

596 # Done once here instead of per-question for efficiency 

597 answer_letter_token_ids = [] 

598 for letter in MMLU_ANSWER_LETTERS: 

599 # Try with space prefix first (how it appears after "Answer:") 

600 token_ids = tokenizer.encode(" " + letter, add_special_tokens=False) 

601 if len(token_ids) == 1: 601 ↛ 605line 601 didn't jump to line 605 because the condition on line 601 was always true

602 answer_letter_token_ids.append(token_ids[0]) 

603 else: 

604 # Fallback to without space 

605 token_ids = tokenizer.encode(letter, add_special_tokens=False) 

606 answer_letter_token_ids.append(token_ids[0]) 

607 

608 # Track results 

609 num_correct = 0 

610 num_total = 0 

611 subject_correct: Dict[str, int] = {} 

612 subject_total: Dict[str, int] = {} 

613 

614 # Process examples 

615 for example in tqdm.tqdm(mmlu_data, desc="Evaluating MMLU"): 

616 question = example["question"] 

617 choices = example["choices"] 

618 correct_answer = example["answer"] 

619 subject = example["subject"] 

620 

621 # Initialize subject tracking 

622 if subject not in subject_correct: 

623 subject_correct[subject] = 0 

624 subject_total[subject] = 0 

625 

626 # Format prompt with all choices shown (standard MMLU format) 

627 prompt = f"Question: {question}\n" 

628 prompt += "Choices:\n" 

629 for idx, choice_text in enumerate(choices): 

630 letter = chr(65 + idx) # A, B, C, D 

631 prompt += f"{letter}. {choice_text}\n" 

632 prompt += "Answer:" 

633 

634 # Tokenize the prompt 

635 tokens = tokenizer.encode(prompt, return_tensors="pt").to(model.cfg.device) 

636 

637 logits = model(tokens, return_type="logits") 

638 

639 # Get log probabilities at the last position (predicting the answer letter) 

640 last_log_probs = torch.nn.functional.log_softmax(logits[0, -1, :], dim=-1) 

641 

642 # Score each answer choice by its letter token probability 

643 choice_log_probs = [] 

644 for idx in range(len(choices)): 

645 token_id = answer_letter_token_ids[idx] 

646 choice_log_probs.append(last_log_probs[token_id].item()) 

647 

648 # Select the choice with highest log probability 

649 predicted_answer = choice_log_probs.index(max(choice_log_probs)) 

650 

651 is_correct = predicted_answer == correct_answer 

652 num_correct += int(is_correct) 

653 num_total += 1 

654 subject_correct[subject] += int(is_correct) 

655 subject_total[subject] += 1 

656 

657 # Compute accuracies 

658 overall_accuracy = num_correct / num_total if num_total > 0 else 0.0 

659 subject_scores = { 

660 subject: subject_correct[subject] / subject_total[subject] 

661 for subject in subject_correct.keys() 

662 } 

663 

664 return { 

665 "accuracy": overall_accuracy, 

666 "num_correct": num_correct, 

667 "num_total": num_total, 

668 "subject_scores": subject_scores, 

669 }