Coverage for transformer_lens/model_bridge/sources/transformers/source.py: 90%

175 statements  

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

1"""``boot`` — load a model via HuggingFace ``transformers`` and wrap it in a TransformerBridge.""" 

2from __future__ import annotations 

3 

4import contextlib 

5import copy 

6import logging 

7import warnings 

8from typing import Any 

9 

10import torch 

11from transformers import ( 

12 AutoConfig, 

13 AutoTokenizer, 

14 PreTrainedModel, 

15 PreTrainedTokenizerBase, 

16) 

17 

18# Module import (not a name import): architecture_adapter_factory imports model_bridge, 

19# which imports this module, so its names may not be defined yet at this point. 

20from transformer_lens.factories import architecture_adapter_factory 

21from transformer_lens.model_bridge.bridge import TransformerBridge 

22from transformer_lens.model_bridge.sources._bridge_builder import ( 

23 build_bridge_config_from_hf, 

24 configure_tokenizer, 

25 skip_tokenizer_for_modality, 

26) 

27from transformer_lens.model_bridge.sources._hf_format import ( 

28 determine_architecture_from_hf_config, 

29) 

30from transformer_lens.tools.model_registry.registry_io import resolve_model_alias 

31from transformer_lens.utilities import get_device 

32from transformer_lens.utilities.attn_implementation import force_eager_attention 

33 

34from .helpers import ( 

35 _resolve_checkpoint_to_revision, 

36 get_hf_model_class_for_architecture, 

37 load_modality_processor, 

38) 

39 

40# Suppress transformers warnings that go to stderr; otherwise notebook tests fail 

41# on unexpected stderr output. 

42warnings.filterwarnings("ignore", message=".*generation flags.*not valid.*") 

43logging.getLogger("transformers").setLevel(logging.ERROR) 

44 

45 

46def boot( 

47 model_name: str, 

48 hf_config_overrides: dict | None = None, 

49 device: str | torch.device | None = None, 

50 dtype: torch.dtype = torch.float32, 

51 tokenizer: PreTrainedTokenizerBase | None = None, 

52 load_weights: bool = True, 

53 trust_remote_code: bool = False, 

54 model_class: Any | None = None, 

55 hf_model: Any | None = None, 

56 n_ctx: int | None = None, 

57 revision: str | None = None, 

58 code_revision: str | None = None, 

59 checkpoint_index: int | None = None, 

60 checkpoint_value: int | None = None, 

61 # Multi-device placement (accelerate-dispatched). Mutually exclusive with device. 

62 device_map: str | dict[str, str | int] | None = None, 

63 n_devices: int | None = None, 

64 max_memory: dict[str | int, str | int] | None = None, 

65 offload_folder: str | None = None, 

66) -> TransformerBridge: 

