Coverage for transformer_lens/benchmarks/utils.py: 63%

199 statements  

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

1"""Utility types and functions for benchmarking.""" 

2 

3from contextlib import contextmanager 

4from dataclasses import dataclass 

5from enum import Enum 

6from typing import Any, Collection, Dict, Iterator, List, Optional, Union 

7 

8import torch 

9 

10# Prefixes used by tiny/random test models that produce degenerate weights and 

11# should be skipped for certain benchmarks (centering, generation, etc.). 

12TINY_TEST_MODEL_PATTERNS = ( 

13 "tiny-random", 

14 "trl-internal-testing/tiny", 

15 "peft-internal-testing/tiny", 

16) 

17 

18 

19@contextmanager 

20def deterministic_rng(seed: int = 42) -> Iterator[None]: 

21 """Seed sampling locally, leaving the caller's RNG stream untouched. 

22 

23 Benchmarks that sample need reproducible verdicts, but a bare manual_seed 

24 rewrites the process-global stream for every benchmark that follows. 

25 """ 

26 # Sampling draws from the logits' device, so seed CUDA and MPS too; only the 

27 # generators snapshotted here are seeded, so each one is restored afterwards. 

28 cuda_devices = list(range(torch.cuda.device_count())) if torch.cuda.is_available() else [] 

29 mps_state = torch.mps.get_rng_state() if torch.backends.mps.is_available() else None 

30 # fork_rng defaults to the current accelerator since torch 2.13, so name CUDA explicitly. 

31 with torch.random.fork_rng(devices=cuda_devices, device_type="cuda"): 

32 try: 

33 torch.default_generator.manual_seed(seed) 

34 if cuda_devices: 

35 torch.cuda.manual_seed_all(seed) 

36 if mps_state is not None: 

37 torch.mps.manual_seed(seed) 

38 yield 

39 finally: 

40 if mps_state is not None: 

41 torch.mps.set_rng_state(mps_state) 

42 

43 

44def is_tiny_test_model(model_name: str) -> bool: 

45 """Check if a model name belongs to a tiny/random test model.""" 

46 return any(pattern in model_name for pattern in TINY_TEST_MODEL_PATTERNS) 

47 

48 

49# Hook patterns that bridge models inherently don't have because they use HF's 

50# native implementation rather than reimplementing attention/MLP internals. 

51BRIDGE_EXPECTED_MISSING_PATTERNS = [ 

52 "mlp.hook_pre", 

53 "mlp.hook_post", 

54 "hook_mlp_in", 

55 "hook_mlp_out", 

56 "attn.hook_rot_q", 

57 "attn.hook_rot_k", 

58 "hook_pos_embed", 

59 "embed.ln.hook_scale", 

60 "embed.ln.hook_normalized", 

61 "attn.hook_q", 

62 "attn.hook_k", 

63 "attn.hook_v", 

64 # cfg-gated attention hooks. These exist unconditionally on the attention 

65 # bridge (so `run_with_cache` key lookups never KeyError) but only fire 

66 # when their config flag is on. `benchmark_forward_hooks` runs with 

67 # defaults (flags=False) so these correctly don't fire during that 

68 # benchmark — suppressing them here prevents false "didn't fire" 

69 # failures. The affirmative verification that they DO fire when flags 

70 # are on lives in `benchmark_gated_hooks_fire`, which toggles each flag 

71 # and asserts the relevant hooks capture activations. 

72 "hook_result", 

73 "hook_attn_in", 

74 "hook_q_input", 

75 "hook_k_input", 

76 "hook_v_input", 

77 "attn.hook_attn_scores", 

78 "attn.hook_pattern", 

79 # MoE per-expert hooks: Bridge uses HF's batched MoE forward pass via MoEBridge, 

80 # which wraps the entire MoE module. The legacy reference created individual expert 

81 # modules with per-expert hooks (e.g., blocks.0.mlp.experts.3.hook_pre). 

82 "mlp.experts.", 

83 "mlp.hook_experts", 

84 # Parallel attention+MLP architectures (GPT-J, GPT-NeoX): HF has a single 

85 # shared layer norm (ln_1), while HT creates a virtual ln2 that shares weights 

86 # with ln1. The Bridge only wraps the actual HF ln_1, so ln2 hooks don't exist. 

87 # These patterns only match "missing" hooks when ln2 is absent from the Bridge; 

88 # for non-parallel architectures, the Bridge HAS ln2 and these won't be missing. 

89 "ln2.hook_scale", 

90 "ln2.hook_normalized", 

91] 

