Coverage for transformer_lens/model_bridge/sources/transformers/helpers.py: 68%

111 statements  

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

1"""HF-loader-specific helpers: model-class selection, modality processor loading, checkpoint revision resolution, registry discovery.""" 

2from __future__ import annotations 

3 

4from typing import Any 

5 

6import transformers 

7from transformers import ( 

8 AutoModelForCausalLM, 

9 AutoModelForMaskedLM, 

10 AutoModelForSeq2SeqLM, 

11) 

12 

13from transformer_lens.tools.model_registry.checkpoints import get_checkpoint_labels 

14 

15 

16def get_hf_model_class_for_architecture(architecture: str): 

17 """Pick the correct HuggingFace ``AutoModel*`` class for the architecture.""" 

18 from transformer_lens.utilities.architectures import ( 

19 AUDIO_ARCHITECTURES, 

20 AUDIO_CLASSIFICATION_ARCHITECTURES, 

21 AUDIO_SEQ2SEQ_ARCHITECTURES, 

22 AUDIO_TEXT_ARCHITECTURES, 

23 BASE_AUTOMODEL_ARCHITECTURES, 

24 MASKED_LM_ARCHITECTURES, 

25 MULTIMODAL_ARCHITECTURES, 

26 SEQ2SEQ_ARCHITECTURES, 

27 VISION_ARCHITECTURES, 

28 VISION_CLASSIFICATION_ARCHITECTURES, 

29 ) 

30 

31 if architecture in AUDIO_SEQ2SEQ_ARCHITECTURES: 

32 from transformers import AutoModelForSpeechSeq2Seq 

33 

34 return AutoModelForSpeechSeq2Seq 

35 elif architecture in SEQ2SEQ_ARCHITECTURES or architecture in AUDIO_TEXT_ARCHITECTURES: 

36 return AutoModelForSeq2SeqLM 

37 elif architecture in MASKED_LM_ARCHITECTURES: 

38 return AutoModelForMaskedLM 

39 elif architecture in MULTIMODAL_ARCHITECTURES: 

40 from transformers import AutoModelForImageTextToText 

41 

42 return AutoModelForImageTextToText 

43 elif architecture in BASE_AUTOMODEL_ARCHITECTURES: 43 ↛ 44line 43 didn't jump to line 44 because the condition on line 43 was never true

44 from transformers import AutoModel 

45 

46 return AutoModel 

47 elif architecture in AUDIO_CLASSIFICATION_ARCHITECTURES: 

48 from transformers import AutoModelForAudioClassification 

49 

50 return AutoModelForAudioClassification 

51 elif architecture in AUDIO_ARCHITECTURES: 

52 if "ForCTC" in architecture: 52 ↛ 53line 52 didn't jump to line 53 because the condition on line 52 was never true

53 from transformers import AutoModelForCTC 

54 

55 return AutoModelForCTC 

56 from transformers import AutoModel 

57 

58 return AutoModel 

59 elif architecture in VISION_ARCHITECTURES: 

60 if architecture in VISION_CLASSIFICATION_ARCHITECTURES: 

61 from transformers import AutoModelForImageClassification 

62 

63 return AutoModelForImageClassification 

64 from transformers import AutoModel 

65 

66 return AutoModel 

67 else: 

68 return AutoModelForCausalLM 

69 

70 

71# Modality flag → HF auto-loader class, applied in order. Last write wins on 

72# bridge.processor: multimodal → audio → audio seq2seq → vision. Audio seq2seq 

73# (Whisper) sets is_audio_model too and must follow it, so the full processor 

74# (feature extractor + tokenizer) replaces the bare feature extractor. 

75_MODALITY_PROCESSOR_LOADERS: list[tuple[str, str]] = [ 

76 ("is_multimodal", "AutoProcessor"), 

77 ("is_audio_model", "AutoFeatureExtractor"), 

78 ("is_audio_seq2seq", "AutoProcessor"), 

79 ("is_visual_model", "AutoImageProcessor"), 

80] 

81 

82 

83def _ensure_torchvision() -> bool: 

84 """Import torchvision, installing it on the fly if missing; True when importable.""" 

85 try: 

86 import torchvision # noqa: F401 

87 

88 return True 

89 except Exception: 

90 pass 

91 import importlib 

92 import shutil 

93 import subprocess 

94 import sys 

95 

96 try: 

97 if shutil.which("uv"): 

98 subprocess.check_call(["uv", "pip", "install", "torchvision", "-q"]) 

99 else: 

100 subprocess.check_call([sys.executable, "-m", "pip", "install", "torchvision", "-q"]) 

101 importlib.invalidate_caches() 

102 return True 

103 except Exception: 

104 return False 

105 

106 

107def load_modality_processor( 

108 bridge: Any, 

109 cfg: Any, 

110 model_name: str, 

111 trust_remote_code: bool, 

112 token: str | None, 

113) -> None: 

114 """Attach the modality preprocessor to ``bridge.processor`` per the cfg's modality flags. 

115 

116 Best-effort: each loader failure is swallowed so a missing/broken processor 

117 never blocks the boot itself. 

118 """ 