67 """Boot a model from HuggingFace (exposed as ``TransformerBridge.boot_transformers``). 

68 

69 Returns raw HF weights by default — logits/activations match HF, *not* 

70 legacy ``HookedTransformer`` (which folds LayerNorm + centers weights). 

71 Call ``enable_compatibility_mode()`` on the result for HookedTransformer- 

72 equivalent numerics. Generation, argmax, and CE loss are unaffected. 

73 

74 Attention implementation is forced to ``"eager"`` so hooks can capture scores 

75 and patterns. For an apples-to-apples HF comparison, load the HF model with 

76 ``attn_implementation="eager"`` too; comparing against the default ``"sdpa"`` 

77 shows ~1e-3 fp32 drift from kernel-level op reordering, not a bridge bug. 

78 

79 Args: 

80 model_name: The name of the model to load. 

81 hf_config_overrides: Optional overrides applied to the HuggingFace config before model load. 

82 device: The device to use. If None, will be determined automatically. Mutually exclusive 

83 with ``device_map``. 

84 dtype: The dtype to use for the model. 

85 tokenizer: Optional pre-initialized tokenizer to use; if not provided one will be created. 

86 load_weights: If False, build the model with ``from_config`` instead of loading the 

87 checkpoint: real parameters with the architecture's random initialisation, on the CPU, 

88 in the config's dtype and in training mode. ``device`` is recorded in ``cfg.device`` 

89 but not applied, and neither are ``dtype`` nor ``device_map``; move, cast and 

90 ``eval()`` the model before running it on another device or in another dtype. 

91 model_class: Optional HuggingFace model class to use instead of the default auto-detected 

92 class. When the class name matches a key in SUPPORTED_ARCHITECTURES, the corresponding 

93 adapter is selected automatically (e.g., BertForNextSentencePrediction). 

94 hf_model: Optional pre-loaded HuggingFace model to use instead of loading one. Useful for 

95 models loaded with custom configurations (e.g., quantization via BitsAndBytesConfig). 

96 When provided, load_weights is ignored, and without ``device=`` the bridge reads 

97 ``cfg.device`` from the model's weights. 

98 device_map: HuggingFace-style device map (``"auto"``, ``"balanced"``, dict, etc.) for 

99 dispatched inference. Explicit maps may include CPU and disk targets; meta targets 

100 are still rejected when ``load_weights=True`` (meta has no real data to offload from, 

101 unlike disk/cpu). Mixed CPU/disk + GPU maps are rejected too, not because they're 

102 known to be broken but because CPU/disk offload has only been verified on CPU-only 

103 hardware — no GPU to mix in. ``bridge.enable_compatibility_mode()`` (with weight 

104 processing, i.e. not ``no_processing=True``) is unsupported on a CPU/disk-offloaded 

105 bridge and raises immediately rather than mid-fold; the default (non-compat-mode) 

106 forward pass, ``run_with_cache``, and hooks all work normally under offload. Mutually 

107 exclusive with ``device``. 

108 n_devices: Convenience: split the model across this many CUDA devices (translated to a 

109 ``max_memory`` dict internally). Requires CUDA with at least this many visible devices. 

110 max_memory: Optional per-device memory budget for HF's dispatcher. 

111 offload_folder: Directory for disk-offloaded weight shards when ``device_map`` includes 

112 a ``"disk"`` target. Defaults to a temporary directory (HF's own default) if omitted. 

113 n_ctx: Optional context length override. The bridge normally uses the model's documented 

114 max context from the HF config. Setting this writes to whichever HF field the model 

115 uses (n_positions / max_position_embeddings / etc.), so callers don't need to know 

116 the field name. If larger than the model's default, a warning is emitted — quality 

117 may degrade past the trained length for rotary models. 

118 revision: Optional HF revision string (branch, tag, or commit). Forwarded to 

119 config, model, and tokenizer loading. 

120 Mutually exclusive with ``checkpoint_index`` and ``checkpoint_value``. 

121 code_revision: Optional HF revision string pinning the ``trust_remote_code`` 

122 modeling file separately from the weights (HF's own ``code_revision``). 

123 Forwarded alongside ``revision`` to config and model loading and to the 

124 adapters' remote-code patching; weights and tokenizer keep ``revision``. 

125 checkpoint_index: Index into the available training checkpoints for the model family. 

126 Convenience over ``revision`` for checkpointed models like EleutherAI/pythia* and 

127 stanford-crfm/*. Resolved to a revision string via the known per-family naming 

128 conventions (``step{value}`` for Pythia, ``checkpoint-{value}`` for stanford-crfm). 

129 checkpoint_value: Training step or token count of the desired checkpoint. Alternative to 

130 ``checkpoint_index``; must be one of the labels returned by ``get_checkpoint_labels``. 

131 

132 Returns: 

133 The bridge to the loaded model. 

134 """ 

135 official_name = resolve_model_alias(model_name) 

136 if official_name is not None: 

137 logging.warning( 

138 f"DEPRECATED: You are using a deprecated, model_name alias '{model_name}'. TransformerLens will now load the official transformers model name, '{official_name}' instead.\n Please update your code to use the official name by changing model_name from '{model_name}' to '{official_name}'.\nSince TransformerLens v3, all model names should be the official transformers model names.\nThe aliases may be removed in a future version of TransformerLens, so please do the update now." 

139 ) 