92 

93 

94def filter_expected_missing_hooks(hook_names: Collection[str]) -> list[str]: 

95 """Filter out hook names that bridge models are expected to be missing.""" 

96 return [ 

97 h 

98 for h in hook_names 

99 if not any(pattern in h for pattern in BRIDGE_EXPECTED_MISSING_PATTERNS) 

100 ] 

101 

102 

103_DEFAULT_WAVEFORM_SAMPLES = 16000 

104 

105 

106def build_modality_input( 

107 bridge: Any, 

108 batch_size: int = 1, 

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

110 dtype: Optional[torch.dtype] = None, 

111) -> Optional[torch.Tensor]: 

112 """Build a synthetic model input for a non-text bridge, or None for text models. 

113 

114 Audio and vision models take a raw tensor where text models take token ids, and 

115 the shape is architecture-specific: spectrogram encoders (AST) need 

116 ``[batch, max_length, num_mel_bins]`` where waveform encoders (HuBERT, wav2vec2) 

117 need ``[batch, samples]``, and vision encoders need 

118 ``[batch, num_channels, image_size, image_size]``. Shapes come from the HF config 

119 so a checkpoint with non-default dimensions is still handled correctly. 

120 """ 

121 cfg = getattr(bridge, "cfg", None) 

122 if cfg is None: 122 ↛ 123line 122 didn't jump to line 123 because the condition on line 122 was never true

123 return None 

124 

125 hf_config = getattr(getattr(bridge, "original_model", None), "config", None) 

126 

127 def _from_config(name: str, default: int) -> int: 

128 value = getattr(hf_config, name, None) if hf_config is not None else None 

129 if value is None: 129 ↛ 130line 129 didn't jump to line 130 because the condition on line 129 was never true

130 value = getattr(cfg, name, None) 

131 return int(value) if isinstance(value, int) else default 

132 

133 if getattr(cfg, "is_visual_model", False): 

134 image_size = _from_config("image_size", 224) 

135 num_channels = _from_config("num_channels", 3) 

136 return torch.randn( 

137 batch_size, num_channels, image_size, image_size, device=device, dtype=dtype 

138 ) 

139 

140 if getattr(cfg, "is_audio_seq2seq", False): 

141 # Whisper-style log-mel window [batch, n_mels, 2 * n_frames]: conv2 has stride 2. 

142 n_mels = _from_config("num_mel_bins", 80) 

143 n_frames = _from_config("max_source_positions", 1500) 

144 return torch.randn(batch_size, n_mels, 2 * n_frames, device=device, dtype=dtype) 

145 

146 if getattr(cfg, "is_audio_model", False): 

147 # num_mel_bins is what distinguishes a spectrogram encoder from a waveform one. 

148 num_mel_bins = getattr(hf_config, "num_mel_bins", None) if hf_config is not None else None 

149 if num_mel_bins is None: 

150 return torch.randn(batch_size, _DEFAULT_WAVEFORM_SAMPLES, device=device, dtype=dtype) 

151 max_length = _from_config("max_length", 1024) 

152 return torch.randn(batch_size, max_length, int(num_mel_bins), device=device, dtype=dtype) 

153 

154 return None 

155 

156 

157def safe_allclose( 

158 tensor1: torch.Tensor, 

159 tensor2: torch.Tensor, 

160 atol: float = 1e-5, 

161 rtol: float = 1e-5, 

162) -> bool: 

163 """torch.allclose that handles dtype and device mismatches.""" 

164 if tensor1.device != tensor2.device: 164 ↛ 165line 164 didn't jump to line 165 because the condition on line 164 was never true

165 tensor1 = tensor1.cpu() 

166 tensor2 = tensor2.cpu() 

167 if tensor1.dtype != tensor2.dtype: 167 ↛ 168line 167 didn't jump to line 168 because the condition on line 167 was never true

168 tensor1 = tensor1.to(torch.float32) 

169 tensor2 = tensor2.to(torch.float32) 

170 return torch.allclose(tensor1, tensor2, atol=atol, rtol=rtol) 

171 

172 

173class BenchmarkSeverity(Enum): 