119 for cfg_flag, loader_name in _MODALITY_PROCESSOR_LOADERS: 

120 if not getattr(cfg, cfg_flag, False): 

121 continue 

122 try: 

123 loader = getattr(transformers, loader_name) 

124 bridge.processor = loader.from_pretrained( 

125 model_name, 

126 token=token, 

127 trust_remote_code=trust_remote_code, 

128 ) 

129 except Exception: 

130 # Some AutoProcessors need torchvision (e.g. LlavaOnevision); install and retry. 

131 if loader_name != "AutoProcessor" or not _ensure_torchvision(): 

132 continue 

133 try: 

134 bridge.processor = transformers.AutoProcessor.from_pretrained( 

135 model_name, 

136 token=token, 

137 trust_remote_code=trust_remote_code, 

138 ) 

139 except Exception: 

140 pass 

141 

142 

143# Known training-checkpoint revision conventions on HF Hub. 

144_CHECKPOINT_REVISION_FORMATS: dict[str, str] = { 

145 "EleutherAI/pythia": "step{value}", 

146 "stanford-crfm": "checkpoint-{value}", 

147} 

148 

149 

150def _resolve_checkpoint_to_revision( 

151 model_name: str, 

152 checkpoint_index: int | None, 

153 checkpoint_value: int | None, 

154) -> str: 

155 """Convert a checkpoint index/value into an HF revision string, validated against ``get_checkpoint_labels``.""" 

156 if checkpoint_index is None and checkpoint_value is None: 

157 raise ValueError("Must specify either checkpoint_index or checkpoint_value.") 

158 

159 format_str: str | None = None 

160 for prefix, fmt in _CHECKPOINT_REVISION_FORMATS.items(): 

161 if model_name.startswith(prefix): 

162 format_str = fmt 

163 break 

164 if format_str is None: 

165 raise ValueError( 

166 f"Model {model_name!r} does not have a known checkpoint revision convention. " 

167 f"Pass revision= directly if your model uses HF revisions. Known checkpoint " 

168 f"families: {list(_CHECKPOINT_REVISION_FORMATS.keys())}." 

169 ) 

170 

171 labels, _ = get_checkpoint_labels(model_name) 

172 if checkpoint_value is not None: 

173 if checkpoint_value not in labels: 

174 raise ValueError( 

175 f"checkpoint_value={checkpoint_value} not in available checkpoints for " 

176 f"{model_name!r}. {len(labels)} labels available, " 

177 f"first/last: {labels[0]}..{labels[-1]}." 

178 ) 

179 else: 

180 assert checkpoint_index is not None # narrowed by initial guard 

181 # Negative indices count from the end, matching the legacy loader. 

182 if not -len(labels) <= checkpoint_index < len(labels): 

183 raise ValueError( 

184 f"checkpoint_index={checkpoint_index} out of range " 

185 f"[-{len(labels)}, {len(labels)}) for {model_name!r}." 

186 ) 

187 checkpoint_value = labels[checkpoint_index] 

188 return format_str.format(value=checkpoint_value) 

189 

190 

191def list_supported_models( 

192 architecture: str | None = None, 

193 verified_only: bool = False, 

194) -> list[str]: 

195 """List all models supported by TransformerLens. 

196 

197 Args: 

198 architecture: Filter by architecture ID (e.g., "GPT2LMHeadModel"). 

199 verified_only: If True, only return verified-to-work models. 

200 

201 Returns: 

202 List of model IDs. 

203 """ 

204 try: 

205 from transformer_lens.tools.model_registry import api 

206 

207 models = api.get_supported_models(architecture=architecture, verified_only=verified_only) 

208 return [m.model_id for m in models] 

209 except ImportError: 

210 return [] 

211 except Exception: 

212 return [] 

213 

214 

215def check_model_support(model_id: str) -> dict: 

216 """Detailed support info for a model: ``is_supported``, ``architecture_id``, ``verified``, ``suggestion``.""" 

217 try: 

218 from transformer_lens.tools.model_registry import api 

219 

220 is_supported = api.is_model_supported(model_id) 

221 

222 if is_supported: 

223 model_info = api.get_model_info(model_id) 

224 return { 

225 "is_supported": True, 

226 "architecture_id": model_info.architecture_id, 

227 "status": model_info.status, 

228 "verified_date": ( 

229 model_info.verified_date.isoformat() if model_info.verified_date else None 

230 ), 

231 "suggestion": None, 

232 } 

233 else: 

234 suggestion = api.suggest_similar_model(model_id) 

235 return { 

236 "is_supported": False, 

237 "architecture_id": None, 

238 "verified": False, 

239 "verified_date": None, 

240 "suggestion": suggestion, 

241 } 

242 except ImportError: 

243 return { 

244 "is_supported": None, 

245 "architecture_id": None, 

246 "verified": False, 

247 "verified_date": None, 

248 "suggestion": None, 

249 "error": "Model registry not available", 

250 } 

251 except Exception as e: 

252 return { 

253 "is_supported": None, 

254 "architecture_id": None, 

255 "verified": False, 

256 "verified_date": None, 

257 "suggestion": None, 

258 "error": str(e), 

259 }