140 model_name = official_name 

141 if checkpoint_index is not None or checkpoint_value is not None: 

142 if revision is not None: 

143 raise ValueError( 

144 "Specify either revision= or checkpoint_index/checkpoint_value, not both." 

145 ) 

146 revision = _resolve_checkpoint_to_revision(model_name, checkpoint_index, checkpoint_value) 

147 # Pass HF token for gated model access (e.g. meta-llama/*) 

148 from transformer_lens.utilities.hf_utils import ( 

149 autoconfig_with_remote_post_init_compat, 

150 autotokenizer_with_special_token_compat, 

151 get_hf_token, 

152 ) 

153 

154 _hf_token = get_hf_token() 

155 if hf_model is not None: 

156 # Reuse the pre-loaded model's config to avoid a Hub call when model_name 

157 # is a Hub repo ID but the model is already loaded locally. 

158 hf_config = copy.deepcopy(hf_model.config) 

159 else: 

160 # Compat wrapper: 4.x-era remote-code configs (OpenELM) define an 

161 # argless __post_init__ that 5.x's dataclass machinery calls with the 

162 # class's own fields as kwargs — unloadable without the shim. 

163 hf_config = autoconfig_with_remote_post_init_compat( 

164 model_name, 

165 auto_config=AutoConfig, 

166 output_attentions=True, 

167 trust_remote_code=trust_remote_code, 

168 token=_hf_token, 

169 revision=revision, 

170 code_revision=code_revision, 

171 ) 

172 _n_ctx_field: str | None = None 

173 if n_ctx is not None: 

174 if n_ctx <= 0: 

175 raise ValueError(f"n_ctx must be a positive integer, got n_ctx={n_ctx}.") 

176 # Resolve n_ctx to whichever HF config field this model uses. Mirrors the order in 

177 # map_default_transformer_lens_config so the TL config derivation picks up the override. 

178 for _field in ( 178 ↛ 189line 178 didn't jump to line 189 because the loop on line 178 didn't complete

179 "n_positions", 

180 "max_position_embeddings", 

181 "max_context_length", 

182 "max_length", 

183 "seq_length", 

184 "max_sequence_length", 

185 ): 

186 if hasattr(hf_config, _field): 

187 _n_ctx_field = _field 

188 break 

189 if _n_ctx_field is None: 189 ↛ 190line 189 didn't jump to line 190 because the condition on line 189 was never true

190 raise ValueError( 

191 f"Cannot apply n_ctx={n_ctx}: no recognized context-length field on " 

192 f"HF config for {model_name}. Use hf_config_overrides instead." 

193 ) 

194 _default_n_ctx = getattr(hf_config, _n_ctx_field) 

195 if _default_n_ctx is not None and n_ctx > _default_n_ctx: 

196 logging.warning( 

197 "Setting n_ctx=%d which is larger than the model's default " 

198 "context length of %d. The model was not trained on sequences " 

199 "this long and may produce unreliable results (especially for " 

200 "rotary models without RoPE scaling).", 

201 n_ctx, 

202 _default_n_ctx, 

203 ) 

204 # Warn if the caller also set the same field via hf_config_overrides — explicit n_ctx wins. 

205 if hf_config_overrides and _n_ctx_field in hf_config_overrides: 

206 _conflicting_value = hf_config_overrides[_n_ctx_field] 

207 if _conflicting_value != n_ctx: 

208 logging.warning( 

209 "Both n_ctx=%d and hf_config_overrides['%s']=%s were provided. " 

210 "The explicit n_ctx takes precedence.", 

211 n_ctx, 

212 _n_ctx_field, 

213 _conflicting_value, 

214 ) 

215 hf_config_overrides = dict(hf_config_overrides or {}) 

216 hf_config_overrides[_n_ctx_field] = n_ctx 

217 if hf_config_overrides: 

218 hf_config.__dict__.update(hf_config_overrides) 