174 """Severity levels for benchmark results.""" 

175 

176 INFO = "info" # ✅ PASS - Model working perfectly, all checks passed 

177 WARNING = "warning" # ⚠️ PASS with notes - Acceptable differences worth noting 

178 DANGER = "danger" # ❌ FAIL - Significant mismatches or failures 

179 ERROR = "error" # ❌ ERROR - Test crashed or couldn't run 

180 SKIPPED = "skipped" # ⏭️ SKIPPED - Test skipped (e.g., no reference model available) 

181 

182 

183@dataclass 

184class BenchmarkResult: 

185 """Result of a benchmark test.""" 

186 

187 name: str 

188 severity: BenchmarkSeverity 

189 message: str 

190 details: Optional[Dict[str, Any]] = None 

191 passed: bool = True 

192 phase: Optional[int] = None # Phase number (1, 2, 3, etc.) 

193 

194 def __str__(self) -> str: 

195 """Format result for console output.""" 

196 severity_icons = { 

197 BenchmarkSeverity.INFO: "🟢", 

198 BenchmarkSeverity.WARNING: "🟡", 

199 BenchmarkSeverity.DANGER: "🔴", 

200 BenchmarkSeverity.ERROR: "❌", 

201 BenchmarkSeverity.SKIPPED: "⏭️", 

202 } 

203 icon = severity_icons[self.severity] 

204 

205 if self.severity == BenchmarkSeverity.SKIPPED: 

206 status = "SKIPPED" 

207 else: 

208 status = "PASS" if self.passed else "FAIL" 

209 

210 result = f"{icon} [{status}] {self.name}: {self.message}" 

211 

212 if self.details: 

213 detail_lines = [] 

214 for key, value in self.details.items(): 

215 detail_lines.append(f" {key}: {value}") 

216 result += "\n" + "\n".join(detail_lines) 

217 

218 return result 

219 

220 def print_immediate(self) -> None: 

221 """Print this result immediately to console.""" 

222 print(str(self)) 

223 

224 

225@dataclass 

226class PhaseReferenceData: 

227 """Float32 reference data from Phase 1 for Phase 3 equivalence comparison.""" 

228 

229 hf_logits: Optional[torch.Tensor] = None 

230 hf_loss: Optional[float] = None 

231 test_text: Optional[str] = None 

232 

233 

234def make_capture_hook(storage: dict, name: str): 

235 """Create a forward hook that captures activations into a dict. 

236 

237 Handles both raw tensors and tuples (extracts first element). 

238 """ 

239 

240 def hook_fn(tensor, hook): 

241 if isinstance(tensor, torch.Tensor): 

242 storage[name] = tensor.detach().clone() 

243 elif isinstance(tensor, tuple) and len(tensor) > 0: 

244 if isinstance(tensor[0], torch.Tensor): 

245 storage[name] = tensor[0].detach().clone() 

246 return tensor 

247 

248 return hook_fn 

249 

250 

251def make_grad_capture_hook(storage: dict, name: str, return_none: bool = False): 

252 """Create a backward hook that captures gradients into a dict. 

253 

254 Args: 

255 storage: Dict to store captured gradients 

256 name: Key name for storage 

257 return_none: If True, return None (for backward hooks that shouldn't modify grads) 

258 """ 

259 

260 def hook_fn(tensor, hook=None): 

261 if isinstance(tensor, torch.Tensor): 

262 storage[name] = tensor.detach().clone() 

263 elif isinstance(tensor, tuple) and len(tensor) > 0: 263 ↛ 266line 263 didn't jump to line 266 because the condition on line 263 was always true

264 if tensor[0] is not None and isinstance(tensor[0], torch.Tensor): 264 ↛ 266line 264 didn't jump to line 266 because the condition on line 264 was always true

265 storage[name] = tensor[0].detach().clone() 

266 return None if return_none else tensor 

267 

268 return hook_fn 

269 

270 

271def _squeeze_batch_dim(t1: torch.Tensor, t2: torch.Tensor): 

272 """Handle batch dimension differences (e.g., [seq, dim] vs [1, seq, dim]). 

273 

274 Returns (t1, t2) with matching shapes, or None if shapes are incompatible. 

275 """ 

276 if t1.shape == t2.shape: 

277 return t1, t2 

