Coverage for transformer_lens/benchmarks/component_benchmark.py: 39%
36 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"""Component-level benchmarks to compare individual model pieces.
3This module provides benchmarks for comparing individual model components
4(attention, MLP, embedding, etc.) between HuggingFace and TransformerBridge.
5"""
7from typing import Any, Optional
9from transformer_lens.benchmarks.component_outputs import ComponentBenchmarker
10from transformer_lens.benchmarks.utils import BenchmarkResult, BenchmarkSeverity
13def benchmark_all_components(
14 bridge,
15 hf_model,
16 atol: float = 1e-4,
17 rtol: float = 1e-4,
18 reference_model: Optional[Any] = None,
19) -> BenchmarkResult:
20 """Comprehensive benchmark of all model components.
22 This function systematically tests every component in the model using the
23 architecture adapter to find and compare equivalent components.
25 Args:
26 bridge: The TransformerBridge model
27 hf_model: The HuggingFace model to compare against
28 atol: Absolute tolerance for comparison
29 rtol: Relative tolerance for comparison
30 reference_model: Optional reference model (unused, for API consistency)
32 Returns:
33 BenchmarkResult summarizing all component tests
34 """
35 try:
36 # Set up component testing (e.g., sync rotary_emb references for Gemma models, eager attention)
37 # This must be called before creating the ComponentBenchmarker
38 bridge.adapter.setup_component_testing(hf_model, bridge_model=bridge)
40 # Create benchmarker
41 benchmarker = ComponentBenchmarker(
42 bridge_model=bridge,
43 hf_model=hf_model,
44 adapter=bridge.adapter,
45 cfg=bridge.cfg,
46 atol=atol,
47 rtol=rtol,
48 )
50 # Skip modality towers for multimodal models — they require image or
51 # audio inputs that isolated text-based component testing cannot
52 # provide. Vision components are validated separately in Phase 7.
53 skip_components = []
54 if getattr(bridge.cfg, "is_multimodal", False): 54 ↛ 55line 54 didn't jump to line 55 because the condition on line 54 was never true
55 skip_components = [
56 "vision_encoder",
57 "vision_projector",
58 "audio_encoder",
59 "audio_projector",
60 ]
61 if getattr(bridge.cfg, "is_audio_model", False):
62 # Audio preprocessing needs waveform input; validated in Phase 8
63 skip_components.extend(["audio_feature_extractor", "feat_proj", "conv_pos_embed"])
64 if getattr(bridge.cfg, "is_audio_seq2seq", False):
65 # Channel-first spectrogram convs; covered end to end by the forward pass
66 skip_components.extend(["conv1", "conv2"])
68 # Run comprehensive benchmark
69 report = benchmarker.benchmark_all_components(skip_components=skip_components)
71 # Convert to BenchmarkResult format
72 if report.failed_components == 0: 72 ↛ 86line 72 didn't jump to line 86 because the condition on line 72 was always true
73 return BenchmarkResult(
74 name="all_components",
75 severity=BenchmarkSeverity.INFO,
76 passed=True,
77 message=f"All {report.total_components} components produce equivalent outputs",
78 details={
79 "total_components": report.total_components,
80 "pass_rate": report.pass_rate,
81 "component_types": report.get_component_type_summary(),
82 },
83 )
84 else:
85 # Get failure details
86 failures_by_severity = report.get_failure_by_severity()
88 # Determine overall severity
89 if failures_by_severity["critical"]:
90 severity = BenchmarkSeverity.ERROR
91 elif failures_by_severity["high"]:
92 severity = BenchmarkSeverity.DANGER
93 else:
94 severity = BenchmarkSeverity.WARNING
96 # Create failure message
97 failure_summary = []
98 for sev in ["critical", "high", "medium", "low"]:
99 count = len(failures_by_severity[sev])
100 if count > 0:
101 failure_summary.append(f"{count} {sev}")
103 message = (
104 f"{report.failed_components}/{report.total_components} components failed "
105 f"({', '.join(failure_summary)})"
106 )
108 # Collect failed component details
109 failed_details = {}
110 for result in report.component_results:
111 if not result.passed:
112 failed_details[result.component_path] = {
113 "max_diff": result.max_diff,
114 "mean_diff": result.mean_diff,
115 "severity": result.get_failure_severity(),
116 "error": result.error_message,
117 }
119 return BenchmarkResult(
120 name="all_components",
121 passed=False,
122 severity=severity,
123 message=message,
124 details={
125 "total_components": report.total_components,
126 "passed_components": report.passed_components,
127 "failed_components": report.failed_components,
128 "pass_rate": report.pass_rate,
129 "failures": failed_details,
130 },
131 )
133 except Exception as e:
134 return BenchmarkResult(
135 name="all_components",
136 passed=False,
137 severity=BenchmarkSeverity.ERROR,
138 message=f"Error running comprehensive component benchmark: {str(e)}",
139 details={"exception": str(e)},
140 )