219 architecture = determine_architecture_from_hf_config(hf_config) 

220 bridge_config = build_bridge_config_from_hf(hf_config, architecture, model_name, dtype) 

221 bridge_config.trust_remote_code = trust_remote_code 

222 adapter = architecture_adapter_factory.ArchitectureAdapterFactory.select_architecture_adapter( 

223 bridge_config 

224 ) 

225 # Pre-loaded models carry their own weight placement (possibly set by the caller via 

226 # device_map). Passing device_map / n_devices / max_memory alongside hf_model= is ambiguous 

227 # and would silently be ignored, so fail loudly. 

228 if hf_model is not None and ( 

229 device_map is not None or n_devices is not None or max_memory is not None 

230 ): 

231 raise ValueError( 

232 "device_map / n_devices / max_memory are only supported when the bridge loads " 

233 "the HF model itself. When passing hf_model=..., apply device_map via " 

234 "AutoModel.from_pretrained before handing the model to the bridge." 

235 ) 

236 # Stateful/SSM (Mamba) models keep a per-layer recurrent cache that must live on that 

237 # layer's device. The bridge allocates the stateful cache on a single cfg.device, so 

238 # cross-device splits would silently misplace the cache. Blocked until v2. 

239 if (n_devices is not None and n_devices > 1) or device_map is not None: 

240 if getattr(bridge_config, "is_stateful", False): 240 ↛ 241line 240 didn't jump to line 241 because the condition on line 240 was never true

241 raise ValueError( 

242 "Multi-device splits are not yet supported for stateful (SSM / Mamba) " 

243 "architectures: the stateful cache allocation is single-device. " 

244 "Load on one device, or wait for v2 support." 

245 ) 

246 # Resolve device_map before defaulting `device` — the two are mutually exclusive and the 

247 # resolver raises on conflict. If n_devices>1 is passed it's translated into a device_map + 

248 # max_memory pair here so downstream code only needs to check the resolved values. 

249 from transformer_lens.utilities.multi_gpu import ( 

250 MIXED_OFFLOAD_GPU_ERROR, 

251 count_unique_devices, 

252 find_embedding_device, 

253 find_misplaced_modules, 

254 is_mixed_offload_gpu, 

255 maybe_cast_floating_params, 

256 resolve_device_map, 

257 ) 

258 

259 resolved_device_map, resolved_max_memory = resolve_device_map( 

260 n_devices, device_map, device, max_memory 

261 ) 

262 if resolved_device_map is None: 

263 # hf_model is never moved; without device= cfg.device is read from it below. 

264 if device is None and hf_model is None: 

265 device = get_device() 

266 adapter.cfg.device = None if device is None else str(device) 

267 else: 

268 # cfg.device set from hf_device_map after the model is loaded; provisionally None. 

269 adapter.cfg.device = None 

270 if model_class is None: 

271 model_class = get_hf_model_class_for_architecture(architecture) 

272 # Ensure pad_token_id exists (v5 raises AttributeError if missing). 

273 if not hasattr(hf_config, "pad_token_id") or "pad_token_id" not in hf_config.__dict__: 

274 fallback_pad = getattr(hf_config, "eos_token_id", None) 

275 # eos_token_id can be a list (Gemma3 uses [1, 106]); take the first. 

276 if isinstance(fallback_pad, list): 

277 fallback_pad = fallback_pad[0] if fallback_pad else None 

278 hf_config.pad_token_id = fallback_pad 

279 model_kwargs = {"config": hf_config, "torch_dtype": dtype} 

280 if _hf_token: 280 ↛ 282line 280 didn't jump to line 282 because the condition on line 280 was always true

281 model_kwargs["token"] = _hf_token 

282 if trust_remote_code: 

283 model_kwargs["trust_remote_code"] = True 

284 if revision is not None: 

285 model_kwargs["revision"] = revision 

286 if code_revision is not None: 

287 model_kwargs["code_revision"] = code_revision 

288 if resolved_device_map is not None: 