278 if t1.ndim == t2.ndim - 1 and t2.shape[0] == 1 and t1.shape == t2.shape[1:]: 

279 return t1.unsqueeze(0), t2 

280 if t2.ndim == t1.ndim - 1 and t1.shape[0] == 1 and t2.shape == t1.shape[1:]: 280 ↛ 281line 280 didn't jump to line 281 because the condition on line 280 was never true

281 return t1, t2.unsqueeze(0) 

282 return None 

283 

284 

285def compare_activation_dicts( 

286 dict1: Dict[str, torch.Tensor], 

287 dict2: Dict[str, torch.Tensor], 

288 atol: float = 1e-5, 

289 rtol: float = 0.0, 

290) -> List[str]: 

291 """Compare two activation/gradient dicts, returning mismatch descriptions. 

292 

293 Handles batch-dim squeezing and dtype/device normalization. 

294 """ 

295 mismatches = [] 

296 common_keys = sorted(set(dict1.keys()) & set(dict2.keys())) 

297 for key in common_keys: 

298 t1, t2 = dict1[key], dict2[key] 

299 squeezed = _squeeze_batch_dim(t1, t2) 

300 if squeezed is None: 

301 mismatches.append(f"{key}: Shape mismatch - {t1.shape} vs {t2.shape}") 

302 continue 

303 t1, t2 = squeezed 

304 if not safe_allclose(t1, t2, atol=atol, rtol=rtol): 

305 b, r = t1.float(), t2.float() 

306 max_diff = torch.max(torch.abs(b - r)).item() 

307 mean_diff = torch.mean(torch.abs(b - r)).item() 

308 mismatches.append( 

309 f"{key}: Value mismatch - max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}" 

310 ) 

311 return mismatches 

312 

313 

314def compare_tensors( 

315 tensor1: torch.Tensor, 

316 tensor2: torch.Tensor, 

317 atol: float = 1e-5, 

318 rtol: float = 1e-5, 

319 name: str = "tensors", 

320) -> BenchmarkResult: 

321 """Compare two tensors and return a benchmark result. 

322 

323 Args: 

324 tensor1: First tensor 

325 tensor2: Second tensor 

326 atol: Absolute tolerance 

327 rtol: Relative tolerance 

328 name: Name of the comparison 

329 

330 Returns: 

331 BenchmarkResult with comparison details 

332 """ 

333 # Check shapes 

334 if tensor1.shape != tensor2.shape: 334 ↛ 335line 334 didn't jump to line 335 because the condition on line 334 was never true

335 return BenchmarkResult( 

336 name=name, 

337 severity=BenchmarkSeverity.DANGER, 

338 message=f"Shape mismatch: {tensor1.shape} vs {tensor2.shape}", 

339 passed=False, 

340 ) 

341 

342 if tensor1.device != tensor2.device: 342 ↛ 343line 342 didn't jump to line 343 because the condition on line 342 was never true

343 tensor1 = tensor1.cpu() 

344 tensor2 = tensor2.cpu() 

345 

346 if tensor1.dtype != tensor2.dtype: 346 ↛ 347line 346 didn't jump to line 347 because the condition on line 346 was never true

347 tensor1 = tensor1.to(torch.float32) 

348 tensor2 = tensor2.to(torch.float32) 

349 

350 if torch.allclose(tensor1, tensor2, atol=atol, rtol=rtol): 350 ↛ 358line 350 didn't jump to line 358 because the condition on line 350 was always true

351 return BenchmarkResult( 

352 name=name, 

353 severity=BenchmarkSeverity.INFO, 

354 message="Tensors match within tolerance", 

355 details={"atol": atol, "rtol": rtol}, 

356 ) 

357 

358 diff = torch.abs(tensor1 - tensor2) 

359 max_diff = diff.max().item() 

360 mean_diff = diff.mean().item() 

361 rel_diff = diff / (torch.abs(tensor1) + 1e-10) 

362 mean_rel = rel_diff.mean().item() 

363 

364 return BenchmarkResult( 

365 name=name, 

366 severity=BenchmarkSeverity.DANGER, 

367 message=f"Tensors differ: max_diff={max_diff:.6f}, mean_rel={mean_rel:.6f}", 

368 details={ 

369 "max_diff": max_diff, 

370 "mean_diff": mean_diff, 

371 "mean_rel": mean_rel, 

372 "atol": atol, 

373 "rtol": rtol, 

374 }, 

375 passed=False, 

376 ) 

