Coverage for transformer_lens/benchmarks/main_benchmark.py: 37%
896 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"""Main benchmark runner for TransformerBridge.
3This module provides the main benchmark suite that compares TransformerBridge
4against reference implementations in an optimized multi-phase approach:
5Phase 1: HF + Bridge (unprocessed) - Compare against raw HuggingFace model
6Phase 2: Bridge (unprocessed) - Runtime self-checks + HF logits/loss equivalence
7Phase 3: Bridge (processed) - Compatibility mode + HF logits/loss equivalence
8Phase 4: Text Quality - profile prompts scored by a pinned judge's perplexity ratio
9Phase 5: Granular Weight Processing Tests (optional, individual flags)
10Phase 6: Granular Weight Processing Tests (optional, combined flags)
11Phase 7: Multimodal Tests (only for multimodal models with pixel_values support)
12Phase 8: Audio Tests (only for audio encoder models / audio-conditioned decoders)
13Phase 9: Vision Tests (only for vision-only encoder models, e.g. ViT/DeiT)
14"""
16import gc
17from typing import Dict, List, Optional, Union
19import torch
20from transformers import (
21 AutoConfig,
22 AutoModelForCausalLM,
23 PreTrainedModel,
24 PreTrainedTokenizerBase,
25)
27from transformer_lens.benchmarks.activation_cache import (
28 benchmark_activation_cache,
29 benchmark_run_with_cache,
30)
31from transformer_lens.benchmarks.backward_gradients import (
32 benchmark_backward_hooks,
33 benchmark_critical_backward_hooks,
34 benchmark_gradient_computation,
35 needs_fp32_gradients,
36)
37from transformer_lens.benchmarks.component_benchmark import benchmark_all_components
38from transformer_lens.benchmarks.forward_pass import (
39 _compute_self_target_loss,
40 _get_decoder_input_ids,
41 benchmark_forward_pass,
42 benchmark_loss_equivalence,
43)
44from transformer_lens.benchmarks.generation import (
45 benchmark_generation,
46 benchmark_generation_with_kv_cache,
47 benchmark_multiple_generation_calls,
48)
49from transformer_lens.benchmarks.hook_registration import (
50 benchmark_critical_forward_hooks,
51 benchmark_forward_hooks,
52 benchmark_gated_hooks_fire,
53 benchmark_hook_functionality,
54 benchmark_hook_registry,
55)
56from transformer_lens.benchmarks.text_quality import benchmark_text_quality
57from transformer_lens.benchmarks.utils import (
58 BenchmarkResult,
59 BenchmarkSeverity,
60 PhaseReferenceData,
61 build_modality_input,
62 compare_tensors,
63 format_results,
64)
65from transformer_lens.benchmarks.weight_processing import (
66 benchmark_attention_output_centering,
67 benchmark_layer_norm_folding,
68 benchmark_mlp_output_centering,
69 benchmark_no_nan_inf,
70 benchmark_unembed_centering,
71 benchmark_value_bias_folding,
72 benchmark_weight_magnitudes,
73 benchmark_weight_modification,
74)
75from transformer_lens.config import TransformerBridgeConfig
76from transformer_lens.factories.architecture_adapter_factory import (
77 ArchitectureAdapterFactory,
78)
79from transformer_lens.model_bridge import TransformerBridge
80from transformer_lens.tools.model_registry.registry_io import TEXT_PHASES
82# Architecture classification — single source of truth in utilities.architectures
83from transformer_lens.utilities.architectures import (
84 get_architectures_for_config,
85 is_audio_model,
86 is_encoder_decoder_model,
87 is_masked_lm_model,
88)
89from transformer_lens.utilities.hf_utils import get_hf_token as _hf_token
92def _adapter_applicable_phases(model_name: str, trust_remote_code: bool = False) -> list[int]:
93 """Text phases (1-4) the model's adapter declares applicable (default all)."""
94 from transformer_lens.factories.architecture_adapter_factory import (
95 SUPPORTED_ARCHITECTURES,
96 )
98 try:
99 config = AutoConfig.from_pretrained(
100 model_name, trust_remote_code=trust_remote_code, token=_hf_token()
101 )
102 for arch in get_architectures_for_config(config):
103 adapter_cls = SUPPORTED_ARCHITECTURES.get(arch)
104 if adapter_cls is not None:
105 return getattr(adapter_cls, "applicable_phases", list(TEXT_PHASES))
106 except Exception:
107 pass
108 return list(TEXT_PHASES)
111def _phase_enabled(
112 phase_num: int, phases: Optional[List[int]], applicable_phases: List[int]
113) -> bool:
114 """Phase gating shared by run_benchmark_suite's should_run_phase.
116 An adapter's ``applicable_phases`` declares which text phases (1-4) it covers.
117 Phases 7/8/9 are gated separately by ``is_multimodal``/``is_audio_model``/
118 ``is_visual_model`` at their call sites, so they are never filtered out here
119 (mirrors verify_models._phases_to_run).
120 """
121 if phases is not None and phase_num not in phases:
122 return False
123 return phase_num not in TEXT_PHASES or phase_num in applicable_phases
126def get_auto_model_class(model_name: str, trust_remote_code: bool = False):
127 """Delegates to the bridge's architecture detection for consistency."""
128 from transformer_lens.model_bridge.sources.transformers import (
129 determine_architecture_from_hf_config,
130 get_hf_model_class_for_architecture,
131 )
133 try:
134 config = AutoConfig.from_pretrained(
135 model_name, trust_remote_code=trust_remote_code, token=_hf_token()
136 )
137 architecture = determine_architecture_from_hf_config(config)
138 return get_hf_model_class_for_architecture(architecture)
139 except Exception:
140 return AutoModelForCausalLM
143def _fixup_custom_model(hf_model) -> None:
144 """Apply post-load fixups for models with custom code (e.g., OpenELM).
146 Recomputes non-persistent buffers (inv_freq, causal_mask) that may be
147 zeroed during HuggingFace's meta-device loading.
148 """
149 # OpenELM fixups
150 if hasattr(hf_model, "transformer") and hasattr(hf_model.transformer, "layers"): 150 ↛ 152line 150 didn't jump to line 152 because the condition on line 150 was never true
151 # Ensure use_cache is set (OpenELM custom config omits it)
152 if not hasattr(hf_model.config, "use_cache") or "use_cache" not in hf_model.config.__dict__:
153 hf_model.config.use_cache = False
155 # Fix 1: Always recompute causal_mask (non-persistent buffer).
156 # After meta→real materialization, the buffer may contain garbage values
157 # rather than clean zeros, so we always recompute.
158 if hasattr(hf_model.transformer, "causal_mask"):
159 cm = hf_model.transformer.causal_mask
160 if cm is not None and cm.numel() > 0:
161 seq_len = cm.shape[-1]
162 correct_mask = torch.triu(
163 torch.ones(seq_len, seq_len, dtype=cm.dtype, device=cm.device),
164 diagonal=1,
165 )
166 hf_model.transformer.causal_mask = correct_mask
168 # Fix 2: Always recompute RoPE inv_freq and sin/cos (non-persistent buffers).
169 rope_max = getattr(hf_model.config, "rope_max_length", None)
170 if rope_max is not None:
171 for layer in hf_model.transformer.layers:
172 if hasattr(layer, "attn") and hasattr(layer.attn, "pos_embedding"):
173 rope = layer.attn.pos_embedding
174 if hasattr(rope, "inv_freq"):
175 correct_inv_freq = 1.0 / (
176 rope.freq_constant
177 ** (
178 torch.arange(0, rope.model_dim, 2, dtype=torch.float32)
179 / rope.model_dim
180 )
181 )
182 rope.inv_freq = correct_inv_freq.to(rope.inv_freq.device)
183 # Force-recompute sin/cos
184 rope._cached_cos = None
185 rope._cached_sin = None
186 rope._compute_sin_cos_embeddings(rope_max)
188 # Create synthetic lm_head for weight-tied models (share_input_output_layers)
189 if getattr(hf_model, "lm_head", None) is None:
190 embed = hf_model.transformer.token_embeddings
191 lm_head = torch.nn.Linear(embed.embedding_dim, embed.num_embeddings, bias=False)
192 lm_head.weight = embed.weight
193 hf_model.lm_head = lm_head
195 # Rotary tables destroyed by meta-device loading, for ANY architecture: the
196 # reference needs the same repair the adapter applies to the bridge, or
197 # Phase 1 compares a correct model against a corrupt one. Only tables that
198 # fail a validity check are touched, so scaled RoPE is never clobbered.
199 from transformer_lens.model_bridge.buffer_restore import restore_rotary_inv_freq
201 restore_rotary_inv_freq(hf_model)
203 if type(hf_model).__name__ == "GiddForDiffusionLM": 203 ↛ 204line 203 didn't jump to line 204 because the condition on line 203 was never true
204 from transformer_lens.model_bridge.supported_architectures.gidd import (
205 restore_frequencies,
206 )
208 restore_frequencies(hf_model)
211def _hf_forward_with_mask_fallback(hf_model, tokens):
212 """Run an HF decoder forward, retrying with a 2D then 4D mask for models that
213 dereference ``attention_mask`` unconditionally (e.g. LLaDA2) -- else the Phase-1
214 capture raises, gets swallowed, and silently degrades to a shape-only check."""
215 try:
216 return hf_model(tokens)
217 except (AttributeError, ValueError):
218 b, s = tokens.shape[0], tokens.shape[-1]
219 for mask in (
220 torch.ones(b, s, dtype=torch.long, device=tokens.device),
221 torch.ones(b, 1, s, s, dtype=torch.long, device=tokens.device),
222 ):
223 try:
224 return hf_model(tokens, attention_mask=mask)
225 except (AttributeError, ValueError):
226 continue
227 raise
230def run_comparison_benchmarks(
231 bridge_model: TransformerBridge,
232 test_text: str,
233 phase_name: str,
234 is_processed: bool,
235 verbose: bool = True,
236 phase1_reference: Optional[PhaseReferenceData] = None,
237 restore_dtype_after_equivalence: Optional[torch.dtype] = None,
238) -> List[BenchmarkResult]:
239 """Run standardized runtime benchmarks on the bridge.
241 This function runs the same comprehensive test suite for both unprocessed (Phase 2)
242 and processed (Phase 3) modes: HF-anchored logits/loss equivalence (via the saved
243 Phase 1 reference) plus reference-free structural self-checks for hooks, cache,
244 and gradients.
246 Args:
247 bridge_model: TransformerBridge model to test
248 test_text: Input text for testing
249 phase_name: Name of the phase ("Phase 2" or "Phase 3") for logging
250 is_processed: Whether models have processed weights (for weight-specific tests)
251 verbose: Whether to print detailed results
252 phase1_reference: Optional saved Phase 1 HF reference data for equivalence testing
253 restore_dtype_after_equivalence: If set, downcast bridge_model to this dtype after
254 the equivalence comparison but before hook/cache/gradient tests. Used when the
255 bridge was upcast to float32 for precise equivalence testing.
257 Returns:
258 List of BenchmarkResult objects
259 """
260 results: List[BenchmarkResult] = []
262 def add_result(result: BenchmarkResult) -> None:
263 """Add a result and optionally print it immediately."""
264 results.append(result)
265 if verbose: 265 ↛ 266line 265 didn't jump to line 266 because the condition on line 265 was never true
266 result.print_immediate()
268 # ========================================================================
269 # 1. Weight Processing Benchmarks (only for processed mode)
270 # MOST BASIC: Check weights are valid before testing anything else
271 # ========================================================================
272 if is_processed: 272 ↛ 273line 272 didn't jump to line 273 because the condition on line 272 was never true
273 if verbose:
274 print("1. Weight Processing Benchmarks (Foundation)")
275 try:
276 # Critical weight validation tests (run first - most basic)
277 add_result(benchmark_no_nan_inf(bridge_model, test_text))
278 add_result(benchmark_weight_magnitudes(bridge_model, test_text))
280 # Detailed weight processing validation benchmarks (don't need reference model)
281 add_result(benchmark_layer_norm_folding(bridge_model, test_text))
282 add_result(benchmark_attention_output_centering(bridge_model, test_text))
283 add_result(benchmark_mlp_output_centering(bridge_model, test_text))
284 add_result(benchmark_unembed_centering(bridge_model, test_text))
285 add_result(benchmark_value_bias_folding(bridge_model, test_text))
287 # weight_modification doesn't need a reference model
288 add_result(benchmark_weight_modification(bridge_model, test_text))
289 gc.collect()
290 except Exception as e:
291 if verbose:
292 print(f"✗ Weight processing benchmark failed: {e}\n")
294 # ========================================================================
295 # 2. Model Equivalence Benchmarks (Forward Pass)
296 # Tests basic forward computation - depends on weights being correct
297 # ========================================================================
298 if verbose: 298 ↛ 299line 298 didn't jump to line 299 because the condition on line 298 was never true
299 print("2. Model Equivalence Benchmarks (Forward Pass)")
301 has_phase1_ref = phase1_reference is not None and phase1_reference.hf_logits is not None
303 if has_phase1_ref: 303 ↛ 358line 303 didn't jump to line 358 because the condition on line 303 was always true
304 # Compare the bridge against the saved Phase 1 HF reference.
305 # We use log_softmax because center_unembed shifts raw logits by a
306 # softmax-invariant constant. Both passes run in float32 (no bf16 round-trip).
307 try:
308 if verbose: 308 ↛ 309line 308 didn't jump to line 309 because the condition on line 308 was never true
309 print("Using saved Phase 1 bridge reference for equivalence comparison")
311 assert phase1_reference is not None
312 assert phase1_reference.hf_logits is not None
314 # Compare log_softmax (centering-invariant) instead of raw logits.
315 bridge_logits = bridge_model(test_text, return_type="logits")
316 ref_logits = phase1_reference.hf_logits.to(bridge_logits.device)
317 bridge_log_probs = torch.nn.functional.log_softmax(bridge_logits, dim=-1)
318 ref_log_probs = torch.nn.functional.log_softmax(ref_logits, dim=-1)
320 # Both passes in float32 — remaining error is float32 non-associativity
321 # in weight processing (~0.006 max_diff on 24-layer Qwen2).
322 logits_atol = 0.01
323 logits_rtol = 1e-4
324 loss_atol = 1e-3
326 add_result(
327 compare_tensors(
328 bridge_log_probs,
329 ref_log_probs,
330 atol=logits_atol,
331 rtol=logits_rtol,
332 name="logits_equivalence",
333 )
334 )
335 if phase1_reference.hf_loss is not None: 335 ↛ 345line 335 didn't jump to line 345 because the condition on line 335 was always true
336 add_result(
337 benchmark_loss_equivalence(
338 bridge_model,
339 test_text,
340 reference_loss=phase1_reference.hf_loss,
341 atol=loss_atol,
342 )
343 )
344 else:
345 add_result(
346 BenchmarkResult(
347 name="loss_equivalence",
348 severity=BenchmarkSeverity.SKIPPED,
349 message="Skipped (no Phase 1 loss reference available)",
350 passed=True,
351 )
352 )
353 gc.collect()
354 except Exception as e:
355 if verbose:
356 print(f"✗ Phase 1 reference comparison failed: {e}\n")
357 else:
358 if verbose:
359 print("⏭️ Skipped (no Phase 1 HF reference)\n")
360 for benchmark_name in ["logits_equivalence", "loss_equivalence"]:
361 add_result(
362 BenchmarkResult(
363 name=benchmark_name,
364 severity=BenchmarkSeverity.SKIPPED,
365 message="Skipped (no Phase 1 HF reference available)",
366 passed=True,
367 )
368 )
370 # Restore native dtype so remaining tests run in the model's real dtype.
371 if restore_dtype_after_equivalence is not None: 371 ↛ 372line 371 didn't jump to line 372 because the condition on line 371 was never true
372 try:
373 bridge_model.to(restore_dtype_after_equivalence)
374 if verbose:
375 print(f" (restored to {restore_dtype_after_equivalence} for remaining tests)\n")
376 except Exception as e:
377 if verbose:
378 print(f"⚠ Could not restore dtype: {e}\n")
380 # ========================================================================
381 # 3. Hook Registration Benchmarks
382 # Tests hooks exist and are registered - depends on model structure
383 # ========================================================================
384 if verbose: 384 ↛ 385line 384 didn't jump to line 385 because the condition on line 384 was never true
385 print("3. Hook Registration Benchmarks")
387 try:
388 add_result(benchmark_hook_registry(bridge_model))
389 gc.collect()
390 except Exception as e:
391 if verbose:
392 print(f"✗ Hook registry benchmark failed: {e}\n")
394 # ========================================================================
395 # 4. Forward Hook Functionality Benchmarks
396 # Tests hooks fire and produce correct values - depends on forward pass + hooks
397 # ========================================================================
398 if verbose: 398 ↛ 399line 398 didn't jump to line 399 because the condition on line 398 was never true
399 print("4. Forward Hook Functionality Benchmarks")
401 try:
402 add_result(benchmark_hook_functionality(bridge_model, test_text))
403 add_result(benchmark_critical_forward_hooks(bridge_model, test_text))
404 add_result(benchmark_forward_hooks(bridge_model, test_text))
405 add_result(benchmark_gated_hooks_fire(bridge_model, test_text))
406 # Reset hooks to prevent handle leaks
407 if hasattr(bridge_model, "reset_hooks"): 407 ↛ 409line 407 didn't jump to line 409 because the condition on line 407 was always true
408 bridge_model.reset_hooks()
409 gc.collect()
410 except Exception as e:
411 if verbose:
412 print(f"✗ Forward hook benchmark failed: {e}\n")
414 # ========================================================================
415 # 5. Activation Cache Benchmarks
416 # Tests caching mechanism - depends on forward pass + hooks working
417 # ========================================================================
418 if verbose: 418 ↛ 419line 418 didn't jump to line 419 because the condition on line 418 was never true
419 print("5. Activation Cache Benchmarks")
421 try:
422 add_result(benchmark_run_with_cache(bridge_model, test_text))
423 add_result(benchmark_activation_cache(bridge_model, test_text))
424 # Reset hooks to prevent handle leaks
425 if hasattr(bridge_model, "reset_hooks"): 425 ↛ 427line 425 didn't jump to line 427 because the condition on line 425 was always true
426 bridge_model.reset_hooks()
427 gc.collect()
428 except Exception as e:
429 if verbose:
430 print(f"✗ Activation cache benchmark failed: {e}\n")
432 # ========================================================================
433 # 6. Backward Gradient Benchmarks
434 # MOST COMPLEX: Tests gradients and backward hooks - depends on everything above
435 # ========================================================================
436 if verbose: 436 ↛ 437line 436 didn't jump to line 437 because the condition on line 436 was never true
437 print("6. Backward Gradient Benchmarks")
439 # Gradient comparisons are graded against fp32-calibrated thresholds
440 # (REL_L2_TOLERANCE): bf16's rounding floor alone is ~2e-3 rel_l2, inside the
441 # measured bug band, so reduced-precision gradients cannot be graded at all.
442 # Upcast for the gradient section on every device (MPS additionally lacks
443 # bf16 autograd), then restore below.
444 bridge_grad_dtype = bridge_model.cfg.dtype if hasattr(bridge_model, "cfg") else None
445 grad_fp32_upcast = needs_fp32_gradients(bridge_grad_dtype)
446 if grad_fp32_upcast: 446 ↛ 447line 446 didn't jump to line 447 because the condition on line 446 was never true
447 try:
448 bridge_model.to(torch.float32)
449 except Exception:
450 grad_fp32_upcast = False # Upcast failed; proceed as-is
452 try:
453 add_result(benchmark_gradient_computation(bridge_model, test_text))
454 add_result(benchmark_critical_backward_hooks(bridge_model, test_text))
455 add_result(benchmark_backward_hooks(bridge_model, test_text))
456 # Reset hooks to prevent handle leaks
457 if hasattr(bridge_model, "reset_hooks"): 457 ↛ 459line 457 didn't jump to line 459 because the condition on line 457 was always true
458 bridge_model.reset_hooks()
459 gc.collect()
460 except Exception as e:
461 if verbose:
462 print(f"✗ Gradient benchmark failed: {e}\n")
464 if grad_fp32_upcast and bridge_grad_dtype is not None: 464 ↛ 465line 464 didn't jump to line 465 because the condition on line 464 was never true
465 try:
466 bridge_model.to(bridge_grad_dtype)
467 except Exception:
468 pass
470 return results
473def run_benchmark_suite(
474 model_name: str,
475 device: str = "cpu",
476 dtype: torch.dtype = torch.float32,
477 test_text: Optional[str] = None,
478 use_hf_reference: bool = True,
479 enable_compatibility_mode: bool = True,
480 verbose: bool = True,
481 track_memory: bool = False,
482 phases: list[int] | None = None,
483 trust_remote_code: bool = False,
484 judge_model: PreTrainedModel | None = None,
485 judge_tokenizer: PreTrainedTokenizerBase | None = None,
486 prompt_profile: str | None = None,
487) -> List[BenchmarkResult]:
488 """Run comprehensive benchmark suite for TransformerBridge.
490 This function implements an optimized multi-phase approach to minimize model reloading:
491 Phase 1: HF + Bridge (unprocessed) - Compare against raw HuggingFace model
492 Phase 2: Bridge (unprocessed) - Runtime self-checks + HF logits/loss equivalence
493 Phase 3: Bridge (processed) - Compatibility mode + HF logits/loss equivalence
494 Phase 4: Text Quality - profile prompts scored by a pinned judge's perplexity ratio
496 Args:
497 model_name: Name of the model to benchmark (e.g., "gpt2")
498 device: Device to run on ("cpu" or "cuda")
499 dtype: Precision for model loading (default: torch.float32). Use
500 torch.bfloat16 to halve memory for larger models. Phase 2/3
501 comparisons automatically upcast to float32 for precision.
502 test_text: Optional test text (default: standard test prompt)
503 use_hf_reference: Whether to compare against HuggingFace model
504 enable_compatibility_mode: Whether to enable compatibility mode on bridge
505 verbose: Whether to print results to console
506 track_memory: Whether to track and report memory usage (requires psutil)
507 phases: Optional list of phase numbers to run (e.g., [1, 2, 3]). If None, runs all phases.
508 trust_remote_code: Whether to trust remote code for custom architectures.
509 judge_model: Optional pre-loaded Phase-4 judge. When provided with
510 judge_tokenizer, avoids reloading for each model in batch.
511 judge_tokenizer: Optional pre-loaded tokenizer for the Phase-4 judge.
512 prompt_profile: Optional Phase-4 prompt profile (e.g. "chat",
513 "task:translation@en-de"). Resolved from curation + the registry
514 when None.
516 Returns:
517 List of BenchmarkResult objects
518 """
519 if test_text is None: 519 ↛ 526line 519 didn't jump to line 526 because the condition on line 519 was always true
520 test_text = (
521 "Natural language processing tasks, such as question answering, "
522 "machine translation, reading comprehension, and summarization, "
523 "are typically approached with supervised learning."
524 )
526 results: List[BenchmarkResult] = []
528 # Memory tracking setup
529 memory_tracker = None
530 if track_memory: 530 ↛ 531line 530 didn't jump to line 531 because the condition on line 530 was never true
531 try:
532 import psutil
534 process = psutil.Process()
535 initial_memory = process.memory_info().rss / 1024 / 1024 # MB
537 def get_memory_mb():
538 return process.memory_info().rss / 1024 / 1024
540 memory_tracker = {"initial": initial_memory, "checkpoints": []}
541 if verbose:
542 print(f"Memory tracking enabled (initial: {initial_memory:.1f} MB)")
543 except ImportError:
544 if verbose:
545 print("⚠ psutil not available - memory tracking disabled")
546 track_memory = False
548 if verbose: 548 ↛ 549line 548 didn't jump to line 549 because the condition on line 548 was never true
549 print(f"\n{'='*80}")
550 print(f"Running TransformerBridge Benchmark Suite")
551 print(f"Model: {model_name}")
552 print(f"Device: {device}")
553 print(f"{'='*80}\n")
555 # Track current phase for result tagging
556 current_phase: List[Optional[int]] = [None] # Use list to allow modification in nested function
558 adapter_applicable = _adapter_applicable_phases(model_name, trust_remote_code)
560 def should_run_phase(phase_num: int) -> bool:
561 """Check if a phase should run based on the phases filter and adapter applicability."""
562 return _phase_enabled(phase_num, phases, adapter_applicable)
564 def add_result(result: BenchmarkResult) -> None:
565 """Add a result and optionally print it immediately."""
566 # Tag result with current phase
567 if current_phase[0] is not None and result.phase is None: 567 ↛ 569line 567 didn't jump to line 569 because the condition on line 567 was always true
568 result.phase = current_phase[0]
569 results.append(result)
570 if verbose: 570 ↛ 571line 570 didn't jump to line 571 because the condition on line 570 was never true
571 result.print_immediate()
573 def cleanup_tensors(*tensors) -> None:
574 """Free memory from tensors and caches."""
575 for tensor in tensors:
576 if tensor is not None:
577 # If it's an ActivationCache, clear all tensors
578 if hasattr(tensor, "cache_dict"):
579 for key in list(tensor.cache_dict.keys()):
580 val = tensor.cache_dict[key]
581 if val is not None and isinstance(val, torch.Tensor):
582 del val
583 tensor.cache_dict[key] = None
584 tensor.cache_dict.clear()
585 # If it's a regular tensor, just delete it
586 elif isinstance(tensor, torch.Tensor):
587 del tensor
588 # Force cleanup
589 gc.collect()
590 if device != "cpu" and torch.cuda.is_available():
591 torch.cuda.empty_cache()
592 if device == "mps" and hasattr(torch, "mps") and hasattr(torch.mps, "empty_cache"):
593 torch.mps.synchronize()
594 torch.mps.empty_cache()
596 def cleanup_model(model, model_name_str: str):
597 """Free up memory by deleting a model and forcing garbage collection."""
598 import gc
600 if verbose: 600 ↛ 601line 600 didn't jump to line 601 because the condition on line 600 was never true
601 print(f"Cleaning up {model_name_str}...")
603 # Track memory before cleanup
604 if track_memory and memory_tracker is not None: 604 ↛ 605line 604 didn't jump to line 605 because the condition on line 604 was never true
605 memory_before = get_memory_mb()
607 # Move model to CPU first to free GPU memory immediately
608 if device != "cpu" and hasattr(model, "cpu"): 608 ↛ 609line 608 didn't jump to line 609 because the condition on line 608 was never true
609 try:
610 model.cpu()
611 if torch.cuda.is_available():
612 torch.cuda.empty_cache()
613 if hasattr(torch, "mps") and hasattr(torch.mps, "empty_cache"):
614 torch.mps.synchronize()
615 torch.mps.empty_cache()
616 except Exception:
617 pass
619 # Explicitly remove all hooks to prevent memory leaks
620 if hasattr(model, "modules"): 620 ↛ 656line 620 didn't jump to line 656 because the condition on line 620 was always true
621 try:
622 for module in model.modules():
623 # Clear PyTorch hooks
624 if hasattr(module, "_forward_hooks"): 624 ↛ 626line 624 didn't jump to line 626 because the condition on line 624 was always true
625 module._forward_hooks.clear()
626 if hasattr(module, "_backward_hooks"): 626 ↛ 628line 626 didn't jump to line 628 because the condition on line 626 was always true
627 module._backward_hooks.clear()
628 if hasattr(module, "_forward_pre_hooks"): 628 ↛ 630line 628 didn't jump to line 630 because the condition on line 628 was always true
629 module._forward_pre_hooks.clear()
630 if hasattr(module, "_backward_pre_hooks"): 630 ↛ 632line 630 didn't jump to line 632 because the condition on line 630 was always true
631 module._backward_pre_hooks.clear()
632 if hasattr(module, "_state_dict_hooks"): 632 ↛ 634line 632 didn't jump to line 634 because the condition on line 632 was always true
633 module._state_dict_hooks.clear()
634 if hasattr(module, "_state_dict_pre_hooks"): 634 ↛ 636line 634 didn't jump to line 636 because the condition on line 634 was always true
635 module._state_dict_pre_hooks.clear()
636 if hasattr(module, "_load_state_dict_pre_hooks"): 636 ↛ 638line 636 didn't jump to line 638 because the condition on line 636 was always true
637 module._load_state_dict_pre_hooks.clear()
638 if hasattr(module, "_load_state_dict_post_hooks"): 638 ↛ 642line 638 didn't jump to line 642 because the condition on line 638 was always true
639 module._load_state_dict_post_hooks.clear()
641 # Clear TransformerLens-specific hooks
642 if hasattr(module, "remove_all_hooks"): 642 ↛ 643line 642 didn't jump to line 643 because the condition on line 642 was never true
643 module.remove_all_hooks()
645 # Clear gradients
646 if hasattr(module, "zero_grad"): 646 ↛ 622line 646 didn't jump to line 622 because the condition on line 646 was always true
647 try:
648 module.zero_grad(set_to_none=True)
649 except Exception:
650 pass
651 except Exception:
652 # If hook cleanup fails, continue anyway
653 pass
655 # Clear top-level hooks
656 if hasattr(model, "_forward_hooks"): 656 ↛ 658line 656 didn't jump to line 658 because the condition on line 656 was always true
657 model._forward_hooks.clear()
658 if hasattr(model, "_backward_hooks"): 658 ↛ 660line 658 didn't jump to line 660 because the condition on line 658 was always true
659 model._backward_hooks.clear()
660 if hasattr(model, "_forward_pre_hooks"): 660 ↛ 664line 660 didn't jump to line 664 because the condition on line 660 was always true
661 model._forward_pre_hooks.clear()
663 # Clear top-level gradients
664 if hasattr(model, "zero_grad"): 664 ↛ 671line 664 didn't jump to line 671 because the condition on line 664 was always true
665 try:
666 model.zero_grad(set_to_none=True)
667 except Exception:
668 pass
670 # Break circular references to help GC
671 if hasattr(model, "_modules"): 671 ↛ 685line 671 didn't jump to line 685 because the condition on line 671 was always true
672 # Clear each submodule's __dict__ to break circular references
673 for name, submodule in list(model._modules.items()):
674 if submodule is not None: 674 ↛ 673line 674 didn't jump to line 673 because the condition on line 674 was always true
675 # Clear submodule hooks
676 if hasattr(submodule, "_forward_hooks"): 676 ↛ 678line 676 didn't jump to line 678 because the condition on line 676 was always true
677 submodule._forward_hooks.clear()
678 if hasattr(submodule, "_backward_hooks"): 678 ↛ 681line 678 didn't jump to line 681 because the condition on line 678 was always true
679 submodule._backward_hooks.clear()
680 # Break reference
681 model._modules[name] = None
682 model._modules.clear()
684 # Clear parameters dict
685 if hasattr(model, "_parameters"): 685 ↛ 694line 685 didn't jump to line 694 because the condition on line 685 was always true
686 for param_name in list(model._parameters.keys()): 686 ↛ 687line 686 didn't jump to line 687 because the loop on line 686 never started
687 param = model._parameters[param_name]
688 if param is not None:
689 del param
690 model._parameters[param_name] = None
691 model._parameters.clear()
693 # Clear buffers dict
694 if hasattr(model, "_buffers"): 694 ↛ 702line 694 didn't jump to line 702 because the condition on line 694 was always true
695 for buffer_name in list(model._buffers.keys()): 695 ↛ 696line 695 didn't jump to line 696 because the loop on line 695 never started
696 buffer = model._buffers[buffer_name]
697 if buffer is not None:
698 del buffer
699 model._buffers[buffer_name] = None
700 model._buffers.clear()
702 del model
704 # Aggressive garbage collection (multiple passes to break circular references)
705 for _ in range(3):
706 gc.collect()
708 # Clear GPU cache
709 if device != "cpu" and torch.cuda.is_available(): 709 ↛ 710line 709 didn't jump to line 710 because the condition on line 709 was never true
710 torch.cuda.empty_cache()
711 torch.cuda.synchronize()
712 if device == "mps" and hasattr(torch, "mps") and hasattr(torch.mps, "empty_cache"): 712 ↛ 713line 712 didn't jump to line 713 because the condition on line 712 was never true
713 torch.mps.synchronize()
714 torch.mps.empty_cache()
716 # Track memory after cleanup
717 if track_memory and memory_tracker is not None: 717 ↛ 718line 717 didn't jump to line 718 because the condition on line 717 was never true
718 memory_after = get_memory_mb()
719 freed_mb = memory_before - memory_after
720 memory_tracker["checkpoints"].append(
721 {
722 "label": f"Cleanup: {model_name_str}",
723 "memory_mb": memory_after,
724 "freed_mb": freed_mb,
725 }
726 )
727 if verbose and freed_mb > 0:
728 print(f" Freed {freed_mb:.1f} MB")
730 # ========================================================================
731 # PHASE 1: HuggingFace + Bridge (unprocessed)
732 # ========================================================================
733 current_phase[0] = 1
734 if verbose: 734 ↛ 735line 734 didn't jump to line 735 because the condition on line 734 was never true
735 print(f"\n{'='*80}")
736 print("PHASE 1: HuggingFace + TransformerBridge (unprocessed)")
737 print(f"{'='*80}\n")
739 bridge_unprocessed = None
740 hf_model = None
741 phase1_reference = PhaseReferenceData()
743 # Load bridge without weights first to detect attn_implementation and dtype
744 if verbose: 744 ↛ 745line 744 didn't jump to line 745 because the condition on line 744 was never true
745 print("Detecting model configuration...")
746 bridge_dtype = dtype
747 attn_implementation = None
748 try:
749 # Load a lightweight version without weights to get config
750 bridge_config_only = TransformerBridge.boot_transformers(model_name, device=device, dtype=bridge_dtype, load_weights=False, trust_remote_code=trust_remote_code) # type: ignore[attr-defined]
751 # Match bridge's attn_implementation: check adapter config first, then
752 # default to "eager" (bridge uses output_attentions=True which forces eager).
753 if hasattr(bridge_config_only.adapter.cfg, "attn_implementation"): 753 ↛ 755line 753 didn't jump to line 755 because the condition on line 753 was always true
754 attn_implementation = bridge_config_only.adapter.cfg.attn_implementation
755 if attn_implementation is None: 755 ↛ 757line 755 didn't jump to line 757 because the condition on line 755 was always true
756 attn_implementation = "eager"
757 if verbose: 757 ↛ 758line 757 didn't jump to line 758 because the condition on line 757 was never true
758 print(f"✓ Detected attn_implementation={attn_implementation}")
759 # Clean up config-only bridge immediately to free memory
760 del bridge_config_only
761 gc.collect()
762 except Exception as e:
763 if verbose:
764 print(f"⚠ Could not detect config (will use defaults): {str(e)}")
765 # Config-only bridge failed; apply architecture patches directly to prevent
766 # _init_weights from re-randomizing loaded weights.
767 if trust_remote_code:
768 try:
769 from transformer_lens.model_bridge.sources.transformers import (
770 determine_architecture_from_hf_config,
771 map_default_transformer_lens_config,
772 )
774 hf_cfg = AutoConfig.from_pretrained(
775 model_name, trust_remote_code=True, token=_hf_token()
776 )
777 tl_cfg = map_default_transformer_lens_config(hf_cfg)
778 arch = determine_architecture_from_hf_config(hf_cfg)
779 bridge_cfg = TransformerBridgeConfig.from_dict(tl_cfg.__dict__)
780 bridge_cfg.architecture = arch
781 bridge_cfg.model_name = model_name
782 adapter = ArchitectureAdapterFactory.select_architecture_adapter(bridge_cfg)
783 adapter.prepare_loading(model_name, {})
784 if verbose:
785 print("✓ Applied architecture patches for custom code model")
786 del adapter, bridge_cfg, tl_cfg, hf_cfg
787 except Exception as patch_err:
788 if verbose:
789 print(f"⚠ Could not apply architecture patches: {patch_err}")
791 hf_saved_logits = None
792 hf_saved_loss = None
794 if use_hf_reference and should_run_phase(1): 794 ↛ 869line 794 didn't jump to line 869 because the condition on line 794 was always true
795 try:
796 if verbose: 796 ↛ 797line 796 didn't jump to line 797 because the condition on line 796 was never true
797 print("Loading HuggingFace reference model...")
798 # Match bridge loading path: no device_map, explicit .to(device),
799 # and matching torch_dtype. When dtype=float32, loading in float32
800 # ensures non-persistent buffers (e.g., Gemma3's embed_scale) are
801 # computed at full precision. When dtype=bfloat16, both HF and
802 # Bridge load in bfloat16 so comparisons are apples-to-apples.
803 hf_kwargs: dict[str, object] = {
804 "low_cpu_mem_usage": True, # Reduce memory spikes during loading
805 "torch_dtype": dtype,
806 }
807 if _hf_token(): 807 ↛ 809line 807 didn't jump to line 809 because the condition on line 807 was always true
808 hf_kwargs["token"] = _hf_token()
809 if attn_implementation is not None: 809 ↛ 814line 809 didn't jump to line 814 because the condition on line 809 was always true
810 hf_kwargs["attn_implementation"] = attn_implementation
811 if verbose: 811 ↛ 812line 811 didn't jump to line 812 because the condition on line 811 was never true
812 print(f"Using attn_implementation={attn_implementation}")
813 # Use appropriate AutoModel class (e.g., AutoModelForSeq2SeqLM for T5)
814 auto_model_class = get_auto_model_class(model_name, trust_remote_code=trust_remote_code)
815 if verbose and auto_model_class != AutoModelForCausalLM: 815 ↛ 816line 815 didn't jump to line 816 because the condition on line 815 was never true
816 print(f"Using {auto_model_class.__name__}")
817 # Ensure pad_token_id exists (some models crash without it during init).
818 hf_config = AutoConfig.from_pretrained(
819 model_name, trust_remote_code=trust_remote_code, token=_hf_token()
820 )
821 if not hasattr(hf_config, "pad_token_id") or "pad_token_id" not in hf_config.__dict__: 821 ↛ 822line 821 didn't jump to line 822 because the condition on line 821 was never true
822 eos = getattr(hf_config, "eos_token_id", None)
823 hf_config.pad_token_id = eos[0] if isinstance(eos, (list, tuple)) else eos
824 hf_kwargs["config"] = hf_config
825 if trust_remote_code: 825 ↛ 826line 825 didn't jump to line 826 because the condition on line 825 was never true
826 hf_kwargs["trust_remote_code"] = True
827 hf_model = auto_model_class.from_pretrained(model_name, **hf_kwargs) # type: ignore[arg-type]
828 hf_model = hf_model.to(device)
829 # Post-load fixup for custom code models (e.g., OpenELM).
830 # Must run AFTER .to(device) so non-persistent buffers (RoPE sin/cos,
831 # causal_mask) are recomputed on the target device, matching the bridge
832 # which also recomputes after .to(device).
833 _fixup_custom_model(hf_model)
834 hf_model.eval()
835 # Detect dtype from HF model
836 try:
837 bridge_dtype = next(hf_model.parameters()).dtype
838 if verbose: 838 ↛ 839line 838 didn't jump to line 839 because the condition on line 838 was never true
839 print(f"Detected dtype={bridge_dtype}")
840 except StopIteration:
841 pass
842 # When float32 was requested but the model natively uses reduced
843 # precision, upcast for maximum benchmark accuracy. When dtype was
844 # explicitly set to bfloat16/float16 (e.g., to fit larger models in
845 # memory), respect it — both HF and Bridge will run in that precision.
846 if dtype == torch.float32 and bridge_dtype in (torch.float16, torch.bfloat16): 846 ↛ 847line 846 didn't jump to line 847 because the condition on line 846 was never true
847 if verbose:
848 print(f"⚠ {bridge_dtype} detected, upcasting to float32 for benchmarking...")
849 hf_model.to(torch.float32)
850 bridge_dtype = torch.float32
851 if verbose:
852 print("✓ Upcast to float32 in-place")
853 elif bridge_dtype != dtype: 853 ↛ 854line 853 didn't jump to line 854 because the condition on line 853 was never true
854 bridge_dtype = dtype # Trust the requested dtype
855 if verbose: 855 ↛ 856line 855 didn't jump to line 856 because the condition on line 855 was never true
856 print("✓ HuggingFace model loaded")
858 # HF reference logits will be captured AFTER the bridge is
859 # loaded so we can use bridge.to_tokens() for consistent
860 # tokenization (e.g. BOS prepending). This happens right
861 # after the component benchmark, while both models are still
862 # in memory, before the HF model is deleted.
864 except Exception as e:
865 if verbose:
866 print(f"✗ Could not load HuggingFace model: {str(e)}\n")
868 # Now load the full bridge with correct dtype (GPU is mostly free)
869 if verbose: 869 ↛ 870line 869 didn't jump to line 870 because the condition on line 869 was never true
870 print("Loading TransformerBridge (unprocessed)...")
871 try:
872 bridge_unprocessed = TransformerBridge.boot_transformers(model_name, device=device, dtype=bridge_dtype, trust_remote_code=trust_remote_code) # type: ignore[attr-defined]
873 if verbose: 873 ↛ 874line 873 didn't jump to line 874 because the condition on line 873 was never true
874 print("✓ TransformerBridge loaded (unprocessed)\n")
875 # Apply the adapter's prepare_model() to the HF reference model so
876 # both bridge and reference have the same fixups (e.g., weight tying).
877 # This keeps model-specific logic in the adapter, not the benchmark.
878 if hf_model is not None and hasattr(bridge_unprocessed, "adapter"): 878 ↛ 898line 878 didn't jump to line 898 because the condition on line 878 was always true
879 bridge_unprocessed.adapter.prepare_model(hf_model)
880 except Exception as e:
881 import traceback
883 error_trace = traceback.format_exc()
884 add_result(
885 BenchmarkResult(
886 name="load_bridge_unprocessed",
887 severity=BenchmarkSeverity.ERROR,
888 message=f"Failed to load unprocessed TransformerBridge: {str(e)}",
889 passed=False,
890 )
891 )
892 if verbose:
893 print(f"✗ Failed to load TransformerBridge: {str(e)}")
894 print(f"\nStack trace:\n{error_trace}")
895 return results
897 # Detect audio/vision models once for use across all phases
898 _is_audio = bridge_unprocessed is not None and getattr(
899 bridge_unprocessed.cfg, "is_audio_model", False
900 )
901 _is_visual = bridge_unprocessed is not None and getattr(
902 bridge_unprocessed.cfg, "is_visual_model", False
903 )
904 _is_audio_seq2seq = bridge_unprocessed is not None and getattr(
905 bridge_unprocessed.cfg, "is_audio_seq2seq", False
906 )
907 # Shared non-text input (spectrogram, waveform, or pixels) — the same tensor is used
908 # for the HF reference capture and the bridge forward so they stay comparable.
909 _test_modality_input = (
910 build_modality_input(bridge_unprocessed, device=device, dtype=dtype)
911 if (_is_audio or _is_visual)
912 else None
913 )
915 # Run Phase 1 benchmarks
916 if should_run_phase(1) and bridge_unprocessed: 916 ↛ 1102line 916 didn't jump to line 1102 because the condition on line 916 was always true
917 if verbose: 917 ↛ 918line 917 didn't jump to line 918 because the condition on line 917 was never true
918 print("Running Phase 1 benchmarks...\n")
920 # Component-level benchmarks
921 if verbose: 921 ↛ 922line 921 didn't jump to line 922 because the condition on line 921 was never true
922 print("1. Component-Level Benchmarks")
923 if hf_model is not None: 923 ↛ 1015line 923 didn't jump to line 1015 because the condition on line 923 was always true
924 # Full mode: component benchmark with independent HF model (brief 2.0x)
925 try:
926 component_result = benchmark_all_components(bridge_unprocessed, hf_model)
927 add_result(component_result)
928 if verbose: 928 ↛ 929line 928 didn't jump to line 929 because the condition on line 928 was never true
929 status = "✓" if component_result.passed else "✗"
930 print(f"{status} {component_result.message}\n")
931 gc.collect()
932 if device != "cpu" and torch.cuda.is_available(): 932 ↛ 933line 932 didn't jump to line 933 because the condition on line 932 was never true
933 torch.cuda.empty_cache()
934 if device == "mps" and hasattr(torch, "mps") and hasattr(torch.mps, "empty_cache"): 934 ↛ 935line 934 didn't jump to line 935 because the condition on line 934 was never true
935 torch.mps.synchronize()
936 torch.mps.empty_cache()
937 except Exception as e:
938 if verbose:
939 print(f"✗ Component benchmark failed: {e}\n")
941 # Capture HF reference outputs. Both models are still in memory (2.0x window).
942 if verbose: 942 ↛ 943line 942 didn't jump to line 943 because the condition on line 942 was never true
943 print("Capturing HF reference outputs to CPU...")
944 try:
945 if _test_modality_input is not None: 945 ↛ 947line 945 didn't jump to line 947 because the condition on line 945 was never true
946 # Audio/vision models: use the shared non-text input for HF vs bridge
947 with torch.no_grad():
948 if _is_visual:
949 hf_out = hf_model(pixel_values=_test_modality_input)
950 elif _is_audio_seq2seq:
951 dec_ids = _get_decoder_input_ids(
952 hf_model, _test_modality_input.shape[0]
953 ).to(_test_modality_input.device)
954 audio_kwargs = {
955 bridge_unprocessed.adapter.audio_input_name: _test_modality_input
956 }
957 hf_out = hf_model(**audio_kwargs, decoder_input_ids=dec_ids)
958 else:
959 hf_out = hf_model(input_values=_test_modality_input)
960 # Bare encoders output last_hidden_state, not logits
961 if hasattr(hf_out, "logits") and hf_out.logits is not None:
962 hf_saved_logits = hf_out.logits.detach().cpu().clone()
963 else:
964 hf_saved_logits = hf_out.last_hidden_state.detach().cpu().clone()
965 # No loss computation — there are no next-token labels here
966 if verbose:
967 kind = "vision" if _is_visual else "audio"
968 print(
969 f"✓ Captured HF {kind} output {hf_saved_logits.shape}, "
970 f"loss=N/A (no token labels)\n"
971 )
972 else:
973 hf_tokens = bridge_unprocessed.to_tokens(test_text)
974 is_enc_dec = is_encoder_decoder_model(
975 model_name, trust_remote_code=trust_remote_code
976 )
977 with torch.no_grad():
978 if is_enc_dec: 978 ↛ 979line 978 didn't jump to line 979 because the condition on line 978 was never true
979 decoder_start_id = getattr(
980 getattr(hf_model, "config", None),
981 "decoder_start_token_id",
982 0,
983 )
984 dec_ids = torch.tensor([[decoder_start_id]]).to(hf_tokens.device)
985 hf_out = hf_model(hf_tokens, decoder_input_ids=dec_ids)
986 else:
987 hf_out = _hf_forward_with_mask_fallback(hf_model, hf_tokens)
988 hf_saved_logits = hf_out.logits.detach().cpu().clone()
990 # Compute causal LM loss (shift logits and labels)
991 if not is_enc_dec and hf_saved_logits.shape[1] > 1: 991 ↛ 1000line 991 didn't jump to line 1000
992 shift_logits = hf_out.logits[..., :-1, :].contiguous()
993 shift_labels = hf_tokens[..., 1:].contiguous()
994 loss_fn = torch.nn.CrossEntropyLoss()
995 hf_saved_loss = loss_fn(
996 shift_logits.view(-1, shift_logits.size(-1)),
997 shift_labels.view(-1),
998 ).item()
1000 if verbose: 1000 ↛ 1001line 1000 didn't jump to line 1001 because the condition on line 1000 was never true
1001 loss_str = f"{hf_saved_loss:.4f}" if hf_saved_loss is not None else "N/A"
1002 print(
1003 f"✓ Captured HF logits {hf_saved_logits.shape}, " f"loss={loss_str}\n"
1004 )
1005 del hf_tokens
1006 except Exception as e:
1007 if verbose:
1008 print(f"⚠ Could not capture HF reference outputs: {e}\n")
1010 # Delete HF model immediately after component benchmark + logit capture.
1011 # From here on, Phase 1 runs at 1.0x using saved HF tensors.
1012 cleanup_model(hf_model, "HuggingFace model")
1013 hf_model = None
1014 else:
1015 if verbose:
1016 print("⏭️ Skipped (no HF reference model available)\n")
1018 # Forward pass benchmarks
1019 if verbose: 1019 ↛ 1020line 1019 didn't jump to line 1020 because the condition on line 1019 was never true
1020 print("2. Forward Pass Benchmarks")
1022 # Widen tolerance for reduced-precision benchmarking — MPS bfloat16
1023 # matmul non-determinism can exceed the float32 default of 1e-3
1024 p1_atol = 1e-3 if dtype == torch.float32 else 5e-3
1026 # For audio/vision models, reuse the input from HF reference capture
1027 _p1_input: Union[str, torch.Tensor] = test_text
1028 if _test_modality_input is not None: 1028 ↛ 1029line 1028 didn't jump to line 1029 because the condition on line 1028 was never true
1029 _p1_input = _test_modality_input
1031 if hf_saved_logits is not None: 1031 ↛ 1046line 1031 didn't jump to line 1046 because the condition on line 1031 was always true
1032 # Full mode: use pre-captured HF logits (bridge only, 1.0x)
1033 try:
1034 add_result(
1035 benchmark_forward_pass(
1036 bridge_unprocessed,
1037 _p1_input,
1038 reference_logits=hf_saved_logits.to(device),
1039 atol=p1_atol,
1040 )
1041 )
1042 except Exception as e:
1043 if verbose:
1044 print(f"✗ Forward pass benchmark failed: {e}\n")
1045 else:
1046 try:
1047 add_result(benchmark_forward_pass(bridge_unprocessed, _p1_input, atol=p1_atol))
1048 except Exception as e:
1049 if verbose:
1050 print(f"✗ Forward pass benchmark failed: {e}\n")
1052 # Capture Phase 1 reference for Phase 3 equivalence comparison.
1053 # Skip for audio/vision models (Phase 3 won't run — weight processing
1054 # unsupported — and the capture below feeds text, which they cannot accept).
1055 # When dtype==float32 (default) and the model natively uses reduced
1056 # precision, upcast for maximum accuracy. When the user explicitly
1057 # requested a non-float32 dtype, run the reference pass in that dtype
1058 # so the entire pipeline honours the requested precision.
1059 if bridge_unprocessed is not None and not _is_audio and not _is_visual: 1059 ↛ 1102line 1059 didn't jump to line 1102 because the condition on line 1059 was always true
1060 try:
1061 original_dtype = bridge_unprocessed.cfg.dtype
1062 needs_upcast = dtype == torch.float32 and original_dtype not in (
1063 torch.float32,
1064 torch.float64,
1065 )
1066 # Snapshot registered buffers before the round-trip. HF's
1067 # RotaryEmbedding recomputes inv_freq during the float32 forward
1068 # pass, and the downcast back to bfloat16 would produce different
1069 # values than the original, corrupting the model for Phase 2.
1070 saved_buffers = {}
1071 if needs_upcast: 1071 ↛ 1072line 1071 didn't jump to line 1072 because the condition on line 1071 was never true
1072 for bname, buf in bridge_unprocessed.named_buffers():
1073 saved_buffers[bname] = buf.data.clone()
1074 bridge_unprocessed.to(torch.float32)
1075 with torch.no_grad():
1076 bridge_logits = bridge_unprocessed(test_text, return_type="logits")
1077 phase1_reference.hf_logits = bridge_logits.detach().cpu().clone()
1078 bridge_loss = _compute_self_target_loss(bridge_unprocessed, test_text)
1079 phase1_reference.hf_loss = bridge_loss.item()
1080 phase1_reference.test_text = test_text
1081 if needs_upcast: 1081 ↛ 1082line 1081 didn't jump to line 1082 because the condition on line 1081 was never true
1082 bridge_unprocessed.to(original_dtype)
1083 # Restore buffers that were corrupted by the round-trip.
1084 # Use direct assignment (not copy_) to preserve original dtype.
1085 # HF's RotaryEmbedding keeps inv_freq in float32 even when the
1086 # model is bfloat16. After to(bfloat16), the buffer becomes
1087 # bfloat16, and copy_() would truncate the float32 saved values.
1088 for bname, buf in bridge_unprocessed.named_buffers():
1089 if bname in saved_buffers:
1090 buf.data = saved_buffers[bname]
1091 if verbose: 1091 ↛ 1092line 1091 didn't jump to line 1092 because the condition on line 1091 was never true
1092 dtype_note = " (upcast to float32)" if needs_upcast else ""
1093 print(
1094 f"✓ Saved Phase 1 reference data "
1095 f"(logits: {phase1_reference.hf_logits.shape}){dtype_note}"
1096 )
1097 except Exception as e:
1098 if verbose:
1099 print(f"⚠ Could not save Phase 1 reference data: {e}")
1101 # Free saved HF tensors now that Phase 1 is done
1102 del hf_saved_logits, hf_saved_loss
1104 # Save bridge_dtype before potential cleanup (needed for Phase 3)
1105 saved_bridge_dtype = bridge_dtype
1107 # Clean up HF model if still alive (e.g., Phase 1 was skipped)
1108 if hf_model is not None: 1108 ↛ 1109line 1108 didn't jump to line 1109 because the condition on line 1108 was never true
1109 cleanup_model(hf_model, "HuggingFace model")
1110 hf_model = None
1112 # ========================================================================
1113 # PHASE 2: Bridge (unprocessed) — runtime self-checks + HF equivalence
1114 # ========================================================================
1115 current_phase[0] = 2
1117 # OPTIMIZATION: Run generation benchmarks first (only bridge in memory).
1118 if should_run_phase(2) and bridge_unprocessed: 1118 ↛ 1206line 1118 didn't jump to line 1206 because the condition on line 1118 was always true
1119 if verbose: 1119 ↛ 1120line 1119 didn't jump to line 1120 because the condition on line 1119 was never true
1120 print(f"\n{'='*80}")
1121 print("PHASE 2: TransformerBridge (unprocessed) — runtime self-checks + HF equivalence")
1122 print(f"{'='*80}\n")
1123 if verbose: 1123 ↛ 1124line 1123 didn't jump to line 1124 because the condition on line 1123 was never true
1124 print("Running Phase 2 benchmarks...\n")
1126 # Generation benchmarks (unprocessed only) - RUN FIRST
1127 # Skip for encoder-decoder and audio models (no text generation capability)
1128 # Diffusion LMs generate through a native sampler; the benchmarks route
1129 # to it, so only architectures with neither path are skipped.
1130 _adapter = getattr(bridge_unprocessed, "adapter", None)
1131 _no_generate = not getattr(_adapter, "supports_generation", True) and not getattr(
1132 _adapter, "native_sampler", None
1133 )
1134 _skip_generation = (
1135 is_encoder_decoder_model(model_name)
1136 or getattr(bridge_unprocessed.cfg, "is_audio_model", False)
1137 or _no_generate
1138 )
1139 _skip_reason = (
1140 "Skipped (model does not support generation)"
1141 if _no_generate
1142 else "Skipped (encoder-decoder model)"
1143 )
1144 if verbose: 1144 ↛ 1145line 1144 didn't jump to line 1145 because the condition on line 1144 was never true
1145 print("1. Generation Benchmarks (unprocessed)")
1146 if _skip_generation: 1146 ↛ 1182line 1146 didn't jump to line 1182 because the condition on line 1146 was always true
1147 if verbose: 1147 ↛ 1148line 1147 didn't jump to line 1148 because the condition on line 1147 was never true
1148 print(f"⏭️ {_skip_reason}\n")
1149 add_result(
1150 BenchmarkResult(
1151 name="generation",
1152 severity=BenchmarkSeverity.INFO,
1153 passed=True,
1154 message=_skip_reason,
1155 )
1156 )
1157 add_result(
1158 BenchmarkResult(
1159 name="generation_with_kv_cache",
1160 severity=BenchmarkSeverity.INFO,
1161 passed=True,
1162 message=_skip_reason,
1163 )
1164 )
1165 add_result(
1166 BenchmarkResult(
1167 name="multiple_generation_calls",
1168 severity=BenchmarkSeverity.INFO,
1169 passed=True,
1170 message=_skip_reason,
1171 )
1172 )
1173 add_result(
1174 BenchmarkResult(
1175 name="text_quality",
1176 severity=BenchmarkSeverity.INFO,
1177 passed=True,
1178 message=_skip_reason,
1179 )
1180 )
1181 else:
1182 try:
1183 add_result(benchmark_generation(bridge_unprocessed, test_text, max_new_tokens=10))
1184 add_result(
1185 benchmark_generation_with_kv_cache(
1186 bridge_unprocessed, test_text, max_new_tokens=10
1187 )
1188 )
1189 add_result(
1190 benchmark_multiple_generation_calls(
1191 bridge_unprocessed,
1192 test_prompts=[
1193 "The quick brown fox",
1194 "Hello world",
1195 "Machine learning is",
1196 ],
1197 max_new_tokens=5,
1198 )
1199 )
1200 gc.collect() # Force cleanup after generation benchmarks
1201 except Exception as e:
1202 if verbose:
1203 print(f"✗ Generation benchmark failed: {e}\n")
1205 # Run Phase 2 runtime benchmarks using unified function
1206 if should_run_phase(2) and bridge_unprocessed: 1206 ↛ 1248line 1206 didn't jump to line 1248 because the condition on line 1206 was always true
1207 if verbose: 1207 ↛ 1208line 1207 didn't jump to line 1208 because the condition on line 1207 was never true
1208 print("2. Running Unprocessed Model Runtime Benchmarks\n")
1210 # When dtype==float32 (default) but the model natively loaded in
1211 # reduced precision, upcast for maximum benchmark accuracy. When the
1212 # user explicitly requested bfloat16/float16, honour that — run the
1213 # entire comparison in the requested precision.
1214 phase2_restore_dtype = None
1215 if dtype == torch.float32 and bridge_dtype in (torch.bfloat16, torch.float16): 1215 ↛ 1216line 1215 didn't jump to line 1216 because the condition on line 1215 was never true
1216 try:
1217 bridge_unprocessed.to(torch.float32)
1218 phase2_restore_dtype = bridge_dtype
1219 if verbose:
1220 print(f" (upcast from {bridge_dtype} to float32 for comparison)\n")
1221 except Exception:
1222 phase2_restore_dtype = None # Upcast failed; proceed as-is
1224 phase2_results = run_comparison_benchmarks(
1225 bridge_model=bridge_unprocessed,
1226 test_text=test_text,
1227 phase_name="Phase 2",
1228 is_processed=False, # Unprocessed mode - skip weight processing tests
1229 verbose=verbose,
1230 phase1_reference=phase1_reference, # Saved HF logits/loss for equivalence testing
1231 restore_dtype_after_equivalence=phase2_restore_dtype,
1232 )
1233 # Tag all phase 2 results with phase number
1234 for result in phase2_results:
1235 if result.phase is None: 1235 ↛ 1234line 1235 didn't jump to line 1234 because the condition on line 1235 was always true
1236 result.phase = 2
1237 results.extend(phase2_results)
1239 # bridge_unprocessed is kept alive for Phase 3 and Phase 4 — reusing the
1240 # same instance avoids non-deterministic loading in some architectures
1241 # (e.g., OpenELM).
1243 # ========================================================================
1244 # PHASE 4: Text Quality (profile prompts, judge perplexity-ratio scoring)
1245 # Runs before Phase 3 so it can reuse bridge_unprocessed (Phase 3
1246 # destructively processes the weights, consuming the bridge).
1247 # ========================================================================
1248 current_phase[0] = 4
1250 if ( 1250 ↛ 1263line 1250 didn't jump to line 1263 because the condition on line 1250 was never true
1251 should_run_phase(4)
1252 and bridge_unprocessed is not None
1253 # applicable_phases and supports_generation are independent switches;
1254 # without this check a disagreement surfaces as an ERROR, not a skip.
1255 # Native-sampler architectures generate too, just not autoregressively.
1256 and (
1257 getattr(bridge_unprocessed.adapter, "supports_generation", True)
1258 or getattr(bridge_unprocessed.adapter, "native_sampler", None) is not None
1259 )
1260 and not is_masked_lm_model(model_name, trust_remote_code=trust_remote_code)
1261 and not is_audio_model(model_name, trust_remote_code=trust_remote_code)
1262 ):
1263 if prompt_profile is None:
1264 from transformer_lens.benchmarks.text_quality_profiles import (
1265 resolve_profile,
1266 )
1267 from transformer_lens.tools.model_registry.registry_io import (
1268 registry_prompt_profile,
1269 )
1271 config = getattr(bridge_unprocessed, "original_model", None)
1272 archs = getattr(getattr(config, "config", None), "architectures", None) or []
1273 prompt_profile = str(
1274 resolve_profile(
1275 model_name, archs[0] if archs else None, registry_prompt_profile(model_name)
1276 )
1277 )
1279 if verbose:
1280 print(f"\n{'='*80}")
1281 print(f"PHASE 2.5: Text Quality (profile {prompt_profile}, judge ratio scoring)")
1282 print(f"{'='*80}\n")
1284 try:
1285 text_quality_result = benchmark_text_quality(
1286 bridge_unprocessed,
1287 prompt_profile,
1288 judge_model=judge_model,
1289 judge_tokenizer=judge_tokenizer,
1290 model_name=model_name,
1291 )
1292 text_quality_result.phase = 4
1293 add_result(text_quality_result)
1294 except Exception as e:
1295 if verbose:
1296 print(f"✗ Text quality benchmark failed: {e}\n")
1298 # ========================================================================
1299 # Phase 7: Multimodal Tests (only for multimodal models)
1300 # Runs before Phase 3 so we can reuse bridge_unprocessed before cleanup.
1301 # ========================================================================
1302 if ( 1302 ↛ 1307line 1302 didn't jump to line 1307 because the condition on line 1302 was never true
1303 bridge_unprocessed is not None
1304 and getattr(bridge_unprocessed.cfg, "is_multimodal", False)
1305 and should_run_phase(7)
1306 ):
1307 current_phase[0] = 7
1308 if verbose:
1309 print("\n" + "=" * 80)
1310 print("PHASE 7: MULTIMODAL TESTS")
1311 print("=" * 80)
1312 print("Testing multimodal forward pass, generation, and caching with images.")
1313 print("=" * 80 + "\n")
1315 try:
1316 from transformer_lens.benchmarks.multimodal import (
1317 benchmark_multimodal_cache,
1318 benchmark_multimodal_forward,
1319 benchmark_multimodal_generation,
1320 )
1322 mm_results = [
1323 benchmark_multimodal_forward(bridge_unprocessed, test_text=test_text),
1324 benchmark_multimodal_generation(bridge_unprocessed, test_text=test_text),
1325 benchmark_multimodal_cache(bridge_unprocessed, test_text=test_text),
1326 ]
1327 for result in mm_results:
1328 result.phase = 7
1329 results.append(result)
1330 if verbose:
1331 print(result)
1333 if verbose:
1334 print("\n" + "=" * 80)
1335 print("PHASE 7 COMPLETE")
1336 print("=" * 80)
1338 except Exception as e:
1339 if verbose:
1340 print(f"\n⚠ Multimodal tests failed: {e}\n")
1341 results.append(
1342 BenchmarkResult(
1343 name="multimodal_suite",
1344 passed=False,
1345 severity=BenchmarkSeverity.ERROR,
1346 message=f"Failed to run multimodal tests: {str(e)}",
1347 details={"error": str(e)},
1348 phase=7,
1349 )
1350 )
1352 # ========================================================================
1353 # Phase 8: Audio Tests (only for audio encoder models; audio seq2seq models
1354 # need decoder ids on every forward, and Phase 1 covers their audio path)
1355 # Runs before Phase 3 so we can reuse bridge_unprocessed before cleanup.
1356 # ========================================================================
1357 if ( 1357 ↛ 1363line 1357 didn't jump to line 1363 because the condition on line 1357 was never true
1358 bridge_unprocessed is not None
1359 and getattr(bridge_unprocessed.cfg, "is_audio_model", False)
1360 and not _is_audio_seq2seq
1361 and should_run_phase(8)
1362 ):
1363 current_phase[0] = 8
1364 if verbose:
1365 print("\n" + "=" * 80)
1366 print("PHASE 8: AUDIO TESTS")
1367 print("=" * 80)
1368 print("Testing audio forward pass, caching, representation stability, and features.")
1369 print("=" * 80 + "\n")
1371 try:
1372 from transformer_lens.benchmarks.audio import run_audio_benchmarks
1374 audio_results = run_audio_benchmarks(
1375 bridge_unprocessed,
1376 test_audio=_test_modality_input,
1377 verbose=verbose,
1378 )
1379 for result in audio_results:
1380 result.phase = 8
1381 results.append(result)
1382 if verbose:
1383 print(result)
1385 if verbose:
1386 print("\n" + "=" * 80)
1387 print("PHASE 8 COMPLETE")
1388 print("=" * 80)
1390 except Exception as e:
1391 if verbose:
1392 print(f"\n⚠ Audio tests failed: {e}\n")
1393 results.append(
1394 BenchmarkResult(
1395 name="audio_suite",
1396 passed=False,
1397 severity=BenchmarkSeverity.ERROR,
1398 message=f"Failed to run audio tests: {str(e)}",
1399 details={"error": str(e)},
1400 phase=8,
1401 )
1402 )
1404 # ========================================================================
1405 # PHASE 8 (audio-text): audio-conditioned forward for audio decoders
1406 # (Qwen2Audio etc.) — is_multimodal with an audio processor, not an encoder.
1407 # Image Phase 7 feeds pixel_values and encoder Phase 8 feeds a raw waveform;
1408 # neither exercises these models' processed-feature audio path.
1409 # ========================================================================
1410 _audio_text = (
1411 bridge_unprocessed is not None
1412 and getattr(bridge_unprocessed.cfg, "is_multimodal", False)
1413 and not getattr(bridge_unprocessed.cfg, "is_audio_model", False)
1414 and getattr(getattr(bridge_unprocessed, "processor", None), "audio_token", None) is not None
1415 )
1416 if _audio_text and should_run_phase(8): 1416 ↛ 1417line 1416 didn't jump to line 1417 because the condition on line 1416 was never true
1417 current_phase[0] = 8
1418 if verbose:
1419 print("\n" + "=" * 80 + "\nPHASE 8: AUDIO-TEXT FORWARD\n" + "=" * 80 + "\n")
1420 from transformer_lens.benchmarks.audio import benchmark_audio_text_forward
1422 result = benchmark_audio_text_forward(bridge_unprocessed)
1423 result.phase = 8
1424 add_result(result)
1426 # ========================================================================
1427 # Phase 9: Vision Tests (only for vision encoder models — ViT/DeiT, not
1428 # vision+text multimodal models, which Phase 7 covers)
1429 # Runs before Phase 3 so we can reuse bridge_unprocessed before cleanup.
1430 # ========================================================================
1431 if ( 1431 ↛ 1437line 1431 didn't jump to line 1437 because the condition on line 1431 was never true
1432 bridge_unprocessed is not None
1433 and getattr(bridge_unprocessed.cfg, "is_visual_model", False)
1434 and not getattr(bridge_unprocessed.cfg, "is_multimodal", False)
1435 and should_run_phase(9)
1436 ):
1437 current_phase[0] = 9
1438 if verbose:
1439 print("\n" + "=" * 80)
1440 print("PHASE 9: VISION TESTS")
1441 print("=" * 80)
1442 print("Testing pixel forward pass, caching, representation stability, and decoding.")
1443 print("=" * 80 + "\n")
1445 try:
1446 from transformer_lens.benchmarks.vision import run_vision_benchmarks
1448 vision_results = run_vision_benchmarks(
1449 bridge_unprocessed,
1450 test_pixels=_test_modality_input,
1451 verbose=verbose,
1452 )
1453 for result in vision_results:
1454 result.phase = 9
1455 results.append(result)
1456 if verbose:
1457 print(result)
1459 if verbose:
1460 print("\n" + "=" * 80)
1461 print("PHASE 9 COMPLETE")
1462 print("=" * 80)
1464 except Exception as e:
1465 if verbose:
1466 print(f"\n⚠ Vision tests failed: {e}\n")
1467 results.append(
1468 BenchmarkResult(
1469 name="vision_suite",
1470 passed=False,
1471 severity=BenchmarkSeverity.ERROR,
1472 message=f"Failed to run vision tests: {str(e)}",
1473 details={"error": str(e)},
1474 phase=9,
1475 )
1476 )
1478 # ========================================================================
1479 # PHASE 3: Bridge (processed/compatibility mode) — HF equivalence
1480 # ========================================================================
1481 current_phase[0] = 3
1483 def _cleanup_bridge_unprocessed():
1484 """Clean up the kept-alive bridge_unprocessed if Phase 3 is skipped."""
1485 nonlocal bridge_unprocessed
1486 if bridge_unprocessed is not None: 1486 ↛ exitline 1486 didn't return from function '_cleanup_bridge_unprocessed' because the condition on line 1486 was always true
1487 cleanup_model(bridge_unprocessed, "TransformerBridge (unprocessed)")
1488 bridge_unprocessed = None
1490 _skip_phase3 = False
1491 if not enable_compatibility_mode: 1491 ↛ 1496line 1491 didn't jump to line 1496 because the condition on line 1491 was always true
1492 _cleanup_bridge_unprocessed()
1493 _skip_phase3 = True
1494 if verbose: 1494 ↛ 1495line 1494 didn't jump to line 1495 because the condition on line 1494 was never true
1495 print("\n⚠ Compatibility mode disabled - skipping Phase 3\n")
1496 elif not should_run_phase(3):
1497 _cleanup_bridge_unprocessed()
1498 _skip_phase3 = True
1499 if verbose:
1500 print("\n⚠ Phase 3 skipped (excluded by phases filter or adapter applicable_phases)\n")
1501 elif is_encoder_decoder_model(model_name):
1502 _cleanup_bridge_unprocessed()
1503 _skip_phase3 = True
1504 if verbose:
1505 print("\n⚠ Phase 3 skipped (encoder-decoder model - weight processing not supported)\n")
1507 bridge_processed = None
1509 if not _skip_phase3: 1509 ↛ 1510line 1509 didn't jump to line 1510 because the condition on line 1509 was never true
1510 if verbose:
1511 print(f"\n{'='*80}")
1512 print("PHASE 3: TransformerBridge (processed/compatibility mode) — HF equivalence")
1513 print(f"{'='*80}\n")
1515 if not _skip_phase3: 1515 ↛ 1521line 1515 didn't jump to line 1521 because the condition on line 1515 was never true
1516 # Reuse the Phase 1 bridge instance and process weights in-place.
1517 # When dtype==float32 (default) and the model natively uses reduced
1518 # precision, upcast before processing to avoid bf16 quantization
1519 # round-trips. When the user explicitly requested bfloat16/float16,
1520 # process weights in the requested precision — no upcast.
1521 phase3_native_dtype = None # Set if we upcast; used to restore later
1522 if bridge_unprocessed is not None:
1523 try:
1524 if verbose:
1525 print("Processing weights on existing bridge (reusing Phase 1 instance)...")
1526 bridge_processed = bridge_unprocessed
1527 bridge_unprocessed = None # Transfer ownership
1528 phase3_native_dtype = bridge_processed.cfg.dtype
1529 if dtype == torch.float32 and phase3_native_dtype not in (
1530 torch.float32,
1531 torch.float64,
1532 ):
1533 bridge_processed.to(torch.float32)
1534 if verbose:
1535 print(f" (upcast from {phase3_native_dtype} to float32 before processing)")
1536 else:
1537 phase3_native_dtype = None # No restore needed
1538 bridge_processed.enable_compatibility_mode(disable_warnings=True)
1539 if verbose:
1540 print("✓ TransformerBridge compatibility mode enabled (processed)\n")
1541 except Exception as e:
1542 import traceback
1544 error_trace = traceback.format_exc()
1545 add_result(
1546 BenchmarkResult(
1547 name="process_bridge_weights",
1548 severity=BenchmarkSeverity.ERROR,
1549 message=f"Failed to process bridge weights: {str(e)}",
1550 passed=False,
1551 details={"error": str(e), "traceback": error_trace},
1552 )
1553 )
1554 if verbose:
1555 print(f"✗ Failed to process bridge weights: {str(e)}")
1556 print(f"\nStack trace:\n{error_trace}")
1557 else:
1558 # Fallback: load a fresh bridge if Phase 1 bridge was not available
1559 try:
1560 if verbose:
1561 print("Loading TransformerBridge (processed)...")
1562 bridge_dtype = saved_bridge_dtype
1563 if verbose:
1564 print(f"Using dtype={bridge_dtype} from Phase 1")
1565 bridge_processed = TransformerBridge.boot_transformers(model_name, device=device, dtype=bridge_dtype, trust_remote_code=trust_remote_code) # type: ignore[attr-defined]
1566 bridge_processed.enable_compatibility_mode(disable_warnings=True)
1567 if verbose:
1568 print("✓ TransformerBridge compatibility mode enabled (processed)\n")
1569 except Exception as e:
1570 import traceback
1572 error_trace = traceback.format_exc()
1573 add_result(
1574 BenchmarkResult(
1575 name="load_bridge_processed",
1576 severity=BenchmarkSeverity.ERROR,
1577 message=f"Failed to load processed TransformerBridge: {str(e)}",
1578 passed=False,
1579 details={"error": str(e), "traceback": error_trace},
1580 )
1581 )
1582 if verbose:
1583 print(f"✗ Failed to load processed TransformerBridge: {str(e)}")
1584 print(f"\nStack trace:\n{error_trace}")
1586 if bridge_processed is None:
1587 # Add failure results for all Phase 3 tests
1588 phase3_tests = [
1589 "no_nan_inf",
1590 "weight_magnitudes",
1591 "layer_norm_folding",
1592 "attention_output_centering",
1593 "mlp_output_centering",
1594 "unembed_centering",
1595 "value_bias_folding",
1596 "weight_modification",
1597 "logits_equivalence",
1598 "loss_equivalence",
1599 "hook_registry",
1600 "hook_functionality",
1601 "critical_forward_hooks",
1602 "forward_hooks",
1603 "run_with_cache",
1604 "activation_cache",
1605 "gradient_computation",
1606 "critical_backward_hooks",
1607 "backward_hooks",
1608 ]
1610 for test_name in phase3_tests:
1611 add_result(
1612 BenchmarkResult(
1613 name=test_name,
1614 severity=BenchmarkSeverity.ERROR,
1615 message=f"Skipped due to weight processing failure",
1616 passed=False,
1617 details={"reason": "bridge_processing_failed"},
1618 )
1619 )
1621 if verbose:
1622 print("\n" + format_results(results))
1624 # Run Phase 3 benchmarks using unified function
1625 if bridge_processed:
1626 if verbose:
1627 print("Running Phase 3 benchmarks...\n")
1629 # Phase 3 runs in the requested dtype end-to-end, so no dtype
1630 # restoration is needed.
1631 phase3_results = run_comparison_benchmarks(
1632 bridge_model=bridge_processed,
1633 test_text=test_text,
1634 phase_name="Phase 3",
1635 is_processed=True, # Processed mode - include weight processing tests
1636 verbose=verbose,
1637 phase1_reference=phase1_reference, # Saved HF logits/loss for equivalence testing
1638 )
1639 # Tag all phase 3 results with phase number
1640 for result in phase3_results:
1641 if result.phase is None:
1642 result.phase = 3
1643 results.extend(phase3_results)
1645 # Clean up Phase 3 models
1646 if bridge_processed is not None:
1647 cleanup_model(bridge_processed, "TransformerBridge (processed)")
1648 bridge_processed = None
1650 # Print summary (individual results already printed immediately)
1651 if verbose: 1651 ↛ 1652line 1651 didn't jump to line 1652 because the condition on line 1651 was never true
1652 print("\n" + "=" * 80)
1653 print("BENCHMARK SUMMARY")
1654 print("=" * 80)
1656 # Group results by phase
1657 results_by_phase: Dict[Union[int, str], List[BenchmarkResult]] = {}
1658 for r in results:
1659 phase = r.phase if r.phase is not None else "Other"
1660 if phase not in results_by_phase:
1661 results_by_phase[phase] = []
1662 results_by_phase[phase].append(r)
1664 # Print phase-by-phase summary
1665 for phase in sorted(
1666 results_by_phase.keys(), key=lambda x: x if isinstance(x, int) else 999
1667 ):
1668 phase_results = results_by_phase[phase]
1669 phase_name = f"Phase {phase}" if isinstance(phase, int) else phase
1671 phase_passed = sum(
1672 1 for r in phase_results if r.passed and r.severity != BenchmarkSeverity.SKIPPED
1673 )
1674 phase_failed = sum(
1675 1 for r in phase_results if not r.passed and r.severity != BenchmarkSeverity.SKIPPED
1676 )
1677 phase_skipped = sum(1 for r in phase_results if r.severity == BenchmarkSeverity.SKIPPED)
1678 phase_total = len(phase_results)
1679 phase_run = phase_total - phase_skipped
1681 print(f"\n{phase_name}: {phase_run} tests run")
1682 if phase_run > 0:
1683 print(f" Passed: {phase_passed}/{phase_run} ({phase_passed/phase_run*100:.1f}%)")
1684 print(f" Failed: {phase_failed}/{phase_run} ({phase_failed/phase_run*100:.1f}%)")
1685 if phase_skipped > 0:
1686 print(f" Skipped: {phase_skipped}")
1688 # Overall summary
1689 passed = sum(1 for r in results if r.passed and r.severity != BenchmarkSeverity.SKIPPED)
1690 failed = sum(1 for r in results if not r.passed and r.severity != BenchmarkSeverity.SKIPPED)
1691 skipped = sum(1 for r in results if r.severity == BenchmarkSeverity.SKIPPED)
1692 total = len(results)
1693 run_tests = total - skipped
1695 print(f"\nOverall:")
1696 print(f"Total: {total} tests")
1697 if skipped > 0:
1698 print(f"Run: {run_tests} tests")
1699 print(f"Skipped: {skipped} tests")
1700 if run_tests > 0:
1701 print(f"Passed: {passed}/{run_tests} ({passed/run_tests*100:.1f}%)")
1702 print(f"Failed: {failed}/{run_tests} ({failed/run_tests*100:.1f}%)")
1703 print("=" * 80)
1705 # Print memory summary
1706 if track_memory and memory_tracker is not None: 1706 ↛ 1707line 1706 didn't jump to line 1707 because the condition on line 1706 was never true
1707 final_memory = get_memory_mb()
1708 total_increase = final_memory - memory_tracker["initial"]
1710 if verbose:
1711 print("\n" + "=" * 80)
1712 print("MEMORY USAGE SUMMARY")
1713 print("=" * 80)
1714 print(f"Initial memory: {memory_tracker['initial']:>8.1f} MB")
1715 print(f"Final memory: {final_memory:>8.1f} MB")
1716 print(f"Net increase: {total_increase:>+8.1f} MB")
1718 if memory_tracker["checkpoints"]:
1719 print("\nCleanup operations:")
1720 for cp in memory_tracker["checkpoints"]:
1721 if cp.get("freed_mb", 0) > 0:
1722 print(
1723 f" {cp['label']:<40} freed {cp['freed_mb']:>7.1f} MB "
1724 f"(after: {cp['memory_mb']:.1f} MB)"
1725 )
1726 print("=" * 80)
1728 return results
1731def update_model_registry(
1732 model_name: str, results: List[BenchmarkResult], use_hf_reference: bool = False
1733) -> bool:
1734 """Update the model registry with benchmark results.
1736 Args:
1737 model_name: The model that was benchmarked
1738 results: List of benchmark results
1739 use_hf_reference: Whether the run numerically compared against an HF
1740 reference. Defaults to False so an unstated reference state records
1741 a passing run as PROVISIONAL, never VERIFIED.
1743 Returns:
1744 True if registry was updated successfully
1745 """
1746 from transformer_lens.tools.model_registry.registry_io import (
1747 STATUS_FAILED,
1748 STATUS_PROVISIONAL,
1749 add_verification_record,
1750 extract_phase_scores,
1751 pass_status,
1752 update_model_status,
1753 )
1755 # Threshold/note logic shared with verify_models so the two paths can't drift.
1756 from transformer_lens.tools.model_registry.verify_models import (
1757 _build_verified_note,
1758 _check_phase_scores,
1759 _extract_prompt_profile,
1760 _sanitize_note,
1761 )
1763 phase_scores = extract_phase_scores(results)
1765 score_error = _check_phase_scores(phase_scores, results)
1766 if score_error:
1767 status = STATUS_FAILED
1768 note = score_error
1769 else:
1770 status = pass_status(use_hf_reference)
1771 note = _build_verified_note(phase_scores, results)
1772 if status == STATUS_PROVISIONAL:
1773 note = f"Structural only (no HF reference): {note}"
1775 # Try to determine architecture
1776 architecture_id = "Unknown"
1777 try:
1778 from transformers import AutoConfig
1780 config = AutoConfig.from_pretrained(model_name, token=_hf_token())
1781 archs = getattr(config, "architectures", []) or []
1782 if archs: 1782 ↛ 1787line 1782 didn't jump to line 1787 because the condition on line 1782 was always true
1783 architecture_id = archs[0]
1784 except Exception:
1785 pass
1787 updated = update_model_status(
1788 model_id=model_name,
1789 arch_id=architecture_id,
1790 status=status,
1791 phase_scores=phase_scores,
1792 note=note,
1793 sanitize_fn=_sanitize_note,
1794 prompt_profile=_extract_prompt_profile(results),
1795 )
1797 # No history record for provisional runs — VerificationHistory.is_verified()
1798 # treats any record as verified, which would bypass the provisional gate.
1799 if status != STATUS_PROVISIONAL:
1800 add_verification_record(
1801 model_id=model_name,
1802 arch_id=architecture_id,
1803 notes=note,
1804 verified_by="main_benchmark",
1805 sanitize_fn=_sanitize_note,
1806 )
1808 label = {STATUS_FAILED: "FAILED", STATUS_PROVISIONAL: "PROVISIONAL"}.get(status, "VERIFIED")
1809 score_parts = ", ".join(f"P{p}={s}%" for p, s in sorted(phase_scores.items()))
1810 print(f"Updated registry for {model_name} ({label}): {score_parts or 'no phase results'}")
1811 return updated
1814def main():
1815 """Run benchmarks from command line."""
1816 import argparse
1818 parser = argparse.ArgumentParser(description="Run TransformerBridge benchmarks")
1819 parser.add_argument(
1820 "--model",
1821 type=str,
1822 default="gpt2",
1823 help="Model name to benchmark (default: gpt2)",
1824 )
1825 parser.add_argument(
1826 "--device",
1827 type=str,
1828 default="cpu",
1829 help="Device to run on (default: cpu)",
1830 )
1831 parser.add_argument(
1832 "--no-hf-reference",
1833 action="store_true",
1834 help="Disable HuggingFace reference comparison",
1835 )
1836 parser.add_argument(
1837 "--no-compat",
1838 action="store_true",
1839 help="Disable compatibility mode",
1840 )
1841 parser.add_argument(
1842 "--quiet",
1843 action="store_true",
1844 help="Suppress verbose output",
1845 )
1846 parser.add_argument(
1847 "--update-registry",
1848 action="store_true",
1849 help="Update model registry with benchmark results (default: false)",
1850 )
1851 parser.add_argument(
1852 "--trust-remote-code",
1853 action="store_true",
1854 help="Trust remote code for custom architectures (e.g., OpenELM)",
1855 )
1856 args = parser.parse_args()
1858 results = run_benchmark_suite(
1859 model_name=args.model,
1860 device=args.device,
1861 use_hf_reference=not args.no_hf_reference,
1862 enable_compatibility_mode=not args.no_compat,
1863 verbose=not args.quiet,
1864 trust_remote_code=args.trust_remote_code,
1865 )
1867 if args.update_registry:
1868 # Same requested-reference state verify_models feeds pass_status(): a
1869 # --no-hf-reference run can only mint PROVISIONAL, never VERIFIED.
1870 update_model_registry(args.model, results, use_hf_reference=not args.no_hf_reference)
1873if __name__ == "__main__": 1873 ↛ 1874line 1873 didn't jump to line 1874 because the condition on line 1873 was never true
1874 main()