289 model_kwargs["device_map"] = resolved_device_map 

290 if resolved_max_memory is not None: 290 ↛ 291line 290 didn't jump to line 291 because the condition on line 290 was never true

291 model_kwargs["max_memory"] = resolved_max_memory 

292 if offload_folder is not None: 

293 model_kwargs["offload_folder"] = offload_folder 

294 if hasattr(adapter.cfg, "attn_implementation") and adapter.cfg.attn_implementation is not None: 

295 model_kwargs["attn_implementation"] = adapter.cfg.attn_implementation 

296 else: 

297 # Eager is required for output_attentions hooks. 

298 model_kwargs["attn_implementation"] = "eager" 

299 adapter.prepare_loading(model_name, model_kwargs) 

300 # Meta device_map targets crash at boot when loading weights 

301 # (NotImplementedError in HF tie_weights, KeyError in Accelerate offload hooks). 

302 # Only accepted with load_weights=False (config inspection; map not applied). 

303 if load_weights and isinstance(resolved_device_map, dict): 

304 _meta_targets = [ 

305 k 

306 for k, v in resolved_device_map.items() 

307 if isinstance(v, str) and v.strip().lower() == "meta" 

308 ] 

309 if _meta_targets: 

310 raise ValueError( 

311 f"device_map contains meta target(s): {_meta_targets}. " 

312 "Meta device_map values crash at boot when loading weights. " 

313 "Set load_weights=False for config inspection only " 

314 "(the map is not applied; parameters load on CPU via from_config)." 

315 ) 

316 if hf_model is not None: 

317 # Pre-loaded weights stay untouched (quantized models with custom device_map are 

318 # why this branch takes the model as-is), but attn-impl selection is runtime 

319 # dispatch — safe to switch in place. Without it, transformers' default sdpa 

320 # returns attn_weights=None and hook_pattern / hook_attn_scores silently never 

321 # fire. An explicit adapter/user choice wins, matching the load path above. 

322 if getattr(adapter.cfg, "attn_implementation", None) is None: 322 ↛ 374line 322 didn't jump to line 374 because the condition on line 322 was always true

323 force_eager_attention(hf_model) 

324 elif not load_weights: 

325 from_config_kwargs = {} 

326 if trust_remote_code: 326 ↛ 327line 326 didn't jump to line 327 because the condition on line 326 was never true

327 from_config_kwargs["trust_remote_code"] = True 

328 # adapter.prepare_loading may have replaced model_kwargs["config"] (e.g. Qwen3.5 

329 # text-only extraction); honor that here so the no-weights path uses the 

330 # same config the load-weights path would. 

331 prepared_config = model_kwargs.get("config", hf_config) 

332 with contextlib.redirect_stdout(None): 

333 hf_model = model_class.from_config(prepared_config, **from_config_kwargs) 

334 else: 

335 # Only Auto classes resolve remote code, so only they accept code_revision; 

336 # a concrete PreTrainedModel subclass rejects it with a TypeError. The pin 

337 # already did its work in AutoConfig and prepare_loading above. 

338 if isinstance(model_class, type) and issubclass(model_class, PreTrainedModel): 

339 model_kwargs.pop("code_revision", None) 

340 try: 

341 hf_model = model_class.from_pretrained(model_name, **model_kwargs) 

342 except RuntimeError as e: 

343 # HF refuses to load when positional-weight shapes don't match. If the user 

344 # requested an n_ctx that conflicts with the saved weights (common for 

345 # learned-pos-embed models like GPT-2), re-raise with a clearer message. 

346 if n_ctx is not None and "ignore_mismatched_sizes" in str(e): 346 ↛ 357line 346 didn't jump to line 357 because the condition on line 346 was always true

347 raise RuntimeError( 

348 f"Failed to load {model_name} with n_ctx={n_ctx}: the pretrained " 

349 f"weights' positional-embedding shape does not match the requested " 

350 f"context length. This affects models with learned positional " 

351 f"embeddings (e.g. GPT-2, OPT). Options: (1) use the model's " 

352 f"default n_ctx, (2) pass load_weights=False if you only need " 

353 f"config inspection, or (3) choose a rotary-embedding model " 

354 f"(e.g. Llama, Mistral) which supports n_ctx changes without " 

355 f"weight mismatch." 

356 ) from e 