377 

378 

379def compare_scalars( 

380 scalar1: Union[float, int], 

381 scalar2: Union[float, int], 

382 atol: float = 1e-5, 

383 name: str = "scalars", 

384) -> BenchmarkResult: 

385 """Compare two scalar values and return a benchmark result. 

386 

387 Args: 

388 scalar1: First scalar 

389 scalar2: Second scalar 

390 atol: Absolute tolerance 

391 name: Name of the comparison 

392 

393 Returns: 

394 BenchmarkResult with comparison details 

395 """ 

396 diff = abs(float(scalar1) - float(scalar2)) 

397 

398 if diff < atol: 398 ↛ 406line 398 didn't jump to line 406 because the condition on line 398 was always true

399 return BenchmarkResult( 

400 name=name, 

401 severity=BenchmarkSeverity.INFO, 

402 message=f"Scalars match: {scalar1:.6f} ≈ {scalar2:.6f}", 

403 details={"diff": diff, "atol": atol}, 

404 ) 

405 else: 

406 return BenchmarkResult( 

407 name=name, 

408 severity=BenchmarkSeverity.DANGER, 

409 message=f"Scalars differ: {scalar1:.6f} vs {scalar2:.6f}", 

410 details={"diff": diff, "atol": atol}, 

411 passed=False, 

412 ) 

413 

414 

415def format_results(results: List[BenchmarkResult]) -> str: 

416 """Format a list of benchmark results for console output. 

417 

418 Args: 

419 results: List of benchmark results 

420 

421 Returns: 

422 Formatted string for console output 

423 """ 

424 output = [] 

425 output.append("=" * 80) 

426 output.append("BENCHMARK RESULTS") 

427 output.append("=" * 80) 

428 

429 # Count by severity 

430 severity_counts = { 

431 BenchmarkSeverity.INFO: 0, 

432 BenchmarkSeverity.WARNING: 0, 

433 BenchmarkSeverity.DANGER: 0, 

434 BenchmarkSeverity.ERROR: 0, 

435 BenchmarkSeverity.SKIPPED: 0, 

436 } 

437 

438 passed = 0 

439 failed = 0 

440 skipped = 0 

441 

442 for result in results: 

443 severity_counts[result.severity] += 1 

444 if result.severity == BenchmarkSeverity.SKIPPED: 

445 skipped += 1 

446 elif result.passed: 

447 passed += 1 

448 else: 

449 failed += 1 

450 

451 # Summary 

452 total = len(results) 

453 run_tests = total - skipped 

454 output.append(f"\nTotal: {total} tests") 

455 if skipped > 0: 

456 output.append(f"Run: {run_tests} tests") 

457 output.append(f"Skipped: {skipped} tests") 

458 if run_tests > 0: 

459 output.append(f"Passed: {passed} ({passed/run_tests*100:.1f}%)") 

460 output.append(f"Failed: {failed} ({failed/run_tests*100:.1f}%)") 

461 output.append("") 

462 output.append(f"🟢 INFO: {severity_counts[BenchmarkSeverity.INFO]}") 

463 output.append(f"🟡 WARNING: {severity_counts[BenchmarkSeverity.WARNING]}") 

464 output.append(f"🔴 DANGER: {severity_counts[BenchmarkSeverity.DANGER]}") 

465 output.append(f"❌ ERROR: {severity_counts[BenchmarkSeverity.ERROR]}") 

466 if skipped > 0: 

467 output.append(f"⏭️ SKIPPED: {severity_counts[BenchmarkSeverity.SKIPPED]}") 

468 output.append("") 

469 output.append("-" * 80) 

470 

471 # Individual results 

472 for result in results: 

473 output.append(str(result)) 

474 output.append("") 

475 

476 output.append("=" * 80) 

477 

478 return "\n".join(output) 

479 

480 

481def bridge_self_target_loss(bridge, test_text: str): 

482 """Loss with the tokenized input as explicit labels. 

483 

484 Seq2seq bridges refuse label-less return_type="loss" (encoder input_ids are 

485 not decoder targets), so every benchmark loss call routes through here. 

486 """ 

487 labels = bridge.to_tokens(test_text) 

488 return bridge(test_text, labels=labels, return_type="loss")