Coverage for transformer_lens/tools/model_registry/verify_models.py: 40%
738 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"""Batch model verification tool for the TransformerLens model registry.
3Iterates through supported models, estimates memory requirements, runs benchmarks
4phase-by-phase, and updates the registry with status, phase scores, and notes.
6Usage:
7 python -m transformer_lens.tools.model_registry.verify_models [options]
9Examples:
10 # Dry run to see what would be tested
11 python -m transformer_lens.tools.model_registry.verify_models --dry-run
13 # Verify top 10 models per architecture on CPU
14 python -m transformer_lens.tools.model_registry.verify_models --device cpu
16 # Verify only GPT2 models, limit to 3
17 python -m transformer_lens.tools.model_registry.verify_models --architectures GPT2LMHeadModel --limit 3
19 # Resume from a previous interrupted run
20 python -m transformer_lens.tools.model_registry.verify_models --resume
22 # Re-verify already-tested models for a specific architecture
23 python -m transformer_lens.tools.model_registry.verify_models --reverify --architectures Olmo2ForCausalLM
24"""
26import argparse
27import gc
28import json
29import logging
30import re
31import signal
32import time
33from dataclasses import dataclass, field
34from datetime import datetime
35from pathlib import Path
36from typing import Optional
38from transformer_lens.benchmarks.text_quality_profiles import (
39 P4_SCORING_VERSION,
40 p4_pass_threshold,
41)
42from transformer_lens.utilities.heterogeneous_config import het_safe_view
44# Exit code used for graceful interrupts (Ctrl+C). The wrapper script
45# recognises this and stops without marking the in-flight model as failed.
46_EXIT_GRACEFUL_INTERRUPT = 42
48# Module-level flag set by the SIGINT handler so the main loop can stop
49# between models without corrupting state.
50_interrupt_requested = False
52from . import REMOTE_CODE_MODEL_PREFIXES
53from .registry_io import (
54 MODALITY_PHASES,
55 QUANTIZED_NOTE,
56 STATUS_FAILED,
57 STATUS_PROVISIONAL,
58 STATUS_SKIPPED,
59 STATUS_UNVERIFIED,
60 STATUS_VERIFIED,
61 TEXT_PHASES,
62 add_verification_record,
63 extract_phase_scores,
64 is_incompatible_quantized,
65 load_supported_models_raw,
66 pass_status,
67 required_quant_library_for_model,
68 update_model_status,
69)
71logger = logging.getLogger(__name__)
73# Data directory for registry files
74_DATA_DIR = Path(__file__).parent / "data"
75_CHECKPOINT_PATH = _DATA_DIR / "verification_checkpoint.json"
78def _handle_sigint(signum, frame): # noqa: ARG001
79 """Handle Ctrl+C by setting a flag instead of raising immediately.
81 The main verification loop checks this flag between models so it can
82 save the checkpoint cleanly and exit without marking the current model
83 as failed.
84 """
85 global _interrupt_requested # noqa: PLW0603
86 if _interrupt_requested:
87 # Second Ctrl+C — force exit immediately
88 print("\nForce quit.")
89 raise SystemExit(1)
90 _interrupt_requested = True
91 print("\n\nInterrupt received — finishing current model before stopping.")
92 print("(Press Ctrl+C again to force quit immediately.)\n")
95# Pattern matching HuggingFace API tokens (hf_ followed by 20+ alphanumeric chars)
96_HF_TOKEN_RE = re.compile(r"hf_[A-Za-z0-9]{20,}")
99def _sanitize_note(note: Optional[str]) -> Optional[str]:
100 """Sanitize a note string to remove sensitive information.
102 Strips HuggingFace tokens and replaces verbose gated-repo error messages
103 with a concise summary.
104 """
105 if not note:
106 return note
107 # Replace any HF tokens that leaked into the message
108 note = _HF_TOKEN_RE.sub("HF_TOKEN", note)
109 # Replace verbose gated-repo 401 errors with a clean summary
110 if "gated repo" in note:
111 url_match = re.search(r"https://huggingface\.co/([^\s.]+)", note)
112 model_ref = url_match.group(1) if url_match else "unknown"
113 return f"Config unavailable: Gated repo ({model_ref})"
114 return note
117def _phases_to_run(arch: str, phases: list[int]) -> list[int]:
118 """Restrict requested phases to those the adapter supports.
120 An adapter's ``applicable_phases`` declares which text phases (1-4) it covers. Phases
121 7/8/9 are gated separately by ``is_multimodal``/``is_audio``/``is_visual_model`` in
122 ``main_benchmark._phase_enabled`` (the mirror of this gate), so they are never filtered
123 out here. An empty result means none of the requested phases apply to this architecture
124 (SSM / recurrent families run all four).
125 """
126 from transformer_lens.factories.architecture_adapter_factory import (
127 SUPPORTED_ARCHITECTURES,
128 )
130 applicable = getattr(SUPPORTED_ARCHITECTURES.get(arch), "applicable_phases", list(TEXT_PHASES))
131 return [p for p in phases if p in applicable or p in MODALITY_PHASES]
134def _runs_phase_4(candidates: list["ModelCandidate"], phases: Optional[list[int]]) -> bool:
135 """Whether any candidate runs Phase 4, so the text-quality judge is needed."""
136 for candidate in candidates:
137 arch = candidate.architecture_id
138 requested = phases if phases is not None else _default_phases_for_architecture(arch)
139 if 4 in _phases_to_run(arch, requested):
140 return True
141 return False
144def _full_and_core_phases(arch: str) -> tuple[set[int], set[int]]:
145 """``(full verification set, core subset)`` for this architecture -- the single
146 source for both default phase selection and the status-writing decision."""
147 from transformer_lens.utilities.architectures import AUDIO_TEXT_ARCHITECTURES
149 kind = classify_architecture(arch)
150 if kind == "audio":
151 return {1, 8}, {1, 8}
152 if kind == "vision":
153 # Vision encoders have no tokenizer and no text tower: Phases 2/3 compare
154 # text logits/loss, Phase 4 needs text generation, and Phase 7 covers
155 # vision+text multimodal models, not these. Phase 1 (HF parity) plus
156 # Phase 9 (pixel forward/cache/stability) are the whole story.
157 return {1, 9}, {1, 9}
158 if kind == "multimodal":
159 return {1, 2, 3, 4, 7}, {1, 4, 7}
160 if arch in AUDIO_TEXT_ARCHITECTURES:
161 # Phase 8 (audio-conditioned forward) out of the core set so a partial {1,4}
162 # run still verifies; a full run records and gates it via _check_phase_scores.
163 return {1, 2, 3, 4, 8}, {1, 4}
164 return {1, 2, 3, 4}, {1, 4}
167def _default_phases_for_architecture(arch: str) -> list[int]:
168 """Phases to run when the caller names none — a full verification."""
169 return sorted(_full_and_core_phases(arch)[0])
172def _get_current_model_status(model_id: str, arch_id: str) -> int:
173 """Look up a model's current status in the registry.
175 Returns STATUS_UNVERIFIED (0) if the model is not found.
176 """
177 data = load_supported_models_raw()
178 for entry in data.get("models", []):
179 if not isinstance(entry, dict):
180 continue
181 if entry.get("model_id") == model_id and entry.get("architecture_id") == arch_id:
182 return entry.get("status", STATUS_UNVERIFIED)
183 return STATUS_UNVERIFIED
186@dataclass
187class ModelCandidate:
188 """A model selected for verification."""
190 model_id: str
191 architecture_id: str
192 estimated_params: Optional[int] = None
193 estimated_memory_gb: Optional[float] = None
196@dataclass
197class VerificationProgress:
198 """Tracks progress across a verification run."""
200 tested: list[str] = field(default_factory=list)
201 skipped: list[str] = field(default_factory=list)
202 failed: list[str] = field(default_factory=list)
203 verified: list[str] = field(default_factory=list)
204 # Structural-only (--no-hf-reference) passes; kept out of the verified tally.
205 provisional: list[str] = field(default_factory=list)
206 start_time: Optional[str] = None
208 def to_dict(self) -> dict:
209 return {
210 "tested": self.tested,
211 "skipped": self.skipped,
212 "failed": self.failed,
213 "verified": self.verified,
214 "provisional": self.provisional,
215 "start_time": self.start_time,
216 }
218 @classmethod
219 def from_dict(cls, data: dict) -> "VerificationProgress":
220 return cls(
221 tested=data.get("tested", []),
222 skipped=data.get("skipped", []),
223 failed=data.get("failed", []),
224 verified=data.get("verified", []),
225 provisional=data.get("provisional", []),
226 start_time=data.get("start_time"),
227 )
230def published_param_count(model_id: str) -> Optional[int]:
231 """Exact parameter count from the hub's safetensors metadata, or None.
233 Metadata only -- no weights are fetched. Preferred over the config formula
234 below, which assumes every layer carries full attention and an MLP and so
235 over-counts a hybrid Mamba/attention stack roughly fourfold
236 (NVIDIA-Nemotron-Nano-9B-v2: 36.6B estimated against 8.89B published, enough
237 to skip the model as too large for memory it does not need).
238 """
239 from transformer_lens.utilities.hf_utils import get_hf_token
241 try:
242 from huggingface_hub import HfApi
244 info = HfApi().model_info(model_id, expand=["safetensors"], token=get_hf_token())
245 except Exception:
246 # Unpublished metadata, a gated repo or a network blip: fall back rather
247 # than fail, since the config formula needs no hub metadata.
248 return None
249 total = getattr(info.safetensors, "total", None) if info.safetensors else None
250 return int(total) if total else None
253def estimate_model_params(model_id: str) -> int:
254 """Parameter count for this model: published metadata first, else a config estimate.
256 Fetches only metadata and the config JSON (~KB), never weights.
258 Args:
259 model_id: HuggingFace model ID
261 Returns:
262 Number of parameters — exact when the hub publishes it, else estimated
263 from config dimensions using the standard TransformerLens
264 parameter-count formula.
266 Raises:
267 Exception: If config cannot be fetched or parsed
268 """
269 published = published_param_count(model_id)
270 if published:
271 return published
273 trust_remote_code = any(model_id.startswith(prefix) for prefix in REMOTE_CODE_MODEL_PREFIXES)
274 from transformer_lens.utilities.hf_utils import (
275 autoconfig_with_remote_post_init_compat,
276 get_hf_token,
277 )
279 config = autoconfig_with_remote_post_init_compat(
280 model_id, trust_remote_code=trust_remote_code, token=get_hf_token()
281 )
283 # For multimodal models (LLaVA, Gemma3 multimodal), the language model config
284 # is nested under text_config. Fall through to the top-level config otherwise.
285 lang_config = getattr(config, "text_config", config)
287 # Encoder-decoder models (e.g. T5Gemma) nest dimensions under decoder/encoder
288 # subconfigs rather than the top level; prefer the decoder for the estimate.
289 if not (hasattr(lang_config, "hidden_size") or hasattr(lang_config, "d_model")): 289 ↛ 290line 289 didn't jump to line 290 because the condition on line 289 was never true
290 for _sub in ("decoder", "encoder"):
291 _subcfg = getattr(config, _sub, None)
292 if _subcfg is not None and (
293 hasattr(_subcfg, "hidden_size") or hasattr(_subcfg, "d_model")
294 ):
295 lang_config = _subcfg
296 break
298 # Heterogeneous configs (transformers>=5.15 Gemma 4) raise on global reads of
299 # per-layer fields like head_dim; the view resolves them to majority values.
300 lang_config = het_safe_view(lang_config)
302 # Extract dimensions from config (different models use different attribute names)
303 d_model = (
304 getattr(lang_config, "hidden_size", None)
305 or getattr(lang_config, "d_model", None)
306 or getattr(lang_config, "model_dim", None) # OpenELM
307 or 0
308 )
309 n_heads_raw = (
310 getattr(lang_config, "num_attention_heads", None)
311 or getattr(lang_config, "n_head", None)
312 or getattr(lang_config, "num_query_heads", None) # OpenELM (may be per-layer list)
313 or getattr(lang_config, "num_heads", None) # Mamba-2 SSM heads
314 or 0
315 )
316 # OpenELM uses per-layer lists for heads; take the max for estimation
317 n_heads = max(n_heads_raw) if isinstance(n_heads_raw, (list, tuple)) else n_heads_raw
318 n_layers = (
319 getattr(lang_config, "num_hidden_layers", None)
320 or getattr(lang_config, "n_layer", None)
321 or getattr(lang_config, "num_transformer_layers", None) # OpenELM
322 or 0
323 )
324 d_mlp = (
325 getattr(lang_config, "intermediate_size", None)
326 or getattr(lang_config, "d_inner", None)
327 or getattr(lang_config, "n_inner", None)
328 or getattr(lang_config, "ffn_dim", None) # OPT
329 or getattr(lang_config, "d_ff", None) # T5
330 )
331 # Gemma 3n exposes a per-layer intermediate_size list (uniform in all released
332 # checkpoints); collapse to max for the scalar param estimate.
333 if isinstance(d_mlp, (list, tuple)): 333 ↛ 334line 333 didn't jump to line 334 because the condition on line 333 was never true
334 d_mlp = max(d_mlp) if d_mlp else None
335 # OpenELM uses per-layer ffn_multipliers instead of a fixed intermediate_size
336 if not d_mlp and d_model: 336 ↛ 337line 336 didn't jump to line 337 because the condition on line 336 was never true
337 ffn_multipliers = getattr(lang_config, "ffn_multipliers", None)
338 if isinstance(ffn_multipliers, (list, tuple)):
339 d_mlp = int(max(ffn_multipliers) * d_model)
340 else:
341 # Many architectures (GPT-2, Bloom, GPT-Neo, GPT-J) leave d_mlp/n_inner
342 # as None and default to 4 * hidden_size internally.
343 d_mlp = 4 * d_model
344 d_vocab = getattr(lang_config, "vocab_size", None) or 0
346 if d_model == 0 or n_layers == 0: 346 ↛ 347line 346 didn't jump to line 347 because the condition on line 346 was never true
347 raise ValueError(f"Could not extract model dimensions from config for {model_id}")
349 # Attention-less architectures (Mamba SSMs) have no heads. Use nominal
350 # values so the estimate doesn't attribute phantom attention params.
351 is_attention_less = n_heads == 0
352 if is_attention_less: 352 ↛ 353line 352 didn't jump to line 353 because the condition on line 352 was never true
353 n_heads = 1
354 d_head = d_model
355 else:
356 d_head = getattr(lang_config, "head_dim", None) or (d_model // n_heads)
358 # Attention parameters: W_Q, W_K, W_V, W_O per layer (skipped for SSMs)
359 if is_attention_less: 359 ↛ 360line 359 didn't jump to line 360 because the condition on line 359 was never true
360 n_params = 0
361 else:
362 n_params = n_layers * (d_model * d_head * n_heads * 4)
364 # MLP parameters (if present)
365 if d_mlp is not None and d_mlp > 0: 365 ↛ 408line 365 didn't jump to line 408 because the condition on line 365 was always true
366 # Check for gated MLP (LLaMA, Gemma, Mistral, Qwen, T5 gated-gelu, etc.)
367 has_gate = getattr(lang_config, "is_gated_act", False) or (
368 hasattr(lang_config, "intermediate_size")
369 and (
370 getattr(lang_config, "hidden_act", None) in ("silu", "gelu", "swiglu")
371 or getattr(lang_config, "model_type", None)
372 in (
373 "llama",
374 "gemma",
375 "gemma2",
376 "gemma3",
377 "mistral",
378 "mixtral",
379 "qwen2",
380 "qwen3",
381 "qwen3_moe",
382 "phi3",
383 "stablelm",
384 )
385 )
386 )
387 mlp_multiplier = 3 if has_gate else 2
388 n_params += n_layers * (d_model * d_mlp * mlp_multiplier)
390 # MoE expert scaling
391 num_experts = (
392 getattr(lang_config, "num_local_experts", None)
393 or getattr(lang_config, "num_experts", None)
394 or getattr(lang_config, "n_routed_experts", None) # DeepSeek-V2/V3
395 )
396 if num_experts and num_experts > 1: 396 ↛ 399line 396 didn't jump to line 399 because the condition on line 396 was never true
397 # Qwen3MoE and similar store per-expert hidden size in moe_intermediate_size;
398 # intermediate_size refers to a dense fallback MLP that we don't use here.
399 moe_d_mlp = getattr(lang_config, "moe_intermediate_size", None) or d_mlp
400 # MLP params scale with num_experts; add gate params per expert
401 mlp_per_layer = d_model * moe_d_mlp * mlp_multiplier
402 moe_per_layer = (mlp_per_layer + d_model) * num_experts
403 # Replace the non-MoE MLP contribution
404 n_params -= n_layers * (d_model * d_mlp * mlp_multiplier)
405 n_params += n_layers * moe_per_layer
407 # Embedding parameters (not in the block-param formula but relevant for memory)
408 n_params += d_vocab * d_model
410 return n_params
413def estimate_benchmark_memory_gb(
414 n_params: int,
415 dtype: str = "float32",
416 phases: Optional[list[int]] = None,
417 use_hf_reference: bool = True,
418 device: str = "cpu",
419) -> float:
420 """Estimate peak memory needed for benchmark suite.
422 Phases run sequentially, so peak memory is the maximum of any single phase,
423 not the sum. The multiplier represents how many model copies exist at peak:
425 Phase 1 (HF ref on): HF ref + Bridge → 2.0x peak
426 Phase 1 (HF ref off): Bridge only → 1.0x peak
427 Phase 2: Bridge only (runtime self-checks) → 1.0x model + overhead
428 Phase 3: Bridge + weight-processing state-dict transient → 2.0x model + overhead
429 Phase 4: Bridge + GPT-2 scorer (~500MB) → ~1.0x model + 0.5 GB
431 Args:
432 n_params: Number of model parameters
433 dtype: Data type for memory calculation
434 phases: Which phases will be run (None = all phases)
435 use_hf_reference: Whether Phase 1 loads an HF reference alongside the
436 Bridge. Mirrors the ``--no-hf-reference`` CLI flag.
438 Returns:
439 Estimated peak memory in GB
440 """
441 bytes_per_param = {"float32": 4, "float16": 2, "bfloat16": 2}
442 bpp = bytes_per_param.get(dtype, 4)
443 model_size_gb = n_params * bpp / (1024**3)
445 # Phase-4 judge overhead: measured 2.33 GB RSS loading Qwen2.5-0.5B fp32
446 # on CPU (494M params). Kept slightly above the measurement; over-counting
447 # is the safe direction.
448 # The CPU-pinned judge never occupies accelerator memory; charging it to
449 # a cuda budget produces spurious VRAM skips.
450 judge_overhead_gb = 2.5 if device == "cpu" else 0.0
452 # Activation/framework overhead as a fraction of model size
453 overhead_fraction = 0.2
455 # Determine peak memory across all requested phases
456 phase_peaks = []
458 if phases is None: 458 ↛ 459line 458 didn't jump to line 459 because the condition on line 458 was never true
459 phases = list(TEXT_PHASES)
461 for p in phases:
462 if p == 1:
463 # HF ref + Bridge (2 copies) or Bridge alone
464 multiplier = 2.0 if use_hf_reference else 1.0
465 phase_peaks.append(model_size_gb * multiplier * (1 + overhead_fraction))
466 elif p == 2:
467 # Bridge only (runtime self-checks + saved-HF equivalence)
468 phase_peaks.append(model_size_gb * 1.0 * (1 + overhead_fraction))
469 elif p == 3:
470 # Bridge + the full state-dict copy materialized during weight processing
471 phase_peaks.append(model_size_gb * 2.0 * (1 + overhead_fraction))
472 elif p == 4: 472 ↛ 461line 472 didn't jump to line 461 because the condition on line 472 was always true
473 # Bridge + judge
474 phase_peaks.append(model_size_gb * (1 + overhead_fraction) + judge_overhead_gb)
476 return max(phase_peaks) if phase_peaks else model_size_gb
479def get_available_memory_gb(device: str) -> float:
480 """Detect available memory on the target device.
482 Args:
483 device: "cpu" or "cuda"
485 Returns:
486 Available memory in GB
487 """
488 if device.startswith("cuda"):
489 try:
490 import torch
492 if torch.cuda.is_available():
493 device_idx = 0
494 if ":" in device:
495 device_idx = int(device.split(":")[1])
496 props = torch.cuda.get_device_properties(device_idx)
497 return props.total_memory / (1024**3)
498 except Exception:
499 pass
500 return 8.0 # Conservative default for GPU
502 # CPU: use psutil if available, else conservative default
503 try:
504 import psutil
506 return psutil.virtual_memory().available / (1024**3)
507 except ImportError:
508 return 16.0 # Conservative default for CPU
511def select_models_for_verification(
512 per_arch: int = 10,
513 architectures: Optional[list[str]] = None,
514 limit: Optional[int] = None,
515 resume_progress: Optional[VerificationProgress] = None,
516 retry_failed: bool = False,
517 reverify: bool = False,
518) -> list[ModelCandidate]:
519 """Select models for verification from the registry.
521 Loads supported_models.json (already sorted by downloads).
522 Takes the top N unverified models per architecture.
524 Args:
525 per_arch: Maximum models to verify per architecture
526 architectures: Filter to specific architectures (None = all)
527 limit: Total model cap (None = no cap)
528 resume_progress: If resuming, skip already-tested models
529 retry_failed: If True, include previously failed models for re-testing
530 reverify: If True, ignore previous status and re-test all matching models
532 Returns:
533 List of ModelCandidate objects to verify
534 """
535 already_tested: set[str] = set()
536 if resume_progress and not reverify:
537 already_tested = set(resume_progress.tested)
538 if retry_failed:
539 # Remove failed models from already_tested so they get re-selected
540 failed_set = set(resume_progress.failed)
541 already_tested -= failed_set
543 data = load_supported_models_raw()
544 models = data.get("models", [])
546 # Group by architecture
547 by_arch: dict[str, list[dict]] = {}
548 for model in models:
549 arch = model["architecture_id"]
550 by_arch.setdefault(arch, []).append(model)
552 # Determine which architectures to scan
553 if architectures:
554 arch_ids = architectures
555 else:
556 arch_ids = sorted(by_arch.keys())
558 candidates: list[ModelCandidate] = []
560 for arch in arch_ids:
561 arch_models = by_arch.get(arch, [])
562 count = 0
564 for model in arch_models:
565 model_id = model["model_id"]
567 # Skip already-verified or already-tested models
568 if not reverify:
569 model_status = model.get("status", 0)
570 if model_status == STATUS_VERIFIED or model_status == STATUS_SKIPPED:
571 continue
572 if model_status == STATUS_FAILED and not retry_failed:
573 continue
574 if model_id in already_tested:
575 continue
577 # Check per-arch limit
578 if count >= per_arch:
579 break
581 count += 1
582 candidates.append(ModelCandidate(model_id=model_id, architecture_id=arch))
584 # Check total limit
585 if limit and len(candidates) >= limit:
586 return candidates
588 return candidates
591# Phase-score extraction and pass-status logic live in registry_io
592# (extract_phase_scores / pass_status) — the shared home for both
593# registry-writing paths, this module and main_benchmark.update_model_registry.
596def _extract_prompt_profile(results: list) -> Optional[str]:
597 """Effective Phase-4 prompt profile from the benchmark details, or None
598 when no Phase-4 result exists. The default "continuation" is reported so
599 the registry write can clear a stale non-default key."""
600 for result in results:
601 if result.phase == 4 and result.details:
602 profile = result.details.get("prompt_profile")
603 if isinstance(profile, str): 603 ↛ 600line 603 didn't jump to line 600 because the condition on line 603 was always true
604 return profile
605 return None
608# Per-phase minimum score thresholds (0-100).
609# Phase 1: Core correctness (bridge vs HF) — must pass everything.
610# Phase 2: Hook/cache/gradient tests — most should pass.
611# Phase 3: Weight processing tests — most should pass.
612# Phase 4: Text quality — inherently fuzzy, keep lenient.
613_MIN_PHASE_SCORES: dict[int, float] = {
614 1: 100.0,
615 2: 75.0,
616 3: 75.0,
617 # Phase 4 floor == the benchmark pass line; a gap between them lets a
618 # failing score carry a clean "completed" note.
619 4: p4_pass_threshold(),
620 7: 75.0,
621 8: 75.0,
622 9: 75.0,
623}
624_DEFAULT_MIN_PHASE_SCORE = 50.0
626from transformer_lens.utilities.architectures import classify_architecture
628# Tests that MUST pass for a phase to be considered passing, regardless of
629# the overall percentage score. If any required test fails, the phase fails
630# even if the score is above the minimum threshold.
631_REQUIRED_PHASE_TESTS: dict[int, list[str]] = {
632 2: ["logits_equivalence", "loss_equivalence"],
633 3: ["logits_equivalence", "loss_equivalence"],
634 7: ["multimodal_forward"],
635 8: ["audio_forward", "audio_text_forward"],
636 9: ["vision_forward", "vision_cache"],
637}
639# Failure text for a modality phase that produced no score — either absent from
640# phase_scores (all tests skipped) or explicitly NULL.
641_MODALITY_NULL_MESSAGES: dict[int, str] = {
642 7: "P7=NULL (multimodal tests skipped — processor unavailable)",
643 8: "P8=NULL (audio tests skipped — no results)",
644 9: "P9=NULL (vision tests skipped — no results)",
645}
648def _measured_nothing(phase_scores: dict) -> bool:
649 """True when no phase produced a score, so the run verified nothing.
651 An adapter's ``applicable_phases`` can prune the requested phases to empty.
652 That leaves ``required_phases`` empty as well, so no score check fires and a
653 run that measured nothing would otherwise be recorded as VERIFIED.
655 ``is not None`` rather than truthiness: 0.0 is a real score.
656 """
657 return not any(score is not None for score in phase_scores.values())
660def _check_phase_scores(
661 phase_scores: dict[int, Optional[float]],
662 all_results: list,
663 required_phases: Optional[set[int]] = None,
664) -> Optional[str]:
665 """Check phase scores against per-phase minimum thresholds and required tests.
667 A phase fails if:
668 1. Its overall score is below the minimum threshold, OR
669 2. Any of its required tests (per _REQUIRED_PHASE_TESTS) failed.
671 Phase 4 (text quality) is excluded — it is a quality metric, not a
672 correctness check. Low text quality is surfaced in the verification
673 note via _build_verified_note() but never causes a model to fail.
675 Args:
676 phase_scores: Per-phase scores; a phase whose tests all skipped is
677 absent entirely (``extract_phase_scores`` omits empty phases).
678 all_results: Benchmark results, used to name the failing tests.
679 required_phases: Phases this architecture must produce a score for —
680 the core set from ``_full_and_core_phases``. A required modality
681 phase that is absent counts as NULL, not as a pass.
683 Returns an error message if any phase fails, or None if all phases pass.
684 The message includes the names of failed tests.
685 """
686 from transformer_lens.benchmarks.utils import BenchmarkSeverity
688 failing_phases: list[str] = []
690 # A required modality phase whose tests all skipped never reaches phase_scores.
691 for phase in sorted((required_phases or set()) - set(phase_scores)):
692 if phase in _MODALITY_NULL_MESSAGES:
693 failing_phases.append(_MODALITY_NULL_MESSAGES[phase])
695 for phase, score in sorted(phase_scores.items()):
696 if score is None: 696 ↛ 700line 696 didn't jump to line 700 because the condition on line 696 was never true
697 # Phase 7 (multimodal), 8 (audio), or 9 (vision) with a NULL score
698 # means the modality tests never ran. This is a verification
699 # failure, not something to silently skip.
700 if phase in _MODALITY_NULL_MESSAGES:
701 failing_phases.append(_MODALITY_NULL_MESSAGES[phase])
702 continue
704 # Phase 4 is a quality metric, not a pass/fail check — skip it here.
705 # Low text quality is reported in the note by _build_verified_note().
706 if phase == 4:
707 continue
709 # Check 1: overall score threshold
710 threshold = _MIN_PHASE_SCORES.get(phase, _DEFAULT_MIN_PHASE_SCORE)
711 if score < threshold:
712 failed_tests = [
713 r.name
714 for r in all_results
715 if r.phase == phase and not r.passed and r.severity != BenchmarkSeverity.SKIPPED
716 ]
717 tests_str = ", ".join(failed_tests) if failed_tests else "unknown"
718 failing_phases.append(f"P{phase}={score}% < {threshold}% (failed: {tests_str})")
719 continue # Already failing; no need to also check required tests
721 # Check 2: required tests must pass
722 required_tests = _REQUIRED_PHASE_TESTS.get(phase, [])
723 if required_tests:
724 failed_required = [
725 r.name
726 for r in all_results
727 if r.phase == phase
728 and r.name in required_tests
729 and not r.passed
730 and r.severity != BenchmarkSeverity.SKIPPED
731 ]
732 if failed_required: 732 ↛ 733line 732 didn't jump to line 733 because the condition on line 732 was never true
733 tests_str = ", ".join(failed_required)
734 failing_phases.append(f"P{phase}={score}% but required tests failed: {tests_str}")
736 if failing_phases:
737 return f"Below threshold: {'; '.join(failing_phases)}"
738 return None
741def _build_verified_note(
742 phase_scores: dict[int, Optional[float]],
743 all_results: list,
744) -> str:
745 """Build a verification note summarizing phase scores.
747 Phase 4 (text quality) is excluded from the score summary since it's a
748 quality metric, not a pass/fail comparison. It only contributes a "low
749 text quality" flag when below threshold.
750 """
751 from transformer_lens.benchmarks.utils import BenchmarkSeverity
753 issue_parts: list[str] = []
754 low_text_quality = False
756 for phase in sorted(phase_scores):
757 score = phase_scores[phase]
758 if score is None: 758 ↛ 759line 758 didn't jump to line 759 because the condition on line 758 was never true
759 continue
760 # Phase 4 is a quality score, not a pass/fail comparison — don't
761 # include it in the normal score summary.
762 if phase == 4:
763 threshold = _MIN_PHASE_SCORES.get(4, _DEFAULT_MIN_PHASE_SCORE)
764 if score < threshold: 764 ↛ 765line 764 didn't jump to line 765 because the condition on line 764 was never true
765 low_text_quality = True
766 continue
768 if score < 100.0: 768 ↛ 769line 768 didn't jump to line 769 because the condition on line 768 was never true
769 failed_tests = [
770 r.name
771 for r in all_results
772 if r.phase == phase and not r.passed and r.severity != BenchmarkSeverity.SKIPPED
773 ]
774 if failed_tests:
775 issue_parts.append(f"P{phase}={score}% (failed: {', '.join(failed_tests)})")
776 else:
777 issue_parts.append(f"P{phase}={score}%")
779 p4_uncovered = next(
780 (
781 r.message
782 for r in all_results
783 if r.phase == 4
784 and r.severity == BenchmarkSeverity.SKIPPED
785 and r.message.startswith("P4 skipped:")
786 ),
787 None,
788 )
789 suffix = ""
790 if p4_uncovered: 790 ↛ 792line 790 didn't jump to line 792 because the condition on line 790 was never true
791 # Keep the gap visible in the registry until prompt coverage is added.
792 reason = p4_uncovered.split("—")[0].replace("P4 skipped:", "").strip()
793 suffix = f"; P4 skipped (uncovered: {reason} — file a coverage issue)"
795 if issue_parts and low_text_quality: 795 ↛ 796line 795 didn't jump to line 796 because the condition on line 795 was never true
796 return (
797 f"Full verification completed with issues, low text quality: {'; '.join(issue_parts)}"
798 + suffix
799 )
800 if issue_parts: 800 ↛ 801line 800 didn't jump to line 801 because the condition on line 800 was never true
801 return f"Full verification completed with issues: {'; '.join(issue_parts)}" + suffix
802 if low_text_quality: 802 ↛ 803line 802 didn't jump to line 803 because the condition on line 802 was never true
803 return "Full verification completed with issues, low text quality" + suffix
804 return "Full verification completed" + suffix
807def _preserved_issue_suffix(model_id: str, eff_phases) -> str:
808 """Sub-100 scores from phases not re-run this pass stay visible in the
809 note; a partial pass must not overwrite tracked residue."""
810 from transformer_lens.tools.model_registry.registry_io import (
811 load_supported_models_raw,
812 )
814 try:
815 entry = next(
816 (
817 m
818 for m in load_supported_models_raw().get("models", [])
819 if m.get("model_id") == model_id
820 ),
821 None,
822 )
823 except OSError:
824 return ""
825 if entry is None: 825 ↛ 826line 825 didn't jump to line 826 because the condition on line 825 was never true
826 return ""
827 residue = []
828 for phase in (2, 3, 7, 8, 9):
829 if phase in (eff_phases or []):
830 continue
831 score = entry.get(f"phase{phase}_score")
832 if score is not None and score < 100.0:
833 residue.append(f"P{phase}={score}%")
834 if not residue:
835 return ""
836 return f" (prior issues retained: {', '.join(residue)})"
839def _p1_only_core_note(p4_score, all_results: list) -> str:
840 """Note for a core run where P1 passed but P4 did not contribute a pass.
842 A skipped P4 is a coverage gap, not a quality failure — the stale
843 (possibly old-scale) score must not be relabeled "poor"."""
844 from transformer_lens.benchmarks.utils import BenchmarkSeverity
846 p4_skip_msg = next(
847 (
848 r.message
849 for r in all_results
850 if r.phase == 4
851 and r.severity == BenchmarkSeverity.SKIPPED
852 and r.message.startswith("P4 skipped:")
853 ),
854 None,
855 )
856 if p4_skip_msg is not None:
857 reason = p4_skip_msg.split("—")[0].replace("P4 skipped:", "").strip()
858 return f"Core verification passed; P4 skipped ({reason})"
859 if p4_score is None:
860 return "Core verification passed, but text quality benchmark errored. Needs review"
861 return f"Core verification passed, but text quality poor (P4={p4_score}). Needs review"
864def _clear_hf_cache(quiet: bool = False) -> None:
865 """Remove downloaded model weights from the HuggingFace cache to free disk."""
866 from pathlib import Path
868 cache_dir = Path.home() / ".cache" / "huggingface" / "hub"
869 if not cache_dir.exists(): 869 ↛ 870line 869 didn't jump to line 870 because the condition on line 869 was never true
870 return
872 from transformer_lens.benchmarks.text_quality import JUDGE_MODEL_ID
874 # The pinned Phase-4 judge is needed by every run; deleting it here would
875 # force a re-download per family.
876 judge_dir = "models--" + JUDGE_MODEL_ID.replace("/", "--")
878 freed = 0
879 for blobs_dir in cache_dir.glob("models--*/blobs"):
880 if blobs_dir.parent.name == judge_dir:
881 continue
882 for blob in blobs_dir.iterdir():
883 try:
884 size = blob.stat().st_size
885 blob.unlink()
886 freed += size
887 except OSError:
888 pass
890 if not quiet and freed > 0: 890 ↛ 891line 890 didn't jump to line 891 because the condition on line 890 was never true
891 print(f" Cleared {freed / (1024**3):.1f} GB from HuggingFace cache")
894def _save_checkpoint(progress: VerificationProgress) -> None:
895 """Save verification progress to checkpoint file."""
896 with open(_CHECKPOINT_PATH, "w") as f:
897 json.dump(progress.to_dict(), f, indent=2)
898 f.write("\n")
901def _skip_model(
902 model_id: str, arch: str, note: str, progress: VerificationProgress, quiet: bool
903) -> None:
904 """Record a model as skipped with ``note``, preserving an existing verified or provisional
905 status, and checkpoint. Callers ``continue`` the loop afterwards.
906 """
907 if not quiet:
908 print(f" SKIP: {note}")
909 if _get_current_model_status(model_id, arch) not in (STATUS_VERIFIED, STATUS_PROVISIONAL):
910 update_model_status(model_id, arch, STATUS_SKIPPED, note=note, sanitize_fn=_sanitize_note)
911 elif not quiet:
912 print(" (preserving existing verified/provisional status)")
913 progress.skipped.append(model_id)
914 _save_checkpoint(progress)
917def _load_checkpoint() -> Optional[VerificationProgress]:
918 """Load verification progress from checkpoint file."""
919 if not _CHECKPOINT_PATH.exists():
920 return None
921 try:
922 with open(_CHECKPOINT_PATH) as f:
923 data = json.load(f)
924 return VerificationProgress.from_dict(data)
925 except (json.JSONDecodeError, KeyError):
926 return None
929def verify_models(
930 candidates: list[ModelCandidate],
931 device: str = "cpu",
932 max_memory_gb: Optional[float] = None,
933 dtype: str = "float32",
934 use_hf_reference: bool = True,
935 phases: Optional[list[int]] = None,
936 quiet: bool = False,
937 progress: Optional[VerificationProgress] = None,
938) -> VerificationProgress:
939 """Run verification benchmarks on a list of model candidates.
941 Args:
942 candidates: Models to verify
943 device: Device for benchmarks
944 max_memory_gb: Memory limit (auto-detected if None)
945 dtype: Dtype for memory estimation
946 use_hf_reference: Whether to compare against HuggingFace model
947 phases: Which benchmark phases to run
948 quiet: Suppress verbose output
949 progress: Existing progress for resume
951 Returns:
952 VerificationProgress with results
953 """
954 from transformer_lens.benchmarks.main_benchmark import run_benchmark_suite
956 if progress is None: 956 ↛ 959line 956 didn't jump to line 959 because the condition on line 956 was always true
957 progress = VerificationProgress(start_time=datetime.now().isoformat())
959 if max_memory_gb is None: 959 ↛ 960line 959 didn't jump to line 960 because the condition on line 959 was never true
960 max_memory_gb = get_available_memory_gb(device)
961 if not quiet:
962 print(f"Auto-detected available memory: {max_memory_gb:.1f} GB")
964 # phases stays None = full verification for the model.
966 # Pre-load the Phase-4 judge so it persists across all models in the batch
967 # instead of being loaded and destroyed for each one. Only when some model
968 # runs Phase 4: otherwise it holds ~2.3 GB the models need.
969 _judge_model = None
970 _judge_tokenizer = None
971 if _runs_phase_4(candidates, phases):
972 try:
973 from transformer_lens.benchmarks.text_quality import (
974 JUDGE_MODEL_ID,
975 JUDGE_REVISION,
976 load_judge,
977 )
979 _judge_model, _judge_tokenizer = load_judge()
980 if not quiet: 980 ↛ 981line 980 didn't jump to line 981 because the condition on line 980 was never true
981 print(f"Pre-loaded Phase 4 judge {JUDGE_MODEL_ID}@{JUDGE_REVISION[:8]}")
982 except Exception as e:
983 if not quiet:
984 print(f"Warning: Could not pre-load Phase 4 judge: {e}")
985 print(" Phase 4 will load its own judge per model.")
987 total = len(candidates)
988 for i, candidate in enumerate(candidates, 1):
989 # Check for graceful interrupt between models
990 if _interrupt_requested: 990 ↛ 991line 990 didn't jump to line 991 because the condition on line 990 was never true
991 if not quiet:
992 print(
993 f"\nStopping gracefully. Progress saved "
994 f"({len(progress.verified)} verified, "
995 f"{len(progress.provisional)} provisional)."
996 )
997 _save_checkpoint(progress)
998 raise SystemExit(_EXIT_GRACEFUL_INTERRUPT)
1000 model_id = candidate.model_id
1001 arch = candidate.architecture_id
1003 if not quiet: 1003 ↛ 1004line 1003 didn't jump to line 1004 because the condition on line 1003 was never true
1004 print(f"\n{'='*70}")
1005 print(f"[{i}/{total}] {model_id} ({arch})")
1006 print(f"{'='*70}")
1008 progress.tested.append(model_id)
1010 # Step 0: Skip formats with no HF loader path (GGUF / MLX / FP4 / FP8).
1011 if is_incompatible_quantized(model_id): 1011 ↛ 1012line 1011 didn't jump to line 1012 because the condition on line 1011 was never true
1012 _skip_model(model_id, arch, QUANTIZED_NOTE, progress, quiet)
1013 continue
1015 # Step 0a: skip HF-loadable quantized models when their loader lib is missing.
1016 required_lib = required_quant_library_for_model(model_id)
1017 if required_lib is not None: 1017 ↛ 1018line 1017 didn't jump to line 1018 because the condition on line 1017 was never true
1018 import importlib.util
1020 if importlib.util.find_spec(required_lib) is None:
1021 note = f"Skipped: {required_lib} not installed (required to load this quantized format)"
1022 _skip_model(model_id, arch, note, progress, quiet)
1023 continue
1025 # Step 0b: Check adapter-level phase applicability. applicable_phases=[]
1026 # means no phase applies (a genuinely unsupported architecture — rare);
1027 # SSM / recurrent families run the full [1, 2, 3, 4].
1028 from transformer_lens.factories.architecture_adapter_factory import (
1029 SUPPORTED_ARCHITECTURES,
1030 )
1032 adapter_cls = SUPPORTED_ARCHITECTURES.get(arch)
1033 eff_phases = phases if phases is not None else _default_phases_for_architecture(arch)
1034 phases_to_run = _phases_to_run(arch, eff_phases)
1035 if adapter_cls is not None and not phases_to_run: 1035 ↛ 1036line 1035 didn't jump to line 1036 because the condition on line 1035 was never true
1036 applicable = getattr(adapter_cls, "applicable_phases", list(TEXT_PHASES))
1037 note = (
1038 f"Architecture {arch} has applicable_phases={applicable}; "
1039 f"verify_models coverage is deferred. Verification lives "
1040 f"in integration tests."
1041 )
1042 _skip_model(model_id, arch, note, progress, quiet)
1043 continue
1045 # Step 1: Estimate parameters
1046 try:
1047 n_params = estimate_model_params(model_id)
1048 candidate.estimated_params = n_params
1049 if not quiet: 1049 ↛ 1050line 1049 didn't jump to line 1050 because the condition on line 1049 was never true
1050 print(f" Estimated parameters: {n_params:,}")
1051 except Exception as e:
1052 _skip_model(model_id, arch, f"Config unavailable: {str(e)[:200]}", progress, quiet)
1053 continue
1055 # Step 2: Check memory
1056 estimated_mem = estimate_benchmark_memory_gb(
1057 n_params, dtype, phases=phases_to_run, use_hf_reference=use_hf_reference, device=device
1058 )
1059 candidate.estimated_memory_gb = estimated_mem
1060 if not quiet: 1060 ↛ 1061line 1060 didn't jump to line 1061 because the condition on line 1060 was never true
1061 print(
1062 f" Estimated benchmark memory: {estimated_mem:.1f} GB (limit: {max_memory_gb:.1f} GB)"
1063 )
1065 if estimated_mem > max_memory_gb: 1065 ↛ 1066line 1065 didn't jump to line 1066 because the condition on line 1065 was never true
1066 note = f"Estimated {estimated_mem:.1f} GB exceeds {max_memory_gb:.1f} GB limit"
1067 _skip_model(model_id, arch, note, progress, quiet)
1068 continue
1070 # Step 3: Run benchmarks (all phases in a single call to share models)
1071 all_results: list = []
1072 error_msg: Optional[str] = None
1074 needs_remote_code = any(
1075 model_id.startswith(prefix) for prefix in REMOTE_CODE_MODEL_PREFIXES
1076 )
1078 # Convert string dtype to torch.dtype for benchmark suite
1079 import torch
1081 _dtype_map = {
1082 "float32": torch.float32,
1083 "float16": torch.float16,
1084 "bfloat16": torch.bfloat16,
1085 }
1086 torch_dtype = _dtype_map[dtype]
1088 from transformer_lens.benchmarks.text_quality_profiles import resolve_profile
1089 from transformer_lens.tools.model_registry.registry_io import (
1090 registry_prompt_profile,
1091 )
1093 resolved_profile = str(resolve_profile(model_id, arch, registry_prompt_profile(model_id)))
1094 if not quiet: 1094 ↛ 1095line 1094 didn't jump to line 1095 because the condition on line 1094 was never true
1095 print(f" Prompt profile: {resolved_profile}")
1096 print(f" Running phases {phases} in a single benchmark call...")
1097 try:
1098 all_results = run_benchmark_suite(
1099 model_id,
1100 device=device,
1101 dtype=torch_dtype,
1102 use_hf_reference=use_hf_reference,
1103 verbose=not quiet,
1104 phases=phases_to_run,
1105 trust_remote_code=needs_remote_code,
1106 judge_model=_judge_model,
1107 judge_tokenizer=_judge_tokenizer,
1108 prompt_profile=resolved_profile,
1109 )
1110 except Exception as e:
1111 error_msg = str(e)
1112 if not quiet:
1113 print(f" Benchmark failed: {error_msg[:200]}")
1115 phase_scores = extract_phase_scores(all_results)
1117 if not error_msg: 1117 ↛ 1127line 1117 didn't jump to line 1127 because the condition on line 1117 was always true
1118 # Only require the core phases this run actually requested, so a
1119 # partial run (e.g. --phases 1 2) isn't failed for a missing P7.
1120 _, core_for_arch = _full_and_core_phases(arch)
1121 score_error = _check_phase_scores(
1122 phase_scores, all_results, required_phases=core_for_arch & set(eff_phases)
1123 )
1124 if score_error: 1124 ↛ 1125line 1124 didn't jump to line 1125 because the condition on line 1124 was never true
1125 error_msg = score_error
1127 if error_msg: 1127 ↛ 1128line 1127 didn't jump to line 1128 because the condition on line 1127 was never true
1128 is_oom = "out of memory" in error_msg.lower() or "oom" in error_msg.lower()
1129 if is_oom:
1130 note = "OOM during benchmark"
1131 else:
1132 # Include the specific error from failed results (e.g., tokenizer
1133 # errors, load failures) so the note explains WHY it failed.
1134 root_errors = [r.message for r in all_results if not r.passed and r.message]
1135 if root_errors:
1136 # Deduplicate and use first unique error as the detail
1137 unique_errors = list(dict.fromkeys(root_errors))
1138 detail = unique_errors[0][:150]
1139 note = f"{error_msg[:100]} — {detail}"
1140 else:
1141 note = error_msg[:200]
1142 final_status = STATUS_FAILED
1143 else:
1144 note = _build_verified_note(phase_scores, all_results)
1145 final_status = STATUS_VERIFIED
1147 # When running a partial phase set (e.g., --phases 4 for backfill),
1148 # only update the phase scores that were run. Don't change the
1149 # model's overall status or note — those reflect the full
1150 # verification and should only be set by a complete run.
1151 kind = classify_architecture(arch)
1152 is_multimodal = kind == "multimodal"
1153 is_audio = kind == "audio"
1154 is_vision = kind == "vision"
1155 full_phases, core_required = _full_and_core_phases(arch)
1156 is_partial_run = set(eff_phases) != full_phases
1158 if is_partial_run and phase_scores: 1158 ↛ 1163line 1158 didn't jump to line 1163 because the condition on line 1158 was never true
1159 # Only write scores for phases that were actually requested.
1160 # Bridge load failures can produce Phase 1-tagged error results
1161 # even during Phase 4-only runs — don't let those corrupt
1162 # existing scores for unrequested phases.
1163 filtered_scores = {p: s for p, s in phase_scores.items() if p in eff_phases}
1164 if filtered_scores:
1165 if not quiet:
1166 score_parts = [f"P{p}={s}%" for p, s in sorted(filtered_scores.items())]
1167 print(f" Partial phase update: {', '.join(score_parts)}")
1169 # Core verification: P1+P4 for text-only, P1+P4+P7 for
1170 # multimodal, P9 for vision.
1171 is_core_verification = set(eff_phases) >= core_required
1172 partial_status = None
1173 partial_note = None
1175 if is_core_verification:
1176 p1 = filtered_scores.get(1)
1177 p4 = filtered_scores.get(4)
1178 p1_pass = p1 is not None and p1 >= _MIN_PHASE_SCORES.get(
1179 1, _DEFAULT_MIN_PHASE_SCORE
1180 )
1181 p4_pass = p4 is not None and p4 >= _MIN_PHASE_SCORES.get(
1182 4, _DEFAULT_MIN_PHASE_SCORE
1183 )
1185 # For multimodal, Phase 7 is required. A score below 75%
1186 # or a missing score (NULL — processor unavailable) both
1187 # count as failures.
1188 p7_pass = True
1189 if is_multimodal:
1190 p7 = filtered_scores.get(7)
1191 if p7 is not None:
1192 p7_pass = p7 >= _MIN_PHASE_SCORES.get(7, _DEFAULT_MIN_PHASE_SCORE)
1193 else:
1194 p7_pass = False
1196 # For audio models, Phase 8 is required; Phase 4 is not applicable
1197 p8_pass = True
1198 if is_audio:
1199 p4_pass = True # Audio models skip text quality
1200 p8 = filtered_scores.get(8)
1201 if p8 is not None:
1202 p8_pass = p8 >= _MIN_PHASE_SCORES.get(8, _DEFAULT_MIN_PHASE_SCORE)
1203 else:
1204 p8_pass = False
1206 # For vision models, Phase 9 is required; text phases 1/4
1207 # are not applicable (no text tower).
1208 p9_pass = True
1209 if is_vision:
1210 p1_pass = True
1211 p4_pass = True
1212 p9 = filtered_scores.get(9)
1213 if p9 is not None:
1214 p9_pass = p9 >= _MIN_PHASE_SCORES.get(9, _DEFAULT_MIN_PHASE_SCORE)
1215 else:
1216 p9_pass = False
1218 if p1_pass and p4_pass and p7_pass and p8_pass and p9_pass:
1219 partial_status = STATUS_VERIFIED
1220 partial_note = "Core verification completed" + _preserved_issue_suffix(
1221 model_id, eff_phases
1222 )
1223 elif p1_pass and p4_pass and not p7_pass:
1224 p7_score = filtered_scores.get(7)
1225 if p7_score is None:
1226 partial_status = STATUS_FAILED
1227 partial_note = (
1228 "Core verification failed: multimodal tests skipped "
1229 "(processor unavailable)"
1230 )
1231 else:
1232 partial_status = STATUS_FAILED
1233 partial_note = (
1234 f"Core verification failed: multimodal tests "
1235 f"scored {p7_score}% (requires >= "
1236 f"{_MIN_PHASE_SCORES.get(7, _DEFAULT_MIN_PHASE_SCORE):g}%)"
1237 )
1238 elif p1_pass and p4_pass and not p9_pass:
1239 p9_score = filtered_scores.get(9)
1240 partial_status = STATUS_FAILED
1241 if p9_score is None:
1242 partial_note = (
1243 "Core verification failed: vision tests skipped (no results)"
1244 )
1245 else:
1246 partial_note = (
1247 f"Core verification failed: vision tests "
1248 f"scored {p9_score}% (requires >= "
1249 f"{_MIN_PHASE_SCORES.get(9, _DEFAULT_MIN_PHASE_SCORE):g}%)"
1250 )
1251 elif p1_pass:
1252 partial_status = STATUS_VERIFIED
1253 partial_note = _p1_only_core_note(p4, all_results)
1254 else:
1255 # P1 failed — build a descriptive failure note
1256 partial_status = STATUS_FAILED
1257 if error_msg:
1258 partial_note = f"CORE FAILED: {error_msg[:200]}"
1259 else:
1260 # Score-based failure — include details
1261 from transformer_lens.benchmarks.utils import (
1262 BenchmarkSeverity,
1263 )
1265 failed_tests = [
1266 r.name
1267 for r in all_results
1268 if r.phase == 1
1269 and not r.passed
1270 and r.severity != BenchmarkSeverity.SKIPPED
1271 ]
1272 tests_str = ", ".join(failed_tests) if failed_tests else "unknown"
1273 partial_note = f"CORE FAILED: P1={p1}% (failed: {tests_str})"
1275 # A structural-only core pass (--no-hf-reference) is provisional,
1276 # never numerically compared to HF, so it must not count as verified.
1277 if partial_status == STATUS_VERIFIED and not use_hf_reference:
1278 partial_status = STATUS_PROVISIONAL
1279 partial_note = f"Structural only (no HF reference): {partial_note}"
1281 if not quiet:
1282 print(f" {partial_note}")
1284 update_model_status(
1285 model_id,
1286 arch,
1287 status=partial_status,
1288 phase_scores=filtered_scores,
1289 note=partial_note,
1290 prompt_profile=_extract_prompt_profile(all_results),
1291 )
1292 # A provisional run was not numerically verified; do not write a
1293 # verification-history record (VerificationHistory.is_verified()
1294 # treats any record as verified — a second "counts as verified" path).
1295 if partial_status != STATUS_PROVISIONAL:
1296 add_verification_record(
1297 model_id,
1298 arch,
1299 notes=partial_note,
1300 sanitize_fn=_sanitize_note,
1301 prompt_profile=_extract_prompt_profile(all_results),
1302 p4_scoring_version=(P4_SCORING_VERSION if 4 in filtered_scores else None),
1303 )
1304 if partial_status == STATUS_FAILED:
1305 progress.failed.append(model_id)
1306 elif partial_status == STATUS_PROVISIONAL:
1307 progress.provisional.append(model_id)
1308 elif partial_status is None:
1309 # Scores were written but the status deliberately was not:
1310 # this phase set cannot establish core verification for
1311 # this architecture class. Reporting it as verified is how
1312 # a model ends up with all-pass scores and status 0.
1313 if not quiet:
1314 print(
1315 f" Scores updated, status unchanged — core verification for "
1316 f"{arch} requires phases {sorted(core_required)}, "
1317 f"this run had {sorted(eff_phases)}."
1318 )
1319 progress.skipped.append(model_id)
1320 else:
1321 progress.verified.append(model_id)
1322 else:
1323 if not quiet:
1324 print(f" No results for requested phases {eff_phases} — skipping update")
1325 progress.skipped.append(model_id)
1326 elif final_status == STATUS_VERIFIED and _measured_nothing(phase_scores): 1326 ↛ 1333line 1326 didn't jump to line 1333 because the condition on line 1326 was always true
1327 if not quiet: 1327 ↛ 1328line 1327 didn't jump to line 1328 because the condition on line 1327 was never true
1328 print(
1329 f" No phase produced a score (requested {eff_phases}) — "
1330 f"status left unchanged"
1331 )
1332 progress.skipped.append(model_id)
1333 elif final_status == STATUS_VERIFIED:
1334 # A passing run is VERIFIED only if it was numerically compared to an
1335 # HF reference; a --no-hf-reference (structural-only) pass is PROVISIONAL.
1336 written_status = pass_status(use_hf_reference)
1337 is_provisional = written_status == STATUS_PROVISIONAL
1338 if is_provisional:
1339 note = f"Structural only (no HF reference): {note}"
1340 if not quiet:
1341 label = "PROVISIONAL" if is_provisional else "VERIFIED"
1342 print(
1343 f" {label}: P1={phase_scores.get(1)}%, "
1344 f"P2={phase_scores.get(2)}%, P3={phase_scores.get(3)}%, "
1345 f"P4={phase_scores.get(4)}%, P7={phase_scores.get(7)}%, "
1346 f"P8={phase_scores.get(8)}%, P9={phase_scores.get(9)}%"
1347 )
1348 update_model_status(
1349 model_id,
1350 arch,
1351 written_status,
1352 phase_scores=phase_scores,
1353 note=note,
1354 prompt_profile=_extract_prompt_profile(all_results),
1355 )
1356 # Provisional runs are not numerically verified — no history record
1357 # (is_verified() would otherwise report them as verified).
1358 if not is_provisional:
1359 add_verification_record(
1360 model_id,
1361 arch,
1362 notes=note,
1363 prompt_profile=_extract_prompt_profile(all_results),
1364 p4_scoring_version=(P4_SCORING_VERSION if 4 in phase_scores else None),
1365 )
1366 if is_provisional:
1367 progress.provisional.append(model_id)
1368 else:
1369 progress.verified.append(model_id)
1370 else:
1371 if not quiet:
1372 print(f" FAILED: {note}")
1373 if any(v is not None for v in phase_scores.values()):
1374 print(
1375 f" Partial scores saved: P1={phase_scores.get(1)}%, "
1376 f"P2={phase_scores.get(2)}%, P3={phase_scores.get(3)}%, "
1377 f"P4={phase_scores.get(4)}%, P7={phase_scores.get(7)}%, "
1378 f"P8={phase_scores.get(8)}%, P9={phase_scores.get(9)}%"
1379 )
1380 update_model_status(
1381 model_id,
1382 arch,
1383 STATUS_FAILED,
1384 note=note,
1385 phase_scores=phase_scores,
1386 sanitize_fn=_sanitize_note,
1387 prompt_profile=_extract_prompt_profile(all_results),
1388 )
1389 add_verification_record(
1390 model_id,
1391 arch,
1392 notes=note,
1393 sanitize_fn=_sanitize_note,
1394 prompt_profile=_extract_prompt_profile(all_results),
1395 p4_scoring_version=(P4_SCORING_VERSION if 4 in phase_scores else None),
1396 )
1397 progress.failed.append(model_id)
1399 # Post-model cleanup
1400 gc.collect()
1401 try:
1402 import torch
1404 if torch.cuda.is_available(): 1404 ↛ 1405line 1404 didn't jump to line 1405 because the condition on line 1404 was never true
1405 torch.cuda.empty_cache()
1406 torch.cuda.synchronize()
1407 if device == "mps" and hasattr(torch, "mps") and torch.backends.mps.is_available(): 1407 ↛ 1408line 1407 didn't jump to line 1408 because the condition on line 1407 was never true
1408 torch.mps.synchronize()
1409 torch.mps.empty_cache()
1411 # Log MPS memory state for debugging long runs
1412 if device == "mps" and not quiet and hasattr(torch.mps, "current_allocated_memory"): 1412 ↛ 1413line 1412 didn't jump to line 1413 because the condition on line 1412 was never true
1413 alloc_mb = torch.mps.current_allocated_memory() / (1024 * 1024)
1414 driver_mb = torch.mps.driver_allocated_memory() / (1024 * 1024)
1415 print(f" MPS memory: {alloc_mb:.0f} MB allocated, " f"{driver_mb:.0f} MB driver")
1416 except ImportError:
1417 pass
1419 # Brief pause to let the OS and MPS reclaim memory between models
1420 if device in ("mps", "cuda"): 1420 ↛ 1421line 1420 didn't jump to line 1421 because the condition on line 1420 was never true
1421 time.sleep(3)
1423 # Periodically clear the HuggingFace cache to prevent disk exhaustion
1424 if i % 50 == 0: 1424 ↛ 1425line 1424 didn't jump to line 1425 because the condition on line 1424 was never true
1425 _clear_hf_cache(quiet)
1427 _save_checkpoint(progress)
1429 # Clean up pre-loaded scoring model
1430 if _judge_model is not None:
1431 del _judge_model
1432 del _judge_tokenizer
1433 gc.collect()
1435 return progress
1438def _print_dry_run(
1439 candidates: list[ModelCandidate],
1440 dtype: str,
1441 max_memory_gb: float,
1442 phases: Optional[list[int]] = None,
1443 use_hf_reference: bool = True,
1444 device: str = "cpu",
1445) -> None:
1446 """Print what would be tested in a dry run."""
1447 print(f"\nDry run: {len(candidates)} models would be tested")
1448 print(f"Memory limit: {max_memory_gb:.1f} GB | Dtype: {dtype}")
1449 print()
1451 # Group by architecture
1452 by_arch: dict[str, list[ModelCandidate]] = {}
1453 for c in candidates:
1454 by_arch.setdefault(c.architecture_id, []).append(c)
1456 skippable = 0
1457 testable = 0
1459 for arch in sorted(by_arch.keys()):
1460 models = by_arch[arch]
1461 # Same per-architecture default as the real run, so the dry run's
1462 # memory estimates cover the phases that will actually execute.
1463 eff_phases = phases if phases is not None else _default_phases_for_architecture(arch)
1464 phases_to_run = _phases_to_run(arch, eff_phases)
1465 print(f" {arch} ({len(models)} models):")
1466 for c in models:
1467 try:
1468 n_params = estimate_model_params(c.model_id)
1469 mem = estimate_benchmark_memory_gb(
1470 n_params,
1471 dtype,
1472 phases=phases_to_run,
1473 use_hf_reference=use_hf_reference,
1474 device=device,
1475 )
1476 status = "OK" if mem <= max_memory_gb else "SKIP (too large)"
1477 if mem > max_memory_gb:
1478 skippable += 1
1479 else:
1480 testable += 1
1481 print(f" {c.model_id}: ~{n_params/1e6:.0f}M params, ~{mem:.1f} GB [{status}]")
1482 except Exception as e:
1483 skippable += 1
1484 print(f" {c.model_id}: config error ({e})")
1485 print()
1487 print(f"Summary: {testable} testable, {skippable} would be skipped")
1490def _print_summary(progress: VerificationProgress) -> None:
1491 """Print a summary of the verification run."""
1492 total = len(progress.tested)
1493 print(f"\n{'='*70}")
1494 print("Verification Summary")
1495 print(f"{'='*70}")
1496 print(f" Total tested: {total}")
1497 print(f" Verified: {len(progress.verified)}")
1498 print(f" Provisional: {len(progress.provisional)}")
1499 print(f" Skipped: {len(progress.skipped)}")
1500 print(f" Failed: {len(progress.failed)}")
1502 if progress.verified:
1503 print(f"\n Verified models:")
1504 for m in progress.verified:
1505 print(f" - {m}")
1507 if progress.provisional:
1508 print(f"\n Provisional models (structural only, no HF reference):")
1509 for m in progress.provisional:
1510 print(f" - {m}")
1512 if progress.failed:
1513 print(f"\n Failed models:")
1514 for m in progress.failed:
1515 print(f" - {m}")
1517 if progress.skipped:
1518 print(f"\n Skipped models:")
1519 for m in progress.skipped[:20]:
1520 print(f" - {m}")
1521 if len(progress.skipped) > 20:
1522 print(f" ... and {len(progress.skipped) - 20} more")
1525def main() -> None:
1526 """CLI entry point for batch model verification."""
1527 parser = argparse.ArgumentParser(
1528 description="Batch verify models in the TransformerLens registry",
1529 formatter_class=argparse.RawDescriptionHelpFormatter,
1530 epilog="""
1531Examples:
1532 %(prog)s --dry-run Show what would be tested
1533 %(prog)s --limit 3 Test 3 models total
1534 %(prog)s --architectures GPT2LMHeadModel --per-arch 5
1535 %(prog)s --device cuda --max-memory 24
1536 %(prog)s --resume Resume from checkpoint
1537 %(prog)s --reverify --architectures Olmo2ForCausalLM Re-verify already-tested models
1538 %(prog)s --model google/gemma-2b Verify a single model by ID
1539 """,
1540 )
1541 parser.add_argument(
1542 "--per-arch",
1543 type=int,
1544 default=10,
1545 help="Max models to verify per architecture (default: 10)",
1546 )
1547 parser.add_argument(
1548 "--device",
1549 type=str,
1550 default="cpu",
1551 help="Device for benchmarks (default: cpu)",
1552 )
1553 parser.add_argument(
1554 "--max-memory",
1555 type=float,
1556 default=None,
1557 help="Memory limit in GB (default: auto-detect)",
1558 )
1559 parser.add_argument(
1560 "--architectures",
1561 nargs="+",
1562 default=None,
1563 help="Filter to specific architectures",
1564 )
1565 parser.add_argument(
1566 "--limit",
1567 type=int,
1568 default=None,
1569 help="Total model cap",
1570 )
1571 parser.add_argument(
1572 "--resume",
1573 action="store_true",
1574 help="Resume from checkpoint",
1575 )
1576 parser.add_argument(
1577 "--dry-run",
1578 action="store_true",
1579 help="Show what would be tested without running benchmarks",
1580 )
1581 parser.add_argument(
1582 "--no-hf-reference",
1583 action="store_true",
1584 help=(
1585 "Skip HuggingFace reference comparison (Phase 1 is structural-only). "
1586 "A passing run is recorded as PROVISIONAL, not verified — re-run without "
1587 "this flag for a real HF-compared verification."
1588 ),
1589 )
1590 parser.add_argument(
1591 "--phases",
1592 nargs="+",
1593 type=int,
1594 default=None,
1595 help=(
1596 "Which benchmark phases to run (default: a full verification for each "
1597 "model's architecture — 1 2 3 4 for text, 1 2 3 4 7 for multimodal, "
1598 "1 8 for audio, 1 9 for vision)"
1599 ),
1600 )
1601 parser.add_argument(
1602 "--dtype",
1603 type=str,
1604 default="float32",
1605 choices=["float32", "float16", "bfloat16"],
1606 help="Dtype for memory estimation (default: float32)",
1607 )
1608 parser.add_argument(
1609 "--quiet",
1610 action="store_true",
1611 help="Suppress verbose output",
1612 )
1613 parser.add_argument(
1614 "--retry-failed",
1615 action="store_true",
1616 help="Re-run previously failed models instead of skipping them",
1617 )
1618 parser.add_argument(
1619 "--reverify",
1620 action="store_true",
1621 help="Re-run verification for already-verified/skipped/failed models. "
1622 "Ignores previous status and re-tests matching models from scratch.",
1623 )
1624 parser.add_argument(
1625 "--model",
1626 type=str,
1627 nargs="+",
1628 default=None,
1629 help="Verify one or more models by HuggingFace model ID. "
1630 "Looks up architecture from the registry automatically.",
1631 )
1633 args = parser.parse_args()
1635 # Setup logging
1636 logging.basicConfig(
1637 level=logging.WARNING if args.quiet else logging.INFO,
1638 format="%(asctime)s [%(levelname)s] %(message)s",
1639 )
1641 # Auto-detect memory
1642 max_memory_gb = args.max_memory
1643 if max_memory_gb is None:
1644 max_memory_gb = get_available_memory_gb(args.device)
1646 # Load checkpoint if resuming
1647 progress = None
1648 if args.resume:
1649 progress = _load_checkpoint()
1650 if progress:
1651 print(f"Resuming from checkpoint: {len(progress.tested)} models already tested")
1652 else:
1653 print("No checkpoint found, starting fresh")
1655 # If retrying failed, clean them from checkpoint and reset status in registry
1656 if args.retry_failed and progress and not args.dry_run:
1657 failed_set = set(progress.failed)
1658 if failed_set:
1659 # Reset status in supported_models.json
1660 registry_data = load_supported_models_raw()
1661 for entry in registry_data.get("models", []):
1662 if entry["model_id"] in failed_set and entry.get("status") == STATUS_FAILED:
1663 update_model_status(
1664 entry["model_id"],
1665 entry["architecture_id"],
1666 STATUS_UNVERIFIED,
1667 )
1668 # Clean checkpoint
1669 progress.tested = [m for m in progress.tested if m not in failed_set]
1670 progress.failed = []
1671 _save_checkpoint(progress)
1672 print(f" Cleared {len(failed_set)} failed models for retry")
1674 # Select models — either --model list or the normal batch selection
1675 if args.model:
1676 # Look up architecture for each model from the registry
1677 registry_data = load_supported_models_raw()
1678 candidates = []
1679 for model_id in args.model:
1680 arch_id = None
1681 for entry in registry_data.get("models", []):
1682 if entry["model_id"] == model_id:
1683 arch_id = entry["architecture_id"]
1684 break
1685 if arch_id is None:
1686 print(f"Model '{model_id}' not found in supported_models.json, skipping")
1687 continue
1688 candidates.append(ModelCandidate(model_id=model_id, architecture_id=arch_id))
1689 if not candidates:
1690 print("No valid models found in registry")
1691 return
1692 print(f"Model list mode: {len(candidates)} model(s)")
1693 else:
1694 candidates = select_models_for_verification(
1695 per_arch=args.per_arch,
1696 architectures=args.architectures,
1697 limit=args.limit,
1698 resume_progress=progress,
1699 retry_failed=args.retry_failed,
1700 reverify=args.reverify,
1701 )
1703 if not candidates:
1704 print("No models to verify (all matching models already tested)")
1705 return
1707 print(f"Selected {len(candidates)} models for verification")
1709 # Dry run
1710 if args.dry_run:
1711 _print_dry_run(
1712 candidates,
1713 args.dtype,
1714 max_memory_gb,
1715 phases=args.phases,
1716 use_hf_reference=not args.no_hf_reference,
1717 device=args.device,
1718 )
1719 return
1721 # Install graceful interrupt handler (Ctrl+C stops between models)
1722 signal.signal(signal.SIGINT, _handle_sigint)
1724 # Run verification
1725 start = time.time()
1726 progress = verify_models(
1727 candidates,
1728 device=args.device,
1729 max_memory_gb=max_memory_gb,
1730 dtype=args.dtype,
1731 use_hf_reference=not args.no_hf_reference,
1732 phases=args.phases,
1733 quiet=args.quiet,
1734 progress=progress,
1735 )
1736 elapsed = time.time() - start
1738 _print_summary(progress)
1739 print(f"\nTotal time: {elapsed:.1f}s")
1741 # Clean up checkpoint on successful completion
1742 if _CHECKPOINT_PATH.exists():
1743 _CHECKPOINT_PATH.unlink()
1744 print("Checkpoint cleared (run complete)")
1747if __name__ == "__main__": 1747 ↛ 1748line 1747 didn't jump to line 1748 because the condition on line 1747 was never true
1748 main()