357 raise 

358 # Skip explicit .to(device) when accelerate has placed weights via device_map. 

359 if resolved_device_map is None and device is not None: 

360 hf_model = hf_model.to(device) 

361 # Cast params to dtype; preserve float32 buffers (e.g. RotaryEmbedding.inv_freq). 

362 # Use module-level alignment so Accelerate can temporarily materialize offloaded 

363 # parameters before we touch them. 

364 # Skip dtype normalization entirely when the model has an active quantizer. 

365 # from_pretrained settled the load dtype above, and on a quantized checkpoint 

366 # that is the quantizer's effective dtype rather than necessarily the requested 

367 # one (HfQuantizer.update_dtype lets AWQ, fbgemm-FP8 and FP-Quant override it; 

368 # AWQ keys off CUDA/XPU being available at all, not off placement). 

369 # Re-casting would overwrite those choices along with quantizer-owned storage, 

370 # whose width is the quantizer's to choose (FP8 *or* float32 scales). 

371 maybe_cast_floating_params(hf_model, dtype) 

372 # Derive cfg.device / cfg.n_devices from hf_device_map when present. Covers fresh loads 

373 # with a resolved device_map AND pre-loaded models with caller-dispatched device_map="auto". 

374 hf_device_map_post = getattr(hf_model, "hf_device_map", None) 

375 if hf_device_map_post: 

376 # All-CPU placement, and disk offload, are supported (GeneralizedComponent.__call__ 

377 # wraps forward in Accelerate's align_module_device, so wrapped components reading 

378 # raw params directly still see materialized data). meta remains rejected here: it 

379 # has no real data to materialize even under offload/dispatch, unlike disk/cpu. 

380 offload_values = {str(v).lower() for v in hf_device_map_post.values() if isinstance(v, str)} 

381 unsupported = offload_values & {"meta"} 

382 if unsupported: 382 ↛ 383line 382 didn't jump to line 383 because the condition on line 382 was never true

383 raise ValueError( 

384 f"hf_device_map contains unsupported offload targets: {sorted(unsupported)}. " 

385 "TransformerBridge currently supports CPU and disk device_map targets." 

386 ) 

387 if is_mixed_offload_gpu(hf_device_map_post.values()): 387 ↛ 388line 387 didn't jump to line 388 because the condition on line 387 was never true

388 raise ValueError(f"Realized hf_device_map is unsupported: {MIXED_OFFLOAD_GPU_ERROR}") 

389 if ( 389 ↛ 395line 389 didn't jump to line 395 because the condition on line 389 was never true

390 "cpu" in offload_values 

391 and device_map is None 

392 and n_devices is not None 

393 and n_devices > 1 

394 ): 

395 raise ValueError( 

396 "hf_device_map contains CPU targets. n_devices is GPU-only; pass device_map " 

397 "explicitly for CPU placement." 

398 ) 

399 misplaced = find_misplaced_modules(hf_model) 

400 if misplaced: 400 ↛ 401line 400 didn't jump to line 401 because the condition on line 400 was never true

401 details = "; ".join( 

402 f"{name!r} mapped to {mapped} but loaded on {actual}" 

403 for name, mapped, actual in misplaced 

404 ) 

405 raise ValueError( 

406 f"device_map entries were not honored: {details}. This usually means the " 

407 "map splits tied parameters (e.g. GPT-2's wte/lm_head share one tensor) " 

408 "across devices — accelerate places a tied parameter once, leaving a module " 

409 "executing on a device its weights aren't on, which crashes mid-forward. " 

410 "Map tied modules to the same device." 

411 ) 

412 embedding_device = find_embedding_device(hf_model) 

413 if embedding_device is not None: 

