Coverage for transformer_lens/benchmarks/component_outputs.py: 66%
468 statements
« prev ^ index » next coverage.py v7.10.1, created at 2026-11-25 00:28 +0000
« prev ^ index » next coverage.py v7.10.1, created at 2026-11-25 00:28 +0000
1"""Comprehensive component benchmarking utility for TransformerBridge.
3This module provides utilities to benchmark all standard components in a TransformerBridge
4model against their HuggingFace equivalents, ensuring output parity.
5"""
7from __future__ import annotations
9from dataclasses import dataclass, field
10from typing import Any, Callable, Dict, List, Optional, Tuple, cast
12import torch
13from torch import nn
15from transformer_lens.benchmarks.utils import build_modality_input
16from transformer_lens.config import TransformerBridgeConfig
17from transformer_lens.model_bridge.architecture_adapter import ArchitectureAdapter
18from transformer_lens.model_bridge.generalized_components.base import (
19 GeneralizedComponent,
20)
23@dataclass
24class ComponentTestResult:
25 """Result of testing a single component."""
27 component_path: str
28 component_type: str
29 passed: bool
30 max_diff: float
31 mean_diff: float
32 output_shape: Tuple[int, ...]
33 error_message: Optional[str] = None
34 percentile_diffs: Optional[Dict[str, float]] = None # 50th, 90th, 99th percentile diffs
36 def get_failure_severity(self) -> str:
37 """Categorize the severity of a failure.
39 Returns:
40 Severity level: "critical", "high", "medium", "low", or "pass"
41 """
42 if self.passed:
43 return "pass"
44 if self.error_message:
45 return "critical"
46 if self.max_diff > 1e-1:
47 return "critical"
48 elif self.max_diff > 1e-3:
49 return "high"
50 elif self.max_diff > 1e-4:
51 return "medium"
52 else:
53 return "low"
56@dataclass
57class BenchmarkReport:
58 """Complete benchmark report for all components."""
60 model_name: str
61 total_components: int
62 passed_components: int
63 failed_components: int
64 component_results: List[ComponentTestResult] = field(default_factory=list)
66 @property
67 def pass_rate(self) -> float:
68 """Calculate the pass rate as a percentage."""
69 if self.total_components == 0: 69 ↛ 70line 69 didn't jump to line 70 because the condition on line 69 was never true
70 return 0.0
71 return (self.passed_components / self.total_components) * 100
73 def print_summary(self, verbose: bool = False) -> None:
74 """Print a summary of the benchmark results.
76 Args:
77 verbose: If True, print details for all components. If False, only print failures.
78 """
79 print("\n" + "=" * 80)
80 print(f"Component Benchmark Report: {self.model_name}")
81 print("=" * 80)
82 print(f"Total components tested: {self.total_components}")
83 print(f"Passed: {self.passed_components} ({self.pass_rate:.1f}%)")
84 print(f"Failed: {self.failed_components}")
85 print("=" * 80)
87 if verbose: 87 ↛ 88line 87 didn't jump to line 88 because the condition on line 87 was never true
88 print("\nAll Component Results:")
89 print("-" * 80)
90 for result in self.component_results:
91 self._print_component_result(result)
92 elif self.failed_components > 0: 92 ↛ 93line 92 didn't jump to line 93 because the condition on line 92 was never true
93 print("\nFailed Components:")
94 print("-" * 80)
95 for result in self.component_results:
96 if not result.passed:
97 self._print_component_result(result)
99 print("=" * 80 + "\n")
101 def _print_component_result(self, result: ComponentTestResult) -> None:
102 """Print details of a single component result."""
103 status = "✓ PASS" if result.passed else "✗ FAIL"
104 severity = result.get_failure_severity()
106 # Add severity indicator for failures
107 if not result.passed and severity != "critical":
108 status = f"{status} [{severity.upper()}]"
110 print(f"{status} | {result.component_path}")
111 print(f" Type: {result.component_type}")
112 print(f" Shape: {result.output_shape}")
113 print(f" Max diff: {result.max_diff:.6e}")
114 print(f" Mean diff: {result.mean_diff:.6e}")
116 if result.percentile_diffs:
117 print(f" Percentile diffs:")
118 for percentile, diff in sorted(result.percentile_diffs.items()):
119 print(f" {percentile}: {diff:.6e}")
121 if result.error_message:
122 print(f" Error: {result.error_message}")
123 print()
125 def get_component_type_summary(self) -> Dict[str, Dict[str, int]]:
126 """Get a summary of results grouped by component type.
128 Returns:
129 Dictionary mapping component types to their pass/fail counts
130 """
131 summary: Dict[str, Dict[str, int]] = {}
133 for result in self.component_results:
134 comp_type = result.component_type
135 if comp_type not in summary:
136 summary[comp_type] = {"passed": 0, "failed": 0, "total": 0}
138 summary[comp_type]["total"] += 1
139 if result.passed: 139 ↛ 142line 139 didn't jump to line 142 because the condition on line 139 was always true
140 summary[comp_type]["passed"] += 1
141 else:
142 summary[comp_type]["failed"] += 1
144 return summary
146 def get_failure_by_severity(self) -> Dict[str, List[ComponentTestResult]]:
147 """Group failures by severity level.
149 Returns:
150 Dictionary mapping severity levels to lists of failed components
151 """
152 failures: Dict[str, List[ComponentTestResult]] = {
153 "critical": [],
154 "high": [],
155 "medium": [],
156 "low": [],
157 }
159 for result in self.component_results:
160 if not result.passed:
161 severity = result.get_failure_severity()
162 if severity in failures:
163 failures[severity].append(result)
165 return failures
167 def print_detailed_analysis(self) -> None:
168 """Print detailed analysis of benchmark results."""
169 print("\n" + "=" * 80)
170 print("Detailed Benchmark Analysis")
171 print("=" * 80)
173 # Component type summary
174 print("\nResults by Component Type:")
175 print("-" * 80)
176 type_summary = self.get_component_type_summary()
177 for comp_type, stats in sorted(type_summary.items()):
178 pass_rate = (stats["passed"] / stats["total"]) * 100 if stats["total"] > 0 else 0
179 print(
180 f"{comp_type:30s}: {stats['passed']:3d}/{stats['total']:3d} passed ({pass_rate:5.1f}%)"
181 )
183 # Failure severity analysis
184 if self.failed_components > 0:
185 print("\nFailures by Severity:")
186 print("-" * 80)
187 failures_by_severity = self.get_failure_by_severity()
188 for severity in ["critical", "high", "medium", "low"]:
189 count = len(failures_by_severity[severity])
190 if count > 0:
191 print(f"{severity.upper():10s}: {count} component(s)")
192 for result in failures_by_severity[severity][:3]: # Show first 3
193 print(f" - {result.component_path} (max_diff: {result.max_diff:.2e})")
194 if count > 3:
195 print(f" ... and {count - 3} more")
197 print("=" * 80 + "\n")
200def _is_ssm_mixer_internal(component_path: str) -> bool:
201 """True for a submodule *inside* an SSM/recurrent mixer slot (``.mixer``/``.linear_attn``).
203 Such submodules wrap the identical HF module (parity is covered by forward_pass_logits)
204 and take SSM-internal shapes, not the ``[b, seq, d_model]`` residual the isolated harness
205 feeds — so they are skipped. The mixer node itself (path ending in the slot) is not.
206 """
207 return any(slot in component_path.split(".")[:-1] for slot in ("mixer", "linear_attn"))
210class ComponentBenchmarker:
211 """Benchmarking utility for testing TransformerBridge components against HuggingFace."""
213 def _is_delegated_block(self) -> bool:
214 """Return True if the blocks component has maintain_native_attention set."""
215 blocks = (
216 getattr(self.adapter, "component_mapping", {}).get("blocks")
217 if self.adapter is not None
218 else None
219 )
220 return getattr(blocks, "maintain_native_attention", False)
222 def __init__(
223 self,
224 bridge_model: nn.Module,
225 hf_model: nn.Module,
226 adapter: ArchitectureAdapter,
227 cfg: TransformerBridgeConfig,
228 atol: float = 1e-4,
229 rtol: float = 1e-4,
230 ):
231 """Initialize the component benchmarker.
233 Args:
234 bridge_model: The TransformerBridge model
235 hf_model: The HuggingFace model
236 adapter: The architecture adapter for mapping components
237 cfg: The model configuration
238 atol: Absolute tolerance for comparing outputs
239 rtol: Relative tolerance for comparing outputs
240 """
241 self.bridge_model = bridge_model
242 self.hf_model = hf_model
243 self.adapter = adapter
244 self.cfg = cfg
246 # Reconcile dtypes: upcast both models to the higher-precision dtype.
247 self._bridge_was_upcast = False
248 self._bridge_original_dtype: Optional[torch.dtype] = None
249 try:
250 hf_dtype = next(hf_model.parameters()).dtype
251 except StopIteration:
252 hf_dtype = torch.float32
253 try:
254 bridge_dtype = next(bridge_model.parameters()).dtype
255 except StopIteration:
256 bridge_dtype = torch.float32
257 if hf_dtype != bridge_dtype:
258 # Upcast to the higher-precision dtype
259 target = hf_dtype if hf_dtype.itemsize >= bridge_dtype.itemsize else bridge_dtype
260 if bridge_dtype != target: 260 ↛ 261line 260 didn't jump to line 261 because the condition on line 260 was never true
261 self._bridge_original_dtype = bridge_dtype
262 bridge_model.to(target)
263 self._bridge_was_upcast = True
264 if hf_dtype != target: 264 ↛ 266line 264 didn't jump to line 266 because the condition on line 264 was always true
265 hf_model.to(target)
266 self.test_dtype = hf_dtype if hf_dtype.itemsize >= bridge_dtype.itemsize else bridge_dtype
268 # Adjust tolerances based on dtype for reduced precision formats
269 model_dtype = getattr(cfg, "dtype", torch.float32)
270 if model_dtype == torch.bfloat16: 270 ↛ 275line 270 didn't jump to line 275 because the condition on line 270 was never true
271 # bfloat16 has ~7 bits of precision (3 decimal digits)
272 # Use more lenient tolerance
273 # Normalization layers (RMSNorm/LayerNorm) can have larger errors due to
274 # square roots and divisions, so use 0.3 tolerance
275 self.atol = max(atol, 0.3)
276 self.rtol = max(rtol, 0.3)
277 elif model_dtype == torch.float16: 277 ↛ 279line 277 didn't jump to line 279 because the condition on line 277 was never true
278 # float16 has ~10 bits of precision (3-4 decimal digits)
279 self.atol = max(atol, 5e-3)
280 self.rtol = max(rtol, 5e-3)
281 else:
282 # float32 or float64 - use provided tolerances
283 self.atol = atol
284 self.rtol = rtol
286 def benchmark_all_components(
287 self,
288 test_inputs: Optional[Dict[str, torch.Tensor]] = None,
289 skip_components: Optional[List[str]] = None,
290 ) -> BenchmarkReport:
291 """Benchmark all components in the model.
293 Args:
294 test_inputs: Optional dictionary of pre-generated test inputs.
295 If None, will generate default inputs.
296 skip_components: Optional list of component paths to skip
298 Returns:
299 BenchmarkReport with results for all tested components
300 """
301 skip_components = skip_components or []
302 # Adapters can exclude subcomponents whose isolated forward cannot run
303 # on synthesized probes (e.g. fused top-k routers) by path suffix.
304 skip_suffixes = tuple(getattr(self.adapter, "component_test_skip_suffixes", ()))
305 component_mapping = self.adapter.get_component_mapping()
307 # Generate test inputs if not provided
308 if test_inputs is None: 308 ↛ 311line 308 didn't jump to line 311 because the condition on line 308 was always true
309 test_inputs = self._generate_test_inputs()
311 results: List[ComponentTestResult] = []
313 # Block-type components that need to be tested recursively by layer
314 # (they are ModuleLists that don't have direct forward methods)
315 block_components = {"blocks", "encoder_blocks", "decoder_blocks", "L_blocks", "H_blocks"}
317 # Test top-level components (embed, pos_embed, ln_final, unembed)
318 for comp_name, component in component_mapping.items():
319 if comp_name in skip_components:
320 continue
322 if comp_name in block_components:
323 # Handle blocks separately - test their subcomponents by layer
324 continue
326 result = self._test_component(comp_name, component, test_inputs)
327 if result is not None: 327 ↛ 318line 327 didn't jump to line 318 because the condition on line 327 was always true
328 results.append(result)
330 # Test block components recursively
331 for block_type in block_components:
332 if block_type in component_mapping and block_type not in skip_components:
333 blocks_component = component_mapping[block_type]
334 # Derive the length from the actual stack: asymmetric
335 # encoder-decoder models (e.g. Blenderbot's 2/12) have
336 # per-stack counts that cfg.n_layers cannot represent.
337 bound_blocks = getattr(self.bridge_model, block_type)
338 n_layers = len(bound_blocks)
340 for layer_idx in range(n_layers):
341 # Get the actual block to check which submodules were bound
342 actual_block = getattr(self.bridge_model, block_type)[layer_idx]
343 for subcomp_name, subcomponent in blocks_component.submodules.items():
344 # Skip optional submodules absent on this layer (hybrid architectures)
345 if subcomp_name not in actual_block._modules: 345 ↛ 346line 345 didn't jump to line 346 because the condition on line 345 was never true
346 continue
347 comp_path = f"{block_type}.{layer_idx}.{subcomp_name}"
348 self._test_component_recursive(
349 comp_path, subcomponent, test_inputs, results, skip_components
350 )
352 # Clean up test inputs to free memory
353 if test_inputs is not None: 353 ↛ 361line 353 didn't jump to line 361 because the condition on line 353 was always true
354 for key in list(test_inputs.keys()):
355 tensor = test_inputs[key]
356 if tensor is not None and isinstance(tensor, torch.Tensor): 356 ↛ 354line 356 didn't jump to line 354 because the condition on line 356 was always true
357 del tensor
358 test_inputs.clear()
360 # Create report
361 passed = sum(1 for r in results if r.passed)
362 failed = sum(1 for r in results if not r.passed)
364 report = BenchmarkReport(
365 model_name=getattr(self.cfg, "model_name", "unknown"),
366 total_components=len(results),
367 passed_components=passed,
368 failed_components=failed,
369 component_results=results,
370 )
372 # Restore bridge to its original dtype if we upcast it
373 if self._bridge_was_upcast and self._bridge_original_dtype is not None: 373 ↛ 374line 373 didn't jump to line 374 because the condition on line 373 was never true
374 self.bridge_model.to(self._bridge_original_dtype)
376 return report
378 def _test_component_recursive(
379 self,
380 component_path: str,
381 component: GeneralizedComponent,
382 test_inputs: Dict[str, torch.Tensor],
383 results: List[ComponentTestResult],
384 skip_components: Optional[List[str]] = None,
385 ) -> None:
386 """Recursively test a component and all its subcomponents.
388 This method tests the given component and then recursively tests all its
389 nested subcomponents (e.g., attn.q, attn.k, mlp.gate, etc.).
391 Note: We skip testing q/k/v subcomponents when the parent attention module
392 uses joint QKV projection (JointQKVAttentionBridge), as these are virtual
393 components that don't exist as separate modules in HuggingFace.
395 Args:
396 component_path: Path to the component (e.g., "blocks.0.attn")
397 component: The generalized component bridge
398 test_inputs: Dictionary of test inputs
399 results: List to append results to
400 skip_components: Optional list of component paths to skip
401 """
402 skip_components = skip_components or []
404 # Skip if in skip list
405 if component_path in skip_components: 405 ↛ 406line 405 didn't jump to line 406 because the condition on line 405 was never true
406 return
408 # Adapter-declared suffix exclusions (isolated forward can't run on
409 # synthesized probes, e.g. fused top-k routers).
410 skip_suffixes = tuple(getattr(self.adapter, "component_test_skip_suffixes", ()))
411 if any(component_path.endswith(suffix) for suffix in skip_suffixes): 411 ↛ 412line 411 didn't jump to line 412 because the condition on line 411 was never true
412 return
414 # SSM/recurrent mixer internal submodules can't be tested in isolation (see
415 # _is_ssm_mixer_internal); the mixer node itself is still tested against HF.
416 if _is_ssm_mixer_internal(component_path): 416 ↛ 417line 416 didn't jump to line 417 because the condition on line 416 was never true
417 return
419 # Skip MLP components that don't exist as separate modules in HF (name=None)
420 # These are virtual components where fc1/fc2 are directly on the layer
421 # Component testing doesn't work for these because get_component returns the parent layer
422 if "mlp" in component_path and hasattr(component, "name") and component.name is None:
423 return
425 # Skip MLPs whose forward needs more than a hidden_states probe (BLOOM
426 # residual; transformers 5.x fused MoE experts need router indices/weights);
427 # full-model forward_pass_logits already covers their parity. Fetch the
428 # layer-bound component since the per-block template's original_component is None.
429 if "mlp" in component_path:
430 import inspect
432 try:
433 bound = self.adapter.get_component(self.bridge_model, component_path)
434 inner = getattr(bound, "original_component", None)
435 if inner is not None: 435 ↛ 453line 435 didn't jump to line 453 because the condition on line 435 was always true
436 required = [
437 p
438 for p in inspect.signature(inner.forward).parameters.values()
439 if p.default is inspect.Parameter.empty
440 and p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)
441 and p.name != "self"
442 ]
443 # An isolatable MLP needs only hidden_states; more required
444 # positional args means it can't run standalone.
445 if len(required) > 1:
446 return
447 except (AttributeError, ValueError, TypeError):
448 # Can't resolve/inspect — fall through and let the test run.
449 pass
451 # Skip attention components that require position embeddings in Phase 3
452 # These can't be tested in isolation without full model context for position embeddings
453 if (
454 "attn" in component_path
455 and hasattr(component, "requires_position_embeddings")
456 and component.requires_position_embeddings
457 ):
458 return
460 # Skip attention components that use native HF attention (maintain_native_attention=True)
461 # These have custom forward signatures (e.g., BLOOM requires residual, alibi, attention_mask)
462 # and can't be tested in isolation without full model context
463 if ( 463 ↛ 468line 463 didn't jump to line 468 because the condition on line 463 was never true
464 "attn" in component_path
465 and hasattr(component, "maintain_native_attention")
466 and component.maintain_native_attention
467 ):
468 return
470 # Skip attention and PLE submodules when using DelegatedAttentionBlockBridge.
471 # These architectures delegate all math to HF; the benchmark can't call the HF
472 # attention in isolation (missing position_embeddings, attention_mask, etc.) and
473 # PLE submodules receive per-layer inputs at a different dimension than hidden_states.
474 _is_delegated = self._is_delegated_block()
475 if _is_delegated and "attn" in component_path: 475 ↛ 476line 475 didn't jump to line 476 because the condition on line 475 was never true
476 return
477 if _is_delegated and any( 477 ↛ 485line 477 didn't jump to line 485 because the condition on line 477 was never true
478 name in component_path
479 for name in (
480 "per_layer_input_gate",
481 "per_layer_projection",
482 "post_per_layer_input_norm",
483 )
484 ):
485 return
487 # Skip models whose MLP/attn forward signatures require extra context from the block:
488 # - BLOOM: MLP requires residual and alibi bias
489 # - T5: requires cache_position for relative position embeddings
490 # - MPT: MLP.forward(hidden_states, residual) performs the residual addition internally
491 if "attn" in component_path or "mlp" in component_path:
492 hf_model_config = getattr(self.hf_model, "config", None)
493 if hf_model_config and hasattr(hf_model_config, "model_type"): 493 ↛ 500line 493 didn't jump to line 500 because the condition on line 493 was always true
494 if hf_model_config.model_type in ["bloom", "t5", "mpt"]: 494 ↛ 495line 494 didn't jump to line 495 because the condition on line 494 was never true
495 return
497 # Skip components that require specific shaped inputs from their parent modules
498 # These components expect intermediate outputs from their parent attention/MLP
499 # modules and can't be tested with generic hidden state inputs
500 path_parts = component_path.split(".")
501 if len(path_parts) >= 3: # e.g., "blocks.0.attn.o" or "blocks.0.mlp.out" 501 ↛ 544line 501 didn't jump to line 544 because the condition on line 501 was always true
502 last_part = path_parts[-1]
504 # Skip attention output projection (expects concatenated attn output)
505 # Skip MLP output projection (expects MLP intermediate activations)
506 # — including *_out variants (dense_out on MoE shared/dense paths).
507 # Note: q_norm/k_norm are handled specially in _run_component
508 if last_part in ["o", "out"] or last_part.endswith("_out"):
509 return
511 # Skip MLA intermediates (expect compressed-dim inputs, not hidden_states)
512 if last_part in [ 512 ↛ 520line 512 didn't jump to line 520 because the condition on line 512 was never true
513 "q_a_proj",
514 "q_a_layernorm",
515 "q_b_proj",
516 "kv_a_proj_with_mqa",
517 "kv_a_layernorm",
518 "kv_b_proj",
519 ]:
520 return
522 # Skip virtual splits from fused projections (no standalone HF equivalent)
523 if last_part in ["q", "k", "v", "gate", "in"]:
524 parent_path = ".".join(path_parts[:-1])
525 try:
526 parent_component = self.adapter.get_component(self.bridge_model, parent_path)
527 if hasattr(parent_component, "submodules"): 527 ↛ 544line 527 didn't jump to line 544 because the condition on line 527 was always true
528 parent_bridge = cast(GeneralizedComponent, parent_component)
529 subs = parent_bridge.submodules
530 # Joint QKV: q/k/v are splits from fused qkv_proj/c_attn
531 if last_part in ["q", "k", "v"] and ("qkv" in subs or "c_attn" in subs):
532 return
533 # Joint gate+up: gate/in are splits from fused gate_up_proj
534 if last_part in ["gate", "in"] and ( 534 ↛ 538line 534 didn't jump to line 538 because the condition on line 534 was never true
535 "gate_up" in subs
536 or type(parent_bridge).__name__ == "JointGateUpMLPBridge"
537 ):
538 return
539 except Exception:
540 pass
542 # Skip components not wired on this layer (per-layer or per-config variation).
543 # Only report as failure if the HF model has it but the bridge doesn't.
544 try:
545 self.adapter.get_component(self.bridge_model, component_path)
546 except (AttributeError, ValueError):
547 parts = component_path.split(".")
548 if len(parts) >= 3 and parts[1].isdigit(): 548 ↛ 566line 548 didn't jump to line 566 because the condition on line 548 was always true
549 subpath = ".".join([parts[0]] + ["{layer}"] + parts[2:])
550 # Per-layer variation: exists on some other layer (e.g., MoE vs dense)
551 for probe_layer in range(self.cfg.n_layers):
552 probe_path = subpath.replace("{layer}", str(probe_layer))
553 try:
554 self.adapter.get_component(self.bridge_model, probe_path)
555 return # Found on another layer — skip this one
556 except (AttributeError, ValueError):
557 continue
558 # Per-config absence: HF model also lacks it (e.g., q_lora_rank=None)
559 try:
560 self.adapter.get_component(self.hf_model, component_path)
561 except (AttributeError, ValueError):
562 return
563 # Bridge is missing a component that HF has — likely misconfiguration
565 # Test this component
566 result = self._test_component(component_path, component, test_inputs)
567 if result is not None: 567 ↛ 571line 567 didn't jump to line 571 because the condition on line 567 was always true
568 results.append(result)
570 # Recursively test subcomponents
571 if hasattr(component, "submodules") and component.submodules:
572 for subcomp_name, subcomponent in component.submodules.items():
573 sub_path = f"{component_path}.{subcomp_name}"
574 self._test_component_recursive(
575 sub_path, subcomponent, test_inputs, results, skip_components
576 )
578 def _test_component(
579 self,
580 component_path: str,
581 component: GeneralizedComponent,
582 test_inputs: Dict[str, torch.Tensor],
583 ) -> Optional[ComponentTestResult]:
584 """Test a single component.
586 Args:
587 component_path: Path to the component (e.g., "embed", "blocks.0.attn")
588 component: The generalized component bridge
589 test_inputs: Dictionary of test inputs
591 Returns:
592 ComponentTestResult or None if the component cannot be tested
593 """
594 try:
595 # Skip rotary_emb for DelegatedAttentionBlockBridge architectures.
596 # Gemma4's RotaryEmbeddingBridge wraps a rotary that returns a set-like
597 # structure which the benchmark comparison can't subscript.
598 if self._is_delegated_block() and component_path == "rotary_emb": 598 ↛ 599line 598 didn't jump to line 599 because the condition on line 598 was never true
599 return None
601 # Get bridge component
602 # The adapter returns nn.Module, but for bridge models it's actually GeneralizedComponent
603 bridge_component = cast(
604 GeneralizedComponent, self.adapter.get_component(self.bridge_model, component_path)
605 )
607 # Get HuggingFace component
608 hf_component = self.adapter.get_component(self.hf_model, component_path)
610 # Determine appropriate test input based on component type
611 test_input = self._get_test_input_for_component(component_path, test_inputs)
612 if test_input is None: 612 ↛ 613line 612 didn't jump to line 613 because the condition on line 612 was never true
613 return None
615 # Get input args/kwargs from the Bridge component
616 # All bridge components inherit from GeneralizedComponent and have get_dummy_inputs()
617 batch, seq_len, _ = test_input.shape
618 pos_indices = (
619 torch.arange(seq_len, device=test_input.device).unsqueeze(0).expand(batch, -1)
620 )
622 # For embedding components, generate the embedding input once
623 shared_embed_input = None
624 if component_path in ("embed", "encoder_embed", "decoder_embed"):
625 # Decoder embeddings take token ids even under an audio/vision encoder.
626 if component_path != "decoder_embed":
627 shared_embed_input = test_inputs.get("modality_input")
628 if shared_embed_input is None: 628 ↛ 636line 628 didn't jump to line 636 because the condition on line 628 was always true
629 batch, seq_len, _ = test_input.shape
630 shared_embed_input = torch.randint(
631 0, self.cfg.d_vocab, (batch, seq_len), device=test_input.device
632 )
634 # Generate shared inputs for attention/MLP/rotary components that have get_random_inputs()
635 # This is needed for model-specific inputs like position_embeddings or attention_mask
636 shared_inputs = None
637 if (
638 (
639 "attn" in component_path
640 or "mlp" in component_path
641 or "rotary" in component_path
642 or "conv" in component_path
643 )
644 and hasattr(bridge_component, "get_random_inputs")
645 and callable(getattr(bridge_component, "get_random_inputs"))
646 ):
647 batch_size, seq_len = test_input.shape[:2]
648 # Cast to callable to satisfy mypy - we've already verified it exists and is callable
649 get_random_inputs_fn = cast(
650 Callable[..., Dict[str, Any]], bridge_component.get_random_inputs
651 )
652 shared_inputs = get_random_inputs_fn(
653 batch_size=batch_size,
654 seq_len=seq_len,
655 device=test_input.device,
656 dtype=test_input.dtype,
657 )
658 if "attn" in component_path:
659 self._add_direct_attention_mask_if_needed(
660 shared_inputs, hf_component, batch_size, seq_len
661 )
663 # Override position_embeddings with correct values from HF model's rotary_emb
664 # This is needed for models with partial RoPE or non-standard rotary dims
665 if ( 665 ↛ 670line 665 didn't jump to line 670 because the condition on line 665 was never true
666 "attn" in component_path
667 and "position_embeddings" in shared_inputs
668 and hasattr(self.hf_model, "model")
669 ):
670 rotary_attr = getattr(self.hf_model.model, "rotary_emb", None)
671 if callable(rotary_attr):
672 try:
673 position_ids = (
674 torch.arange(seq_len, device=test_input.device)
675 .unsqueeze(0)
676 .expand(batch_size, -1)
677 )
678 position_embeddings = rotary_attr(test_input, position_ids)
679 shared_inputs["position_embeddings"] = position_embeddings
680 except Exception:
681 # If rotary_emb fails, keep the fallback position_embeddings from get_random_inputs()
682 pass
684 # Run through both components with shared inputs (for attention) or standard inputs (for others)
685 bridge_output = self._run_component(
686 bridge_component, test_input, component_path, shared_embed_input, shared_inputs
687 )
688 hf_output = self._run_component(
689 hf_component, test_input, component_path, shared_embed_input, shared_inputs
690 )
692 # Extract tensors if outputs are tuples
693 # Legacy modules (e.g. GPT-1's Attention) return lists, not tuples.
694 bridge_tensor = (
695 bridge_output[0] if isinstance(bridge_output, (tuple, list)) else bridge_output
696 )
697 hf_tensor = hf_output[0] if isinstance(hf_output, (tuple, list)) else hf_output
699 # Marian/Bart apply a trained final_logits_bias AFTER lm_head inside the
700 # model forward. The bridge folds it into the unembed bias (b_U), so the
701 # isolated HF lm_head must add it too for a fair comparison — otherwise
702 # the two diverge by exactly the bias (a false failure; the assembled
703 # unembed+bias path is already covered by forward_pass_logits).
704 if "unembed" in component_path or "lm_head" in component_path:
705 flb = getattr(self.hf_model, "final_logits_bias", None)
706 if (
707 flb is not None
708 and isinstance(hf_tensor, torch.Tensor)
709 and hf_tensor.shape[-1] == flb.shape[-1]
710 ):
711 hf_tensor = hf_tensor + flb.to(hf_tensor.dtype)
713 # Ensure both are tensors
714 if not isinstance(bridge_tensor, torch.Tensor) or not isinstance( 714 ↛ 717line 714 didn't jump to line 717 because the condition on line 714 was never true
715 hf_tensor, torch.Tensor
716 ):
717 return ComponentTestResult(
718 component_path=component_path,
719 component_type=type(component).__name__,
720 passed=False,
721 max_diff=float("inf"),
722 mean_diff=float("inf"),
723 output_shape=(),
724 error_message=f"Outputs are not tensors: bridge={type(bridge_tensor)}, hf={type(hf_tensor)}",
725 )
727 # Compare outputs
728 passed, max_diff, mean_diff, percentile_diffs = self._compare_outputs(
729 bridge_tensor, hf_tensor
730 )
732 # Get output shape before deleting tensors
733 output_shape = tuple(bridge_tensor.shape)
735 # Clean up output tensors immediately to free memory
736 del bridge_output, hf_output, bridge_tensor, hf_tensor
737 if shared_inputs is not None:
738 # Clean up shared inputs
739 for key in list(shared_inputs.keys()):
740 val = shared_inputs[key]
741 if val is not None and isinstance(val, torch.Tensor):
742 del val
743 shared_inputs[key] = None
744 if shared_embed_input is not None:
745 del shared_embed_input
747 return ComponentTestResult(
748 component_path=component_path,
749 component_type=type(component).__name__,
750 passed=passed,
751 max_diff=max_diff,
752 mean_diff=mean_diff,
753 output_shape=output_shape,
754 percentile_diffs=percentile_diffs,
755 )
757 except Exception as e:
758 return ComponentTestResult(
759 component_path=component_path,
760 component_type=type(component).__name__,
761 passed=False,
762 max_diff=float("inf"),
763 mean_diff=float("inf"),
764 output_shape=(),
765 error_message=str(e),
766 )
768 @staticmethod
769 def _add_direct_attention_mask_if_needed(
770 shared_inputs: Dict[str, Any],
771 hf_component: Any,
772 batch_size: int,
773 seq_len: int,
774 ) -> None:
775 """Add a causal mask for direct HF attention calls that need parent context."""
776 if "attention_mask" in shared_inputs: 776 ↛ 777line 776 didn't jump to line 777 because the condition on line 776 was never true
777 return
778 hidden_states = shared_inputs.get("hidden_states")
779 if not isinstance(hidden_states, torch.Tensor): 779 ↛ 780line 779 didn't jump to line 780 because the condition on line 779 was never true
780 return
781 if not getattr(hf_component, "is_causal", False):
782 return
783 if getattr(hf_component, "is_cross_attention", False): 783 ↛ 784line 783 didn't jump to line 784 because the condition on line 783 was never true
784 return
786 min_dtype = torch.finfo(hidden_states.dtype).min
787 causal_mask = torch.ones(seq_len, seq_len, device=hidden_states.device, dtype=torch.bool)
788 causal_mask = torch.tril(causal_mask).view(1, 1, seq_len, seq_len)
789 attention_mask = torch.zeros(
790 batch_size,
791 1,
792 seq_len,
793 seq_len,
794 device=hidden_states.device,
795 dtype=hidden_states.dtype,
796 )
797 shared_inputs["attention_mask"] = attention_mask.masked_fill(~causal_mask, min_dtype)
799 def _run_component(
800 self,
801 component: nn.Module,
802 test_input: torch.Tensor,
803 component_path: str,
804 shared_embed_input: Optional[torch.Tensor] = None,
805 shared_inputs: Optional[dict] = None,
806 ) -> Any:
807 """Run a component with appropriate arguments.
809 Args:
810 component: The component to run
811 test_input: The test input tensor
812 component_path: Path to the component for debugging
813 shared_embed_input: Pre-generated input for embedding components (token ids,
814 or a spectrogram/pixel tensor for audio and vision models)
815 shared_inputs: Pre-generated inputs from get_random_inputs() to use for both bridge and HF components
817 Returns:
818 The component output
819 """
820 # q_norm/k_norm expect d_head, not d_model
821 if component_path.endswith(".q_norm") or component_path.endswith(".k_norm"): 821 ↛ 823line 821 didn't jump to line 823 because the condition on line 821 was never true
822 # Reshape test_input from (batch, seq, d_model) to (batch, seq, d_head)
823 batch, seq, d_model = test_input.shape
824 d_head = self.cfg.d_head
825 # Use just d_head dimensions as test input
826 test_input_reshaped = test_input[..., :d_head]
827 return component(test_input_reshaped)
829 # Use shared inputs if provided (generated from bridge component's get_random_inputs())
830 if shared_inputs is not None:
831 # Check if shared_inputs contains positional args
832 if "args" in shared_inputs:
833 # Call with positional args (e.g., for rotary embeddings)
834 return component(*shared_inputs["args"])
835 else:
836 # Call with keyword args (e.g., for attention)
837 try:
838 return component(**shared_inputs)
839 except TypeError:
840 # Pre-kwarg-era modules (e.g. GPT-1's Attention) take the
841 # input positionally and reject the hidden_states keyword.
842 hidden = shared_inputs.get("hidden_states")
843 if hidden is None:
844 raise
845 mask = shared_inputs.get("attention_mask")
846 if mask is not None:
847 return component(hidden, attention_mask=mask)
848 return component(hidden)
850 # Fallback: Use legacy calling conventions for components without get_random_inputs()
851 if "attn" in component_path and "attn" == component_path.split(".")[-1]: 851 ↛ 853line 851 didn't jump to line 853 because the condition on line 851 was never true
852 # Attention components (legacy fallback)
853 try:
854 # Try TransformerLens-style attention
855 return component(
856 query_input=test_input,
857 key_input=test_input,
858 value_input=test_input,
859 past_kv_cache_entry=None,
860 attention_mask=None,
861 )
862 except TypeError:
863 try:
864 # Try HuggingFace-style attention
865 return component(hidden_states=test_input)
866 except TypeError:
867 # Try simple call
868 return component(test_input)
869 elif component_path in ("embed", "encoder_embed", "decoder_embed"):
870 # Token ids for text models; a spectrogram or pixel tensor for audio/vision.
871 if shared_embed_input is not None: 871 ↛ 874line 871 didn't jump to line 874 because the condition on line 871 was always true
872 embed_input = shared_embed_input
873 else:
874 batch, seq_len, _ = test_input.shape
875 embed_input = torch.randint(
876 0, self.cfg.d_vocab, (batch, seq_len), device=test_input.device
877 )
878 return component(embed_input)
879 elif component_path == "pos_embed" or "pos_embed" in component_path:
880 # Position embedding expects integer position indices
881 batch, seq_len, _ = test_input.shape
882 # For positional embeddings, we need position indices
883 pos_indices = (
884 torch.arange(seq_len, device=test_input.device).unsqueeze(0).expand(batch, -1)
885 )
886 try:
887 return component(pos_indices)
888 except (TypeError, IndexError):
889 # Some pos embeds just return their embeddings directly
890 # or may not take inputs
891 try:
892 if hasattr(component, "weight") and isinstance(component.weight, torch.Tensor): 892 ↛ 895line 892 didn't jump to line 895 because the condition on line 892 was always true
893 return component.weight[:seq_len]
894 else:
895 raise AttributeError("Component has no weight attribute")
896 except AttributeError:
897 # Skip this component
898 raise ValueError("Cannot test pos_embed - unclear interface")
899 elif isinstance(getattr(component, "original_component", component), torch.nn.Embedding):
900 # Any other embedding table (BERT's token_type_embed) rejects the
901 # float default: embeddings index with integer ids. The HF side is
902 # the bare nn.Embedding, the bridge side wraps one. Ids are derived
903 # from test_input so both sides index identically.
904 embedding_table = getattr(component, "original_component", component)
905 assert isinstance(embedding_table, torch.nn.Embedding) # narrowed by the elif
906 num_ids = int(embedding_table.num_embeddings)
907 id_input = (test_input.abs().sum(dim=-1) * 1e3).long() % num_ids
908 return component(id_input)
909 elif component_path == "project_in": 909 ↛ 911line 909 didn't jump to line 911 because the condition on line 909 was never true
910 # project_in expects word_embed_proj_dim, not d_model.
911 word_embed_proj_dim = getattr(self.cfg, "word_embed_proj_dim", None)
912 if word_embed_proj_dim is not None and word_embed_proj_dim != self.cfg.d_model:
913 test_input = test_input[..., :word_embed_proj_dim]
914 return component(test_input)
915 elif (
916 component_path == "unembed"
917 or "unembed" in component_path
918 or "lm_head" in component_path
919 ):
920 # Unembed may expect word_embed_proj_dim (e.g., OPT-350m project_out).
921 word_embed_proj_dim = getattr(self.cfg, "word_embed_proj_dim", None)
922 if ( 922 ↛ 927line 922 didn't jump to line 927 because the condition on line 922 was never true
923 word_embed_proj_dim is not None
924 and word_embed_proj_dim != self.cfg.d_model
925 and test_input.shape[-1] != word_embed_proj_dim
926 ):
927 test_input = test_input[..., :word_embed_proj_dim]
928 return component(test_input)
929 else:
930 # Standard components (MLP, LayerNorm, etc.)
931 try:
932 return component(test_input)
933 except TypeError:
934 # Try with hidden_states kwarg
935 return component(hidden_states=test_input)
937 def _get_test_input_for_component(
938 self, component_path: str, test_inputs: Dict[str, torch.Tensor]
939 ) -> Optional[torch.Tensor]:
940 """Get the appropriate test input for a component.
942 Args:
943 component_path: Path to the component
944 test_inputs: Dictionary of available test inputs
946 Returns:
947 The appropriate test input tensor, or None if not applicable
948 """
949 # Use standard hidden state input for most components
950 return test_inputs.get("hidden_states")
952 def _generate_test_inputs(self) -> Dict[str, torch.Tensor]:
953 """Generate default test inputs for benchmarking.
955 Returns:
956 Dictionary of test input tensors
957 """
958 batch_size = 2
959 seq_len = 8
960 d_model = self.cfg.d_model
962 # Use the reconciled dtype from __init__.
963 dtype = self.test_dtype
964 try:
965 device = next(self.hf_model.parameters()).device
966 except StopIteration:
967 device = torch.device("cpu")
969 inputs = {
970 "hidden_states": torch.randn(batch_size, seq_len, d_model, dtype=dtype, device=device),
971 }
973 # Vision/audio models have no token vocabulary — d_vocab stays at its -1 sentinel.
974 if self.cfg.d_vocab > 0: 974 ↛ 980line 974 didn't jump to line 980 because the condition on line 974 was always true
975 inputs["token_ids"] = torch.randint(
976 0, self.cfg.d_vocab, (batch_size, seq_len), device=device
977 )
979 # Audio/vision embeddings consume a raw spectrogram or pixel tensor, not token ids.
980 modality_input = build_modality_input(
981 self.bridge_model, batch_size=batch_size, device=device, dtype=dtype
982 )
983 if modality_input is not None:
984 inputs["modality_input"] = modality_input
986 return inputs
988 def _compare_outputs(
989 self, bridge_output: torch.Tensor, hf_output: torch.Tensor
990 ) -> Tuple[bool, float, float, Dict[str, float]]:
991 """Compare two output tensors.
993 Args:
994 bridge_output: Output from TransformerBridge component
995 hf_output: Output from HuggingFace component
997 Returns:
998 Tuple of (passed, max_diff, mean_diff, percentile_diffs)
999 """
1000 # Check shapes match
1001 if bridge_output.shape != hf_output.shape: 1001 ↛ 1002line 1001 didn't jump to line 1002 because the condition on line 1001 was never true
1002 return False, float("inf"), float("inf"), {}
1004 # Compute differences (upcast to float32 for safety)
1005 bo = bridge_output.float()
1006 ho = hf_output.float()
1007 diff = torch.abs(bo - ho)
1008 max_diff = diff.max().item()
1009 mean_diff = diff.mean().item()
1011 # Compute percentile differences
1012 flat_diff = diff.flatten()
1013 percentile_diffs = {
1014 "50th": torch.quantile(flat_diff, 0.5).item(),
1015 "90th": torch.quantile(flat_diff, 0.9).item(),
1016 "99th": torch.quantile(flat_diff, 0.99).item(),
1017 }
1019 # Check if within tolerance
1020 passed = torch.allclose(bo, ho, atol=self.atol, rtol=self.rtol)
1022 return passed, max_diff, mean_diff, percentile_diffs
1025def benchmark_model(
1026 model_name: str,
1027 device: str = "cpu",
1028 atol: float = 1e-4,
1029 rtol: float = 1e-4,
1030 skip_components: Optional[List[str]] = None,
1031 verbose: bool = False,
1032) -> BenchmarkReport:
1033 """Benchmark all components in a model.
1035 Args:
1036 model_name: Name of the HuggingFace model to benchmark
1037 device: Device to run on
1038 atol: Absolute tolerance for comparisons
1039 rtol: Relative tolerance for comparisons
1040 skip_components: Optional list of component paths to skip
1041 verbose: If True, print detailed results for all components
1043 Returns:
1044 BenchmarkReport with results for all components
1045 """
1046 from transformers import AutoModelForCausalLM
1048 from transformer_lens.model_bridge import TransformerBridge
1050 # Load models
1051 print(f"Loading models: {model_name}")
1052 bridge_model = TransformerBridge.boot_transformers(model_name, device=device) # type: ignore[attr-defined]
1054 # Load HF model with same attn_implementation as bridge model (if specified)
1055 # This ensures numerical consistency between bridge and HF models
1056 hf_kwargs = {"device_map": device}
1057 if (
1058 hasattr(bridge_model.adapter.cfg, "attn_implementation")
1059 and bridge_model.adapter.cfg.attn_implementation is not None
1060 ):
1061 hf_kwargs["attn_implementation"] = bridge_model.adapter.cfg.attn_implementation
1063 hf_model = AutoModelForCausalLM.from_pretrained(model_name, **hf_kwargs)
1065 # Set models to eval mode (disable dropout, etc.)
1066 bridge_model.eval()
1067 hf_model.eval()
1069 # Get adapter
1070 adapter = bridge_model.adapter
1072 # Set up component testing (e.g., sync rotary_emb references for Gemma-3)
1073 # Pass bridge_model so adapter can set up actual bridge instances, not just templates
1074 adapter.setup_component_testing(hf_model, bridge_model=bridge_model)
1076 # Create benchmarker
1077 benchmarker = ComponentBenchmarker(
1078 bridge_model=bridge_model,
1079 hf_model=hf_model,
1080 adapter=adapter,
1081 cfg=bridge_model.cfg,
1082 atol=atol,
1083 rtol=rtol,
1084 )
1086 # Run benchmark
1087 print("Running component benchmark...")
1088 report = benchmarker.benchmark_all_components(skip_components=skip_components)
1090 # Print report
1091 report.print_summary(verbose=verbose)
1093 return report