414 adapter.cfg.device = str(embedding_device) 

415 adapter.cfg.n_devices = count_unique_devices(hf_model) 

416 elif adapter.cfg.device is None: 

417 # Pre-loaded single-device model with no hf_device_map — fall back to first param. 

418 try: 

419 adapter.cfg.device = str(next(hf_model.parameters()).device) 

420 except StopIteration: 

421 adapter.cfg.device = "cpu" 

422 # Verify the n_ctx override actually took effect on the loaded model. If HF's config class 

423 # silently dropped or normalized the value, warn so the user isn't misled. 

424 if n_ctx is not None and _n_ctx_field is not None and hf_model is not None: 

425 _actual = getattr(hf_model.config, _n_ctx_field, None) 

426 if _actual != n_ctx: 

427 logging.warning( 

428 "n_ctx=%d was requested but hf_model.config.%s=%s after load. " 

429 "The override may not have taken effect; the model may not " 

430 "accept sequences longer than %s.", 

431 n_ctx, 

432 _n_ctx_field, 

433 _actual, 

434 _actual, 

435 ) 

436 adapter.prepare_model(hf_model) 

437 if tokenizer is not None: 

438 tokenizer = configure_tokenizer(tokenizer, adapter.cfg) 

439 elif not skip_tokenizer_for_modality(adapter.cfg): 

440 token_arg = get_hf_token() 

441 use_fast = getattr(adapter.cfg, "use_fast", True) 

442 # Some adapters override tokenizer source (e.g. OpenELM has no tokenizer of its own). 

443 tokenizer_source = model_name 

444 if hasattr(adapter.cfg, "tokenizer_name") and adapter.cfg.tokenizer_name is not None: 444 ↛ 445line 444 didn't jump to line 445 because the condition on line 444 was never true

445 tokenizer_source = adapter.cfg.tokenizer_name 

446 # Encoder-decoder models like T5 don't have a BOS token and raise on add_bos_token=True. 

447 try: 

448 base_tokenizer = autotokenizer_with_special_token_compat( 

449 tokenizer_source, 

450 auto_tokenizer=AutoTokenizer, 

451 add_bos_token=True, 

452 use_fast=use_fast, 

453 token=token_arg, 

454 trust_remote_code=trust_remote_code, 

455 revision=revision, 

456 ) 

457 except ValueError: 

458 base_tokenizer = AutoTokenizer.from_pretrained( 

459 tokenizer_source, 

460 use_fast=use_fast, 

461 token=token_arg, 

462 trust_remote_code=trust_remote_code, 

463 revision=revision, 

464 ) 

465 tokenizer = configure_tokenizer(base_tokenizer, adapter.cfg) 

466 from transformer_lens.model_bridge.sources.transformers_driver import ( 

467 TransformersDriver, 

468 ) 

469 

470 driver = TransformersDriver(hf_model, adapter, tokenizer) 

471 bridge = TransformerBridge(hf_model, adapter, tokenizer, driver=driver) 

472 load_modality_processor(bridge, adapter.cfg, model_name, trust_remote_code, _hf_token) 

473 # Mirror the legacy loader: record which training checkpoint this is, so 

474 # checkpoint sweeps (e.g. induction-head formation) can read it back. 

475 if checkpoint_index is not None or checkpoint_value is not None: 

476 from transformer_lens.tools.model_registry.checkpoints import ( 

477 get_checkpoint_labels, 

478 ) 

479 

480 labels, _label_kind = get_checkpoint_labels(model_name) 

481 if checkpoint_value is not None: 481 ↛ 482line 481 didn't jump to line 482 because the condition on line 481 was never true

482 resolved_value = checkpoint_value 

483 else: 

484 assert checkpoint_index is not None # narrowed by the enclosing if 

485 resolved_value = labels[checkpoint_index] 

486 bridge.cfg.checkpoint_value = resolved_value # type: ignore[attr-defined] 

487 bridge.cfg.checkpoint_index = labels.index(resolved_value) # type: ignore[attr-defined] 

488 return bridge