Coverage for transformer_lens/model_bridge/transformer_bridge.py: 89%

2010 statements  

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

1"""Bridge module for connecting different model architectures. 

2 

3This module provides the bridge components that wrap remote model components and provide 

4a consistent interface for accessing their weights and performing operations. 

5""" 

6 

7import inspect 

8import logging 

9import re 

10import warnings 

11from collections.abc import Generator 

12from typing import ( 

13 TYPE_CHECKING, 

14 Any, 

15 Callable, 

16 ClassVar, 

17 Dict, 

18 Iterator, 

19 List, 

20 Literal, 

21 Optional, 

22 Sequence, 

23 Tuple, 

24 Union, 

25 cast, 

26) 

27 

28import einops 

29import numpy as np 

30import torch 

31import tqdm 

32from torch import nn 

33from torch.nn import functional as F 

34from torch.utils.hooks import RemovableHandle 

35from transformers.tokenization_utils_base import PreTrainedTokenizerBase 

36 

37from transformer_lens import utilities as utils 

38from transformer_lens.ActivationCache import ActivationCache 

39from transformer_lens.config import TransformerBridgeConfig 

40from transformer_lens.FactoredMatrix import FactoredMatrix 

41from transformer_lens.hook_points import HookIntrospectionMixin, HookPoint 

42from transformer_lens.model_bridge.architecture_adapter import ArchitectureAdapter 

43from transformer_lens.model_bridge.bridge_core import ( 

44 _BLOCK_LIST_ATTRS, 

45 _SELF_ATTENTION_NAMES, 

46 BridgeCore, 

47 _validate_execution_kwargs, 

48) 

49from transformer_lens.model_bridge.component_setup import ( 

50 refresh_container_state_owners, 

51 set_original_components, 

52) 

53from transformer_lens.model_bridge.composition_scores import CompositionScores 

54from transformer_lens.model_bridge.driver_protocol import ( 

55 TensorLike, 

56 to_torch, 

57 validate_driver, 

58) 

59from transformer_lens.model_bridge.exceptions import StopAtLayerException 

60from transformer_lens.model_bridge.generalized_components.base import ( 

61 GeneralizedComponent, 

62) 

63from transformer_lens.model_bridge.generalized_components.block import ( 

64 _BLOCK_INTERNAL_MODULES, 

65 _NORM_PREFIXES, 

66 _VARIANT_SUBMODULE_SET, 

67 VARIANT_SUBMODULE_NAMES, 

68) 

69from transformer_lens.model_bridge.generalized_components.mlp import ( 

70 weight_layout_in_out, 

71) 

72from transformer_lens.model_bridge.generalized_components.moe import ( 

73 fold_scale_into_moe_block, 

74 has_batched_experts, 

75) 

76from transformer_lens.model_bridge.get_params_util import get_bridge_params 

77from transformer_lens.utilities.activation_functions import softcap_enabled 

78from transformer_lens.utilities.devices import move_to_and_update_config 

79from transformer_lens.utilities.position_ids import accepts_mask_derived_position_ids 

80from transformer_lens.utilities.quantization import require_readable_weight 

81 

82if TYPE_CHECKING: 

83 pass 

84 

85_BLOCK_PATTERN = re.compile("blocks\\.(\\d+)") 

86 

87 

88def _resolve_attr_path(obj: nn.Module, attr_path: str) -> Optional[torch.Tensor]: 

89 """Walk a dot-separated attribute path and return the final tensor (None if bias-free).""" 

90 result = obj 

91 for attr in attr_path.split("."): 

92 result = getattr(result, attr) 

93 return cast(torch.Tensor, result) 

94 

95 

96def _storage_group_keys(state_dict: dict[str, torch.Tensor]) -> set[str]: 

97 """Keys whose current tensor shares underlying storage with another key's. 

98 

99 Covers every direction of the desync #1637 reported: a partial view onto 

100 a combined weight (e.g. a split QKV/gate-up component's ``torch.tensor_split`` 

101 view into ``c_attn``/``gate_up_proj``), the combined weight itself (writing 

102 it directly would silently orphan the views that share its storage), and a 

103 same-size tied pair (e.g. tied embed/unembed weights, #1725) -- none of 

104 which reliably show up via ``Tensor._base``, since wrapping in 

105 ``nn.Parameter`` doesn't preserve that tracking here. 

106 

107 Meta tensors are excluded from the comparison: every meta tensor reports 

108 ``untyped_storage().data_ptr() == 0`` (it has no real backing memory), so 

109 comparing meta tensors by data pointer would spuriously group every 

110 unrelated offloaded parameter in the model together. A key whose current 

111 target is meta falls through to ordinary ``assign=True`` handling instead 

112 (the standard way to materialize a meta tensor from a real one). 

113 """ 

114 by_storage: dict[int, list[str]] = {} 

115 for key, tensor in state_dict.items(): 

116 if tensor.is_meta: 

117 continue 

118 by_storage.setdefault(tensor.untyped_storage().data_ptr(), []).append(key) 

119 return {key for keys in by_storage.values() if len(keys) > 1 for key in keys} 

120 

121 

122def _stop_on_block_exit(module: nn.Module, args: Any, output: Any) -> None: 

123 """Module forward hook ending the run with the residual a block just returned.""" 

124 raise StopAtLayerException(output[0] if isinstance(output, (tuple, list)) else output) 

125 

126 

127def _extend_prompt_attention_mask(prompt_mask: torch.Tensor, tokens: torch.Tensor) -> torch.Tensor: 

128 """Extend a prompt mask over ``tokens``' generated tail; shared by the loop and cache replay.""" 

129 n_generated = tokens.shape[1] - prompt_mask.shape[1] 

130 return torch.cat( 

131 [ 

132 prompt_mask.to(tokens.device), 

133 torch.ones( 

134 (tokens.shape[0], n_generated), dtype=prompt_mask.dtype, device=tokens.device 

135 ), 

136 ], 

137 dim=1, 

138 ) 

139 

140 

141class TransformerBridge(BridgeCore, HookIntrospectionMixin, nn.Module): 

142 """Torch-backed bridge: HF, vLLM-via-torch, anything that wraps an ``nn.Module``. 

143 

144 Provides a standardized interface to access components of a transformer 

145 model, regardless of the underlying architecture. It uses an architecture adapter 

146 to map between the TransformerLens and HuggingFace model structures. 

147 

148 Stateless reparametrization is unsupported 

149 ------------------------------------------ 

150 

151 ``torch.func.functional_call`` (and ``torch.nn.utils.stateless``) fails to 

152 restore parameters through this tree: each replaced component is registered 

153 both inside the wrapped HF model and as a bridge submodule, and torch's 

154 tied-weight handling double-swaps the shared slot, leaving the override 

155 installed. For temporary weight edits use 

156 :func:`transformer_lens.utilities.temporarily_swap_parameter`. 

157 

158 Tokenization notes 

159 ------------------ 

160 

161 :meth:`to_tokens`, :meth:`to_str_tokens`, :meth:`get_token_position`, 

162 :meth:`forward` (string input), and :meth:`generate` accept ``prepend_bos`` 

163 to control BOS prepending. Resolution: explicit arg → 

164 ``cfg.default_prepend_bos`` (defaults ``True``, even for non-BOS-trained 

165 models — attention heads tend to use position 0 as a resting state). 

166 **Pass ``prepend_bos=False`` when tokenizing a fragment of a larger 

167 prompt** — off-by-one position errors usually trace back here. 

168 

169 Reconciliation with ``cfg.tokenizer_prepends_bos`` (tokenizers that add 

170 BOS automatically) is handled internally — pass the value you want; 

171 the bridge adds or strips manually as needed. When 

172 ``cfg.tokenizer_appends_eos=True`` (OLMo, Apertus, etc.), 

173 :meth:`to_tokens` also strips trailing EOS tokens so the model receives 

174 a continuation rather than a terminated sequence; this path is 

175 bridge-specific. 

176 

177 BPE/SentencePiece tokenizers treat ``"hello"``, ``" hello"``, and 

178 ``"Hello"`` as distinct tokens. Concatenated prompts may not tokenize 

179 as the sum of parts — inspect with :meth:`to_str_tokens` when in doubt. 

180 """ 

181 

182 # hook_aliases inherited from BridgeCore 

183 

184 def __init__( 

185 self, 

186 model: nn.Module, 

187 adapter: ArchitectureAdapter, 

188 tokenizer: Any, 

189 *, 

190 driver: Any = None, 

191 ): 

192 """Initialize the bridge. 

193 

194 Args: 

195 model: The model to bridge (must be a PyTorch nn.Module or PreTrainedModel) 

196 adapter: The architecture adapter to use 

197 tokenizer: The tokenizer to use (required) 

198 driver: Optional pre-built :class:`Driver`. Sources that construct 

199 exotic drivers (vLLM, Inspect) pass them here. When ``None``, 

200 a :class:`TransformersDriver` is built from the supplied 

201 ``model``/``adapter``/``tokenizer`` — kept for backward 

202 compatibility with direct ``TransformerBridge(...)`` callers. 

203 """ 

204 nn.Module.__init__(self) 

205 self._n_params_total = sum(parameter.numel() for parameter in model.parameters()) 

206 self.__dict__["original_model"] = model 

207 # Production sources construct their Driver and pass it via ``driver=``. 

208 # The fallback covers tests / direct callers with a hand-rolled triple. 

209 if driver is None: 

210 from transformer_lens.model_bridge.sources.transformers_driver import ( 

211 TransformersDriver, 

212 ) 

213 

214 driver = TransformersDriver(model, adapter, tokenizer) 

215 BridgeCore.__init__(self, adapter, tokenizer, driver) 

216 # real_components maps TL keys to (remote_path, actual_instance) tuples; 

217 # for list components, actual_instance is a list of instances. 

218 self.real_components: Dict[str, tuple] = {} 

219 if not hasattr(self.cfg, "device") or self.cfg.device is None: 219 ↛ 220line 219 didn't jump to line 220 because the condition on line 219 was never true

220 try: 

221 self.cfg.device = str(next(self.original_model.parameters()).device) 

222 except StopIteration: 

223 self.cfg.device = "cpu" 

224 set_original_components(self, self.adapter, self.__dict__["original_model"]) 

225 self._initialize_hook_registry() 

226 self._register_aliases() 

227 self._register_all_aliases_recursive() 

228 # Re-scan after alias registration so alias names (hook_resid_pre, …) 

229 # join the registry alongside their canonical targets. Shared HookPoint 

230 # instances, so no double-firing. 

231 self._scan_existing_hooks(self, "") 

232 self._setup_hook_compatibility() 

233 # Backfill supported_hook_points = registry − non_fireable. Whitelist- 

234 # semantic drivers (Inspect) declared their own non-empty set and skip. 

235 if not self._driver.supported_hook_points: 

236 self._driver.supported_hook_points = ( 

237 frozenset(self._hook_registry) - self._driver.non_fireable_hook_points 

238 ) 

239 # Fail fast on a misshapen driver here, not at first capture. 

240 validate_driver(self._driver, after_bridge_construction=True) 

241 self.processor = None 

242 # Bridge wrappers are inserted into the HF module tree after 

243 # from_pretrained's eval(), and nn.Module defaults to training=True — 

244 # without re-syncing, reconstruction paths apply dropout at inference. 

245 # train() recurses, so this stamps the wrappers with the model's mode. 

246 model.train(model.training) 

247 self.train(model.training) 

248 self.cfg._bind_bridge(self) 

249 

250 def __setstate__(self, state: dict[str, Any]) -> None: 

251 """Restore runtime config routing after deepcopy or deserialization.""" 

252 super().__setstate__(state) 

253 self.cfg._bind_bridge(self) 

254 

255 # boot_transformers / list_supported_models / check_model_support are 

256 # attached by sources.transformers.__init__ (setattr on this class) so the 

257 # source package owns its own boot entry point. 

258 boot_transformers: ClassVar[Callable[..., "TransformerBridge"]] 

259 

260 @property 

261 def original_model(self) -> nn.Module: 

262 """The wrapped ``nn.Module``. Raises :class:`AttributeError` for 

263 non-torch drivers (vLLM, Inspect) that don't expose a local module.""" 

264 driver = getattr(self, "_driver", None) 

265 if driver is None: 

266 # Bridges assembled without __init__ (object.__new__ scaffolds) keep the 

267 # module in the __dict__ mirror the setter maintains. 

268 model = self.__dict__.get("original_model") 

269 if model is None: 

270 raise AttributeError(f"'{type(self).__name__}' has no driver and no original_model") 

271 return model 

272 underlying = getattr(driver, "underlying_model", None) 

273 if underlying is None: 

274 raise AttributeError( 

275 f"{type(driver).__name__} does not expose an nn.Module — " 

276 "non-torch drivers (vLLM, Inspect) operate without a local module." 

277 ) 

278 return underlying 

279 

280 @original_model.setter 

281 def original_model(self, value: nn.Module) -> None: 

282 """Used by weight-processing paths that move the model across devices.""" 

283 self.__dict__["original_model"] = value 

284 # Sync via the driver's public API; non-torch drivers don't implement it. 

285 setter = getattr(getattr(self, "_driver", None), "set_underlying_model", None) 

286 if callable(setter): 

287 setter(value) 

288 

289 def init_weights(self) -> None: 

290 """Reinitialize a TL-native model in place using the bridge config.""" 

291 from transformer_lens.model_bridge.sources.native.init import ( 

292 initialize_native_model, 

293 ) 

294 from transformer_lens.model_bridge.sources.native.model import NativeModel 

295 

296 model = self.original_model 

297 if not isinstance(model, NativeModel): 

298 raise RuntimeError( 

299 "TransformerBridge.init_weights() is only supported for TL-native " 

300 "bridges created with TransformerBridge.boot_native(...); this bridge " 

301 f"wraps {type(model).__name__}." 

302 ) 

303 initialize_native_model(model, self.cfg) 

304 

305 def _set_processed_weight_attributes(self) -> None: 

306 """Create 3D processed weight attributes for attention components. 

307 

308 For each attention component, if it has 2D weights (q.weight, k.weight, v.weight), 

309 reshape them to 3D format [n_heads, d_model, d_head] and set as: 

310 - _processed_W_Q 

311 - _processed_W_K 

312 - _processed_W_V 

313 - _processed_b_Q 

314 - _processed_b_K 

315 - _processed_b_V 

316 

317 This allows property aliases (W_Q, W_K, W_V) to return 3D format for 

318 HookedTransformer compatibility while keeping 2D format for calculations. 

319 """ 

320 

321 n_heads = self.cfg.n_heads 

322 d_head = self.cfg.d_head 

323 d_model = self.cfg.d_model 

324 blocks_iter = [] 

325 for bl_name in _BLOCK_LIST_ATTRS: 

326 if hasattr(self, bl_name): 

327 blocks_iter.append(getattr(self, bl_name)) 

328 if not blocks_iter: 

329 return 

330 for block in [b for bl in blocks_iter for b in bl]: 

331 if "attn" not in block._modules: 

332 continue 

333 attn = block.attn 

334 if not (hasattr(attn, "q") and hasattr(attn.q, "weight")): 

335 continue 

336 try: 

337 w_q_2d = attn.q.weight.data 

338 w_k_2d = attn.k.weight.data 

339 w_v_2d = attn.v.weight.data 

340 attn._processed_W_Q = einops.rearrange( 

341 w_q_2d, "m (i h) -> i m h", i=n_heads, h=d_head 

342 ) 

343 attn._processed_W_K = einops.rearrange( 

344 w_k_2d, "m (i h) -> i m h", i=n_heads, h=d_head 

345 ) 

346 attn._processed_W_V = einops.rearrange( 

347 w_v_2d, "m (i h) -> i m h", i=n_heads, h=d_head 

348 ) 

349 if hasattr(attn.q, "bias") and attn.q.bias is not None: 

350 b_q_2d = attn.q.bias.data 

351 b_k_2d = attn.k.bias.data 

352 b_v_2d = attn.v.bias.data 

353 attn._processed_b_Q = einops.rearrange( 

354 b_q_2d, "(i h) -> i h", i=n_heads, h=d_head 

355 ) 

356 attn._processed_b_K = einops.rearrange( 

357 b_k_2d, "(i h) -> i h", i=n_heads, h=d_head 

358 ) 

359 attn._processed_b_V = einops.rearrange( 

360 b_v_2d, "(i h) -> i h", i=n_heads, h=d_head 

361 ) 

362 if hasattr(attn, "o") and hasattr(attn.o, "weight"): 

363 w_o_2d = attn.o.weight.data 

364 w_o_transposed = w_o_2d.T 

365 attn._processed_W_O = einops.rearrange( 

366 w_o_transposed, "m (i h) -> i h m", i=n_heads, h=d_head 

367 ) 

368 if hasattr(attn.o, "bias") and attn.o.bias is not None: 

369 attn._processed_b_O = attn.o.bias.data 

370 except Exception: 

371 pass 

372 

373 def _register_all_aliases_recursive(self) -> None: 

374 """Recursively register aliases on all bridge components. 

375 

376 This walks through all components and calls _register_aliases() on each one. 

377 Used after weight processing to ensure aliases point to processed weights. 

378 """ 

379 if hasattr(self, "_register_aliases"): 379 ↛ 381line 379 didn't jump to line 381 because the condition on line 379 was always true

380 self._register_aliases() 

381 for module in self.modules(): 

382 if module is not self and hasattr(module, "_register_aliases"): 

383 getattr(module, "_register_aliases")() 

384 

385 def __setattr__(self, name: str, value: Any) -> None: 

386 """Override setattr to track HookPoint objects dynamically.""" 

387 # nn.Module.__setattr__ claims Module values before any data descriptor runs, so the 

388 # original_model property setter would never fire. object.__setattr__ invokes it: 

389 # a registered copy aliases every HF weight into state_dict and makes .to() move twice. 

390 if name == "original_model": 

391 object.__setattr__(self, name, value) 

392 return 

393 super().__setattr__(name, value) 

394 if isinstance(value, HookPoint): 

395 value.name = name 

396 self._hook_registry[name] = value 

397 elif hasattr(value, "get_hooks") and callable(getattr(value, "get_hooks")): 

398 component_hooks = value.get_hooks() 

399 for hook_name, hook in component_hooks.items(): 

400 full_name = f"{name}.{hook_name}" 

401 hook.name = full_name 

402 self._hook_registry[full_name] = hook 

403 

404 def _scan_existing_hooks(self, module: nn.Module, prefix: str = "") -> None: 

405 """Scan existing modules for hooks and add them to registry.""" 

406 visited = set() 

407 # Protect canonical HookPoint names from alias overwrites. Seeded with 

408 # already-registered hooks so the post-alias-registration re-scan adds 

409 # alias registry entries without renaming shared HookPoint instances 

410 # (dir() sorts alphabetically, so block-level alias attributes like 

411 # hook_mlp_out are visited before the mlp child they point into). 

412 named_hook_ids: set = {id(hp) for hp in self._hook_registry.values() if hp.name is not None} 

413 

414 def scan_module(mod: nn.Module, path: str = "") -> None: 

415 obj_id = id(mod) 

416 if obj_id in visited: 

417 return 

418 visited.add(obj_id) 

419 if hasattr(mod, "get_hooks") and callable(getattr(mod, "get_hooks")): 

420 component_hooks = mod.get_hooks() # type: ignore[operator] 

421 if isinstance(component_hooks, dict): 421 ↛ 430line 421 didn't jump to line 430 because the condition on line 421 was always true

422 hooks_dict = cast(Dict[str, HookPoint], component_hooks) 

423 for hook_name, hook in hooks_dict.items(): 

424 full_name = f"{path}.{hook_name}" if path else hook_name 

425 hook_id = id(hook) 

426 if hook_id not in named_hook_ids: 

427 hook.name = full_name 

428 named_hook_ids.add(hook_id) 

429 self._hook_registry[full_name] = hook 

430 for attr_name in dir(mod): 

431 if attr_name.startswith("_"): 

432 continue 

433 if attr_name == "original_component" or attr_name == "original_model": 

434 continue 

435 if attr_name in [ 

436 "OV", 

437 "QK", 

438 "W_V", 

439 "W_O", 

440 "W_Q", 

441 "W_K", 

442 "W_in", 

443 "W_gate", 

444 "W_out", 

445 "b_V", 

446 "b_O", 

447 "b_Q", 

448 "b_K", 

449 "b_in", 

450 "b_out", 

451 ]: 

452 continue 

453 try: 

454 attr = getattr(mod, attr_name) 

455 except (AttributeError, NameError, RuntimeError, TypeError): 

456 continue 

457 name = f"{path}.{attr_name}" if path else attr_name 

458 if isinstance(attr, HookPoint): 

459 hook_id = id(attr) 

460 if hook_id not in named_hook_ids: 

461 attr.name = name 

462 named_hook_ids.add(hook_id) 

463 self._hook_registry[name] = attr 

464 for child_name, child_module in mod.named_children(): 

465 if ( 

466 child_name == "original_component" 

467 or child_name == "_original_component" 

468 or child_name == "original_model" 

469 ): 

470 continue 

471 child_path = f"{path}.{child_name}" if path else child_name 

472 scan_module(child_module, child_path) 

473 

474 scan_module(module, prefix) 

475 

476 @property 

477 def n_params_total(self) -> int: 

478 """Number of parameters in the wrapped model before bridge instrumentation. 

479 

480 This follows PyTorch's parameter iteration semantics, counting tied 

481 parameters once. Bridge-created split views and synthetic zero tensors 

482 are excluded, so the result can differ from 

483 :attr:`HookedTransformer.n_params_total` and :meth:`tl_parameters`. 

484 

485 Returns: 

486 int: Parameter count of the uninstrumented wrapped model. 

487 """ 

488 return self._n_params_total 

489 

490 def _has_registered_blocks(self) -> bool: 

491 """Whether a ``blocks`` stack is registered as a submodule on this bridge. 

492 

493 Checks ``_modules`` directly rather than ``hasattr``: ``__getattr__`` falls 

494 through to the wrapped HF model, so ``hasattr(self, "blocks")`` can be True 

495 for a model that merely exposes its own ``.blocks`` attribute. 

496 """ 

497 modules = self.__dict__.get("_modules") or {} 

498 return "blocks" in modules 

499 

500 def __getattr__(self, name: str) -> Any: 

501 """Provide a clear error message for missing attributes.""" 

502 # Re-invoke original_model's property so its descriptive AttributeError 

503 # for non-torch drivers isn't shadowed by the __dict__ fallback below. 

504 if name == "original_model": 

505 prop = type(self).__dict__.get("original_model") 

506 if isinstance(prop, property) and prop.fget is not None: 

507 return prop.fget(self) 

508 if name in self.__dict__: # type: ignore[arg-type] 508 ↛ 509line 508 didn't jump to line 509 because the condition on line 508 was never true

509 return self.__dict__[name] 

510 # Use __dict__ directly to avoid recursion 

511 if "_modules" in self.__dict__ and name in self.__dict__["_modules"]: # type: ignore[arg-type] 

512 return self.__dict__["_modules"][name] 

513 adapter = self.__dict__.get("adapter") 

514 component_mapping = getattr(adapter, "component_mapping", None) 

515 if component_mapping is not None and name in component_mapping: 

516 raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") 

517 if "original_model" in self.__dict__ and self.__dict__["original_model"] is not None: 

518 try: 

519 name_split = name.split(".") 

520 if len(name_split) > 1: 520 ↛ 521line 520 didn't jump to line 521 because the condition on line 520 was never true

521 current = getattr(self.__dict__["original_model"], name_split[0]) 

522 for part in name_split[1:]: # type: ignore[operator] 

523 current = getattr(current, part) 

524 return current 

525 else: 

526 return getattr(self.__dict__["original_model"], name) 

527 except AttributeError: 

528 pass # type: ignore[operator,assignment] 

529 # A class property whose fget raised AttributeError lands here with the 

530 # informative message discarded (CPython drops it before __getattr__). 

531 # Re-invoke the property so its own diagnostic (e.g. "bias-free 

532 # projection") surfaces instead of a generic missing-attribute error. 

533 descriptor = getattr(type(self), name, None) 

534 if isinstance(descriptor, property) and descriptor.fget is not None: 

535 descriptor.fget(self) 

536 raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") 

537 

538 def __str__(self) -> str: 

539 """One-line-per-component summary of the bridge. 

540 

541 Returns: 

542 A string describing the bridge's components. 

543 """ 

544 lines = ["TransformerBridge:"] 

545 mapping = self.adapter.get_component_mapping() 

546 

547 def _describe(component_mapping, indent): 

548 pad = " " * indent 

549 for name, component in component_mapping.items(): 

550 lines.append(f"{pad}{name}: {type(component).__name__}") 

551 submodules = getattr(component, "submodules", None) 

552 if submodules: 

553 _describe(submodules, indent + 1) 

554 

555 _describe(mapping, 1) 

556 return "\n".join(lines) 

557 

558 def enable_compatibility_mode( 

559 self, 

560 disable_warnings: bool = False, 

561 no_processing: bool = False, 

562 fold_ln: bool = True, 

563 center_writing_weights: bool = True, 

564 center_unembed: bool = True, 

565 fold_value_biases: bool = True, 

566 refactor_factored_attn_matrices: bool = False, 

567 ) -> None: 

568 """Apply HookedTransformer-equivalent weight processing and legacy hook compatibility. 

569 

570 Defaults match HookedTransformer's load-time processing (fold_ln + weight 

571 centering) — required for analyses that reason in HookedTransformer's 

572 post-processed coordinate system: logit lens, direct logit attribution, 

573 residual-stream norms. Also enables legacy hook/component name aliases. 

574 

575 Hook semantic parity (issue #1317): ``hook_q_input``, ``hook_k_input``, 

576 ``hook_v_input``, ``hook_attn_in``, and ``hook_mlp_in`` fire on the 

577 pre-norm residual. Carve-outs: post-norm architectures (OLMo 2, 

578 BERT-style) read the post-attention residual instead, and MLA blocks 

579 (DeepSeek V2/V3/R1) do not expose the split-qkv aliases. ``hook_mlp_in`` 

580 is gated on ``cfg.use_hook_mlp_in``; toggle it via 

581 :py:meth:`set_use_hook_mlp_in`. 

582 

583 Args: 

584 disable_warnings: Whether to disable warnings about legacy components/hooks 

585 no_processing: Whether to disable ALL pre-processing steps of the model. 

586 If True, overrides fold_ln, center_writing_weights, and center_unembed to False. 

587 fold_ln: Whether to fold layer norm weights into the subsequent linear layers. 

588 Default: True. Ignored if no_processing=True. 

589 center_writing_weights: Whether to center the writing weights (W_out in attention and MLPs). 

590 Default: True. Ignored if no_processing=True. 

591 center_unembed: Whether to center the unembedding matrix. 

592 Default: True. Ignored if no_processing=True. 

593 fold_value_biases: Whether to fold value biases into output bias. 

594 Default: True. Ignored if no_processing=True. 

595 refactor_factored_attn_matrices: Whether to refactor factored attention matrices. 

596 Default: False. Ignored if no_processing=True. 

597 """ 

598 from transformer_lens.utilities.bridge_components import ( 

599 apply_fn_to_all_components, 

600 ) 

601 

602 if not getattr(self.adapter, "supports_compatibility_mode", True): 

603 raise RuntimeError( 

604 f"{type(self.adapter).__name__} does not support compatibility mode: " 

605 "its stored-processed-weights path is known to diverge from the " 

606 "reference model. Use the default bridge forward instead." 

607 ) 

608 

609 hf_device_map = getattr(self.original_model, "hf_device_map", None) 

610 if hf_device_map and not no_processing: 

611 offloaded = {k for k, v in hf_device_map.items() if str(v).lower() in ("cpu", "disk")} 

612 if offloaded: 612 ↛ 626line 612 didn't jump to line 626 because the condition on line 612 was always true

613 raise RuntimeError( 

614 "enable_compatibility_mode() with weight processing " 

615 "(fold_ln/center_writing_weights/center_unembed/fold_value_biases) is not " 

616 "supported on a bridge with an offloaded device_map " 

617 f"({sorted(offloaded)} are CPU/disk-offloaded). Weight processing reads and " 

618 "rewrites parameters directly across many components at once, not through a " 

619 "single component's own forward() call the way the default (non-compat-mode) " 

620 "bridge forward does, so it isn't covered by GeneralizedComponent's per-call " 

621 "materialization and hits raw meta tensors. Load without a CPU/disk device_map " 

622 "for compatibility mode, or call enable_compatibility_mode(no_processing=True) " 

623 "for the hook/component compatibility layer without the weight transforms." 

624 ) 

625 

626 if getattr(self.cfg, "is_audio_model", False) and not getattr( 

627 self.cfg, "is_audio_seq2seq", False 

628 ): 

629 # Audio encoders have no text embed/unembed for the legacy weight 

630 # processing to operate on; without this guard the processing path 

631 # dies later with an opaque KeyError ('embed.weight'). 

632 raise NotImplementedError( 

633 "enable_compatibility_mode() is not supported for audio encoder models: " 

634 "the legacy weight processing (fold_ln/centering) assumes a text " 

635 "embed/unembed, which audio encoders do not have. Use the bridge's " 

636 "native hooks (run_with_cache / run_with_hooks) directly." 

637 ) 

638 

639 self.compatibility_mode = True 

640 

641 def set_compatibility_mode(component: Any) -> None: 

642 """Set compatibility mode on a component.""" 

643 component.compatibility_mode = True 

644 component.disable_warnings = disable_warnings 

645 

646 apply_fn_to_all_components(self, set_compatibility_mode) 

647 self.clear_hook_registry() 

648 # Drop block capture-hook handles from any prior call so they don't accumulate. 

649 if hasattr(self, "blocks"): 

650 for block in self.blocks: 

651 if hasattr(block, "_teardown_capture_hooks"): 651 ↛ 650line 651 didn't jump to line 650 because the condition on line 651 was always true

652 block._teardown_capture_hooks() 

653 try: 

654 if not no_processing: 

655 self.process_weights( 

656 fold_ln=fold_ln, 

657 center_writing_weights=center_writing_weights, 

658 center_unembed=center_unembed, 

659 fold_value_biases=fold_value_biases, 

660 refactor_factored_attn_matrices=refactor_factored_attn_matrices, 

661 ) 

662 finally: 

663 # Re-initialize hooks even on failure so bridge stays usable 

664 self._initialize_hook_registry() 

665 self._setup_hook_compatibility() 

666 self._register_all_aliases_recursive() 

667 

668 def _setup_hook_compatibility(self) -> None: 

669 """Setup hook compatibility transformations to match HookedTransformer behavior. 

670 

671 This method sets up hook conversions and wrappers that ensure Bridge hooks 

672 have the same shapes and behavior as HookedTransformer hooks. This includes: 

673 1. hook_z reshaping from [batch, seq, d_model] to [batch, seq, n_heads, d_head] 

674 2. Wrapping HF attention forward to inject position embeddings/attention masks 

675 3. Architecture-specific setup (e.g., rotary embedding references) 

676 

677 This is called during __init__ and should always be run, regardless of whether 

678 compatibility mode or weight processing is enabled. 

679 

680 Note: This method is idempotent - can be called multiple times safely. 

681 """ 

682 if hasattr(self.adapter, "setup_hook_compatibility"): 

683 self.adapter.setup_hook_compatibility(self) 

684 elif hasattr(self.adapter, "setup_no_processing_hooks"): 684 ↛ 685line 684 didn't jump to line 685 because the condition on line 684 was never true

685 self.adapter.setup_no_processing_hooks(self) 

686 blocks_to_process = [] 

687 for block_list_name in ( 

688 "blocks", 

689 "encoder_blocks", 

690 "decoder_blocks", 

691 "L_blocks", 

692 "H_blocks", 

693 ): 

694 if hasattr(self, block_list_name): 

695 blocks_to_process.extend(getattr(self, block_list_name)) 

696 # A vision tower's layers are not a top-level block list, so they were 

697 # skipped here and their attention never had q/k/v/z reshaping set up -- 

698 # those hooks fired flat, ignoring the tower's head count. 

699 vision_encoder = getattr(self, "vision_encoder", None) 

700 vision_layers = getattr(vision_encoder, "encoder_layers", None) 

701 if vision_layers is not None: 

702 blocks_to_process.extend(vision_layers) 

703 for block in blocks_to_process: 

704 for attn_name in ["attn", "self_attn", "cross_attn"]: 

705 if hasattr(block, attn_name): 

706 attn = getattr(block, attn_name) 

707 if hasattr(attn, "setup_hook_compatibility"): 

708 attn.setup_hook_compatibility() 

709 elif hasattr(attn, "setup_no_processing_hooks"): 709 ↛ 710line 709 didn't jump to line 710 because the condition on line 709 was never true

710 attn.setup_no_processing_hooks() 

711 

712 def process_weights( 

713 self, 

714 verbose: bool = False, 

715 fold_ln: bool = True, 

716 center_writing_weights: bool = True, 

717 center_unembed: bool = True, 

718 fold_value_biases: bool = True, 

719 refactor_factored_attn_matrices: bool = False, 

720 ) -> None: 

721 """Process weights directly using ProcessWeights and architecture adapter. 

722 

723 This method applies weight processing transformations to improve model interpretability 

724 without requiring a reference HookedTransformer model. Works with all architectures 

725 supported by TransformerBridge, including GPT-OSS and other new models. 

726 

727 Args: 

728 verbose: If True, print detailed progress messages. Default: False 

729 fold_ln: Fold LayerNorm weights/biases into subsequent layers. Default: True 

730 center_writing_weights: Center weights that write to residual stream. Default: True 

731 center_unembed: Center unembedding weights (translation invariant). Default: True 

732 fold_value_biases: Fold value biases into output bias. Default: True 

733 refactor_factored_attn_matrices: Experimental QK/OV factorization. Default: False 

734 """ 

735 # Match HookedTransformer: warn and skip rather than raise. Folding and centering 

736 # read their own factors out of the weights and neutralize them, so a repeat pass 

737 # is a no-op for every architecture — but adapters that fold a factor held outside 

738 # the weights would double-apply it, and notebook cell re-runs make that routine. 

739 if self._weights_processed: 

740 logging.warning( 

741 "process_weights was already applied to this bridge. Skipping: re-running " 

742 "it would re-apply adapter weight folds. Boot a fresh bridge with " 

743 "TransformerBridge.boot_transformers(...) to process with different options." 

744 ) 

745 return 

746 

747 # Folding and centering do arithmetic on raw weights, so packed or 

748 # scale-separated storage would produce silent garbage. The forward 

749 # path stays usable when quantized; only this transformation does not. 

750 for name, param in self.original_model.named_parameters(): 

751 # No name filter: modern batched-MoE experts are Parameters that do 

752 # NOT end in .weight (mlp.experts.gate_up_proj), and those are the 

753 # very tensors the converters had to guard. unreadable_weight_reason 

754 # is dtype-driven, so every full-width float parameter still passes. 

755 # Routed through the shared helper so meta gets its own "load with 

756 # real weights" message instead of being silently skipped — folding 

757 # on meta tensors yields meta tensors, which is the same 

758 # silent-garbage failure this guard exists to stop. 

759 require_readable_weight( 

760 param, 

761 operation=f"process weights ({name})", 

762 owner=self.original_model, 

763 remedy=( 

764 "Load the model dequantized, or use the bridge without weight " 

765 "processing (enable_compatibility_mode(no_processing=True))." 

766 ), 

767 ) 

768 

769 # A failed or partial processing attempt is no longer guaranteed to retain 

770 # the raw HuggingFace basis, so invalidate that contract before any work. 

771 self._weights_processed = True 

772 from transformer_lens.weight_processing import ProcessWeights 

773 

774 if verbose: 774 ↛ 775line 774 didn't jump to line 775 because the condition on line 774 was never true

775 print(f"Processing weights for {self.cfg.model_name}...") 

776 

777 # Soft capping (tanh) is not translation-invariant; centering would change output. 

778 if center_unembed and softcap_enabled(getattr(self.cfg, "output_logits_soft_cap", None)): 778 ↛ 779line 778 didn't jump to line 779 because the condition on line 778 was never true

779 logging.warning( 

780 "center_unembed=True is incompatible with logit softcapping " 

781 "(output_logits_soft_cap=%.1f). Disabling center_unembed.", 

782 self.cfg.output_logits_soft_cap, 

783 ) 

784 center_unembed = False 

785 

786 if verbose: 786 ↛ 787line 786 didn't jump to line 787 because the condition on line 786 was never true

787 print(" Extracting state dict from existing model...") 

788 state_dict = self.state_dict() 

789 adapter = self.adapter 

790 

791 # Untie the unembedding from the embedding it shares storage with (GPT-2's embed, 

792 # Whisper's decoder_embed) so centering affects only unembed 

793 unembed_key = "unembed.weight" 

794 unembed = state_dict.get(unembed_key) 

795 if unembed is not None and any( 

796 key != unembed_key and value.data_ptr() == unembed.data_ptr() 

797 for key, value in state_dict.items() 

798 ): 

799 if verbose: 799 ↛ 800line 799 didn't jump to line 800 because the condition on line 799 was never true

800 print(" Breaking weight tying between embed and unembed in state dict...") 

801 state_dict[unembed_key] = unembed.clone() 

802 

803 if adapter is not None: 803 ↛ 812line 803 didn't jump to line 812 because the condition on line 803 was always true

804 # A square weight's shape cannot tell Conv1D's [in, out] from nn.Linear's 

805 # [out, in], so record the [in, out] ones for the layout-sensitive folds. 

806 adapter._in_out_weight_keys = { 

807 key 

808 for key in state_dict 

809 if key.endswith(".weight") and self._stores_weight_in_out(key[: -len(".weight")]) 

810 } 

811 

812 if adapter and hasattr(adapter, "preprocess_weights"): 812 ↛ 818line 812 didn't jump to line 818 because the condition on line 812 was always true

813 adapter._fold_ln_requested = fold_ln # type: ignore[union-attr] 

814 state_dict = adapter.preprocess_weights(state_dict) 

815 

816 # Use the unified ProcessWeights.process_weights() pipeline. 

817 # Float32 upcasting for precision is handled centrally in process_weights(). 

818 if verbose: 818 ↛ 819line 818 didn't jump to line 819 because the condition on line 818 was never true

819 print(" Processing weights (fold_ln, center_writing_weights, etc.)...") 

820 state_dict = ProcessWeights.process_weights( 

821 state_dict, 

822 self.cfg, 

823 fold_ln=fold_ln, 

824 center_writing_weights=center_writing_weights, 

825 center_unembed=center_unembed, 

826 fold_value_biases=fold_value_biases, 

827 refactor_factored_attn_matrices=refactor_factored_attn_matrices, 

828 adapter=adapter, 

829 ) 

830 

831 # Normalize HF-prefix keys to TL format for weight routing 

832 import re 

833 

834 hf_to_tl_prefix = {} 

835 for tl_name, (remote_path, _component) in self.real_components.items(): 

836 if remote_path and remote_path != tl_name: 836 ↛ 835line 836 didn't jump to line 835 because the condition on line 836 was always true

837 hf_to_tl_prefix[remote_path] = tl_name 

838 

839 normalized_state_dict = {} 

840 for key, value in state_dict.items(): 

841 new_key = key 

842 for hf_prefix, tl_prefix in hf_to_tl_prefix.items(): 

843 if key.startswith(hf_prefix + "."): 843 ↛ 844line 843 didn't jump to line 844 because the condition on line 843 was never true

844 suffix = key[len(hf_prefix) + 1 :] 

845 new_key = f"{tl_prefix}.{suffix}" 

846 break 

847 normalized_state_dict[self._block_submodule_key_to_bridge(new_key)] = value 

848 state_dict = normalized_state_dict 

849 

850 if verbose: 850 ↛ 851line 850 didn't jump to line 851 because the condition on line 850 was never true

851 print(" Distributing weights to generalized components...") 

852 ProcessWeights.distribute_weights_to_components( 

853 state_dict=state_dict, 

854 component_mapping=self.real_components, 

855 ) 

856 if fold_ln: 

857 self._fold_layer_norms_into_batched_experts() 

858 if adapter is not None: 858 ↛ exitline 858 didn't return from function 'process_weights' because the condition on line 858 was always true

859 adapter.postprocess_weights(self) 

860 

861 def _block_submodule_key_to_bridge(self, key: str) -> str: 

862 """Rename a block key's HF submodule segment to the bridge name that owns it. 

863 

864 Encoder-decoder state dicts keep HF names inside blocks (``self_attn_layer_norm``), 

865 but a block routes processed weights by bridge name (``ln1``); bridge names pass through. 

866 """ 

867 parts = key.split(".") 

868 if len(parts) < 3 or not parts[1].isdigit() or not self.adapter.component_mapping: 

869 return key 

870 submodules = getattr(self.adapter.component_mapping.get(parts[0]), "submodules", None) 

871 if not submodules or parts[2] in submodules: 

872 return key 

873 for bridge_name, submodule in submodules.items(): 873 ↛ 876line 873 didn't jump to line 876 because the loop on line 873 didn't complete

874 if submodule.name == parts[2]: 

875 return ".".join([parts[0], parts[1], bridge_name, *parts[3:]]) 

876 return key 

877 

878 def _stores_weight_in_out(self, module_name: str) -> bool: 

879 """Whether the component at module_name wraps a Conv1D-style [in, out] weight.""" 

880 try: 

881 module = self.get_submodule(module_name) 

882 except AttributeError: 

883 return False 

884 return weight_layout_in_out(module) is True 

885 

886 def _fold_layer_norms_into_batched_experts(self) -> None: 

887 """Fold each batched-expert MoE layer's ln2 into the weights that read it. 

888 

889 transformers stores a whole expert stack in one 3-D Parameter, which is not a 

890 ``weight``/``bias`` leaf of a declared bridge submodule and so never appears in 

891 the state dict ProcessWeights folds. Left alone those layers keep their learned 

892 FFN gains while attention and dense layers of the same model lose theirs, and 

893 the mixed basis surfaces only in DLA / logit-lens / factored-matrix reads. 

894 

895 Runs on the live model because the readers include tensors the state dict 

896 cannot carry: batched experts, and the shared-expert MLPs that Qwen2-MoE and 

897 GLM4-MoE hang off the same norm. 

898 """ 

899 # An adapter that declares fold_ln unsupported cannot have its norms folded 

900 # weight-preservingly. ProcessWeights already warns and skips for these; folding 

901 # the expert stack anyway leaves the model diverging from the reference. 

902 if not getattr(self.adapter, "supports_fold_ln", True): 

903 return 

904 

905 uses_offset = bool(getattr(self.cfg, "rmsnorm_uses_offset", False)) 

906 skipped: list[str] = [] 

907 for list_name in ("blocks", "encoder_blocks", "decoder_blocks"): 

908 for index, block in enumerate(getattr(self, list_name, None) or []): 

909 mlp = getattr(block, "mlp", None) 

910 if mlp is None or not has_batched_experts(mlp): 

911 continue 

912 label = f"{list_name}.{index}" 

913 norm = getattr(block, "ln2", None) 

914 weight = getattr(norm, "weight", None) if norm is not None else None 

915 if not isinstance(weight, torch.Tensor) or weight.ndim != 1: 915 ↛ 916line 915 didn't jump to line 916 because the condition on line 915 was never true

916 skipped.append(label) 

917 continue 

918 if getattr(norm, "bias", None) is not None: 918 ↛ 920line 918 didn't jump to line 920 because the condition on line 918 was never true

919 # Folding the gain but not the shift would change the block's output. 

920 skipped.append(label) 

921 continue 

922 scale = weight.detach().clone() 

923 if uses_offset: 923 ↛ 924line 923 didn't jump to line 924 because the condition on line 923 was never true

924 scale += 1.0 

925 if not fold_scale_into_moe_block(mlp, scale): 925 ↛ 926line 925 didn't jump to line 926 because the condition on line 925 was never true

926 skipped.append(label) 

927 continue 

928 with torch.no_grad(): 

929 weight.fill_(0.0 if uses_offset else 1.0) 

930 if skipped: 930 ↛ 931line 930 didn't jump to line 931 because the condition on line 930 was never true

931 logging.warning( 

932 "fold_ln could not reach the expert weights of %s, so those layers keep " 

933 "their FFN norm gains while the rest of the model is folded. Direct " 

934 "logit attribution and logit lens will mix two bases.", 

935 ", ".join(skipped), 

936 ) 

937 

938 def to_tokens( 

939 self, 

940 input: Union[str, List[str]], 

941 prepend_bos: Optional[bool] = None, 

942 padding_side: Optional[str] = None, 

943 move_to_device: bool = True, 

944 truncate: bool = True, 

945 ) -> torch.Tensor: 

946 """Converts a string to a tensor of tokens. 

947 

948 See the class-level "Tokenization notes" for full ``prepend_bos`` 

949 semantics, the ``default_prepend_bos`` / 

950 ``tokenizer_prepends_bos`` interaction, and the whitespace- 

951 sensitivity gotcha. **Pass ``prepend_bos=False`` whenever you're 

952 tokenizing only part of a prompt.** 

953 

954 Args: 

955 input: The input to tokenize. 

956 prepend_bos: Overrides ``self.cfg.default_prepend_bos``. Defaults 

957 to ``None`` (use the cfg setting). Pass ``True`` or ``False`` 

958 to override locally. 

959 padding_side: Which side to pad on when tokenizing multiple 

960 strings of different lengths. Defaults to the tokenizer's 

961 ``padding_side``. 

962 move_to_device: Whether to move the result to ``cfg.device``. 

963 truncate: Whether to truncate inputs longer than ``cfg.n_ctx``. 

964 

965 Returns: 

966 Token tensor of shape ``[batch, pos]``. 

967 """ 

968 assert self.tokenizer is not None, "Cannot use to_tokens without a tokenizer" 

969 if prepend_bos is None: 

970 prepend_bos = getattr(self.cfg, "default_prepend_bos", True) 

971 if padding_side is None: 

972 padding_side = getattr(self.tokenizer, "padding_side", "right") 

973 tokenizer_prepends_bos = getattr(self.cfg, "tokenizer_prepends_bos", True) 

974 if prepend_bos and (not tokenizer_prepends_bos): 

975 bos = self.tokenizer.bos_token 

976 encodes_atomically = ( 

977 bos is not None 

978 and len(self.tokenizer(bos, add_special_tokens=False)["input_ids"]) == 1 

979 ) 

980 if encodes_atomically: 

981 input = utils.get_input_with_manually_prepended_bos(bos, input) 

982 # else: the fallback BOS is not an atom in this vocab (e.g. 

983 # '<|endoftext|>' installed on BERT); prepending the string would 

984 # tokenize to subword garbage, so skip rather than pollute the input. 

985 if isinstance(input, str): 

986 input = [input] 

987 tokens = self.tokenizer( 

988 input, 

989 return_tensors="pt", 

990 padding=True, 

991 padding_side=padding_side, 

992 truncation=truncate, 

993 max_length=self.cfg.n_ctx if truncate else None, 

994 )["input_ids"] 

995 # Strip auto-appended EOS tokens (e.g., OLMo) 

996 if ( 

997 getattr(self.cfg, "tokenizer_appends_eos", False) 

998 and self.tokenizer.eos_token_id is not None 

999 ): 

1000 # Remove trailing EOS, keep at least 1 token 

1001 while tokens.shape[-1] > 1 and (tokens[:, -1] == self.tokenizer.eos_token_id).all(): 

1002 tokens = tokens[:, :-1] 

1003 if not prepend_bos and tokenizer_prepends_bos: 

1004 tokens = utils.get_tokens_with_bos_removed( 

1005 self.tokenizer, tokens, padding_side=padding_side 

1006 ) 

1007 if move_to_device: 

1008 tokens = tokens.to(self.cfg.device) 

1009 return tokens 

1010 

1011 def encoder_output( 

1012 self, 

1013 frames: torch.Tensor, 

1014 one_zero_attention_mask: Optional[torch.Tensor] = None, 

1015 ) -> torch.Tensor: 

1016 """Run the audio encoder from precomputed frames, skipping feature extraction. 

1017 

1018 The audio-path analogue of ``start_at_layer``: ``frames`` is 

1019 ``[batch, frames, d_model]``, the tensor the conv front end would have 

1020 produced (observable at ``feat_proj.hook_out``), so callers can inject or 

1021 reuse frames without re-running the waveform convolutions. Positional 

1022 convolution and the encoder layer norm are applied first, exactly as the 

1023 full path does, then the blocks run. Mirrors 

1024 ``HookedAudioEncoder.encoder_output``. 

1025 

1026 Hooks on the bridged components fire as usual, so this composes with 

1027 ``add_hook`` / ``get_caching_hooks``. 

1028 

1029 Args: 

1030 frames: ``[batch, frames, d_model]`` precomputed encoder frames. 

1031 one_zero_attention_mask: Optional ``[batch, frames]`` mask, 1 for 

1032 real frames and 0 for padding. 

1033 

1034 Returns: 

1035 The residual stream leaving the final block, ``[batch, frames, d_model]``. 

1036 """ 

1037 self._require_frame_entry_support() 

1038 if frames.ndim != 3: 

1039 raise ValueError( 

1040 "encoder_output expects precomputed frames [batch, frames, d_model]; " 

1041 f"got a {frames.ndim}D tensor. Pass a waveform to forward() instead." 

1042 ) 

1043 frames = frames.to(self.cfg.device) 

1044 

1045 if one_zero_attention_mask is not None: 

1046 # HF zeroes pad frames before the positional conv (kernel 128 smears 

1047 # pad content into real frames otherwise); masked_fill, not HF's 

1048 # in-place write, so the caller's tensor survives. 

1049 frames = frames.masked_fill( 

1050 ~one_zero_attention_mask.to(frames.device).bool().unsqueeze(-1), 0.0 

1051 ) 

1052 

1053 resid = frames + self.conv_pos_embed(frames) 

1054 # Post-LN encoders (do_stable_layer_norm=False: hubert-base, 

1055 # wav2vec2-base) normalize before the blocks; stable-LN encoders 

1056 # (wav2vec2-large and kin) apply this same module AFTER the blocks — 

1057 # HF's Wav2Vec2EncoderStableLayerNorm.forward. Mirror the real order or 

1058 # every stable-LN activation is silently wrong. 

1059 stable_ln = self._audio_encoder_is_stable_layer_norm() 

1060 if not stable_ln: 

1061 resid = self.embed_ln(resid) 

1062 

1063 additive_attention_mask = None 

1064 if one_zero_attention_mask is not None: 

1065 mask = one_zero_attention_mask.to(self.cfg.device) 

1066 additive_attention_mask = torch.where( 

1067 mask[:, None, None, :] == 0, 

1068 torch.tensor(float("-inf"), dtype=resid.dtype, device=resid.device), 

1069 torch.tensor(0.0, dtype=resid.dtype, device=resid.device), 

1070 ) 

1071 

1072 for block in self.blocks: 

1073 output = block(resid, attention_mask=additive_attention_mask) 

1074 resid = output[0] if isinstance(output, tuple) else output 

1075 if stable_ln: 

1076 resid = self.embed_ln(resid) 

1077 return resid 

1078 

1079 def _audio_encoder_is_stable_layer_norm(self) -> bool: 

1080 """Whether the wrapped audio encoder is the pre-LN ("stable") variant. 

1081 

1082 Structural, not config-driven: build_bridge_from_module never runs the 

1083 adapter's prepare_loading, so cfg.do_stable_layer_norm can be absent 

1084 on that path while the module class is authoritative on both. 

1085 """ 

1086 model = self.original_model 

1087 for attr in ("encoder", "wav2vec2", "hubert", "model"): 1087 ↛ 1094line 1087 didn't jump to line 1094 because the loop on line 1087 didn't complete

1088 candidate = getattr(model, attr, None) 

1089 if candidate is None: 1089 ↛ 1090line 1089 didn't jump to line 1090 because the condition on line 1089 was never true

1090 continue 

1091 encoder = candidate if attr == "encoder" else getattr(candidate, "encoder", None) 

1092 if encoder is not None: 1092 ↛ 1087line 1092 didn't jump to line 1087 because the condition on line 1092 was always true

1093 return type(encoder).__name__.endswith("StableLayerNorm") 

1094 return bool(getattr(self.cfg, "do_stable_layer_norm", False)) 

1095 

1096 def _require_frame_entry_support(self) -> None: 

1097 """Reject models with no conv-frame stage to re-enter.""" 

1098 if not getattr(self.cfg, "is_audio_model", False): 

1099 raise NotImplementedError( 

1100 "encoder_output is an audio-encoder entry point; this bridge is not an " 

1101 "audio model. Use start_at_layer for residual re-entry on text models." 

1102 ) 

1103 missing = [ 

1104 name 

1105 for name in ("conv_pos_embed", "embed_ln", "blocks") 

1106 if self._modules.get(name) is None 

1107 ] 

1108 if missing: 

1109 raise NotImplementedError( 

1110 "encoder_output needs a waveform encoder with a convolutional front end " 

1111 f"(missing {missing}). Spectrogram encoders such as AST have no " 

1112 "precomputed-frame stage to re-enter, so there is nothing to bypass." 

1113 ) 

1114 

1115 def to_sentence_pair_tokens( 

1116 self, 

1117 sentence_a: str, 

1118 sentence_b: str, 

1119 move_to_device: bool = True, 

1120 truncate: bool = True, 

1121 ) -> Dict[str, torch.Tensor]: 

1122 """Pair-tokenize two sentences as ``[CLS] a [SEP] b [SEP]``. 

1123 

1124 Returns ``input_ids``, ``token_type_ids`` and ``attention_mask``. The 

1125 segment ids are not decorative: without them a BERT NSP head sees both 

1126 sentences as one segment and its logits collapse. Mirrors 

1127 ``BertNextSentencePrediction.to_tokens``. 

1128 

1129 Args: 

1130 sentence_a: First sentence of the pair. 

1131 sentence_b: Second sentence of the pair. 

1132 move_to_device: Move the returned tensors to ``cfg.device``. 

1133 truncate: Truncate to the model's context window. 

1134 """ 

1135 assert self.tokenizer is not None, "Cannot pair-tokenize without a tokenizer" 

1136 encodings = self.tokenizer( 

1137 sentence_a, 

1138 sentence_b, 

1139 return_tensors="pt", 

1140 padding=True, 

1141 truncation=truncate, 

1142 max_length=self.cfg.n_ctx if truncate else None, 

1143 ) 

1144 if "token_type_ids" not in encodings: 1144 ↛ 1145line 1144 didn't jump to line 1145 because the condition on line 1144 was never true

1145 raise ValueError( 

1146 f"{type(self.tokenizer).__name__} emits no token_type_ids, so it cannot " 

1147 "express a sentence pair. Next-sentence prediction needs a " 

1148 "segment-aware tokenizer (e.g. BERT's)." 

1149 ) 

1150 keys = ("input_ids", "token_type_ids", "attention_mask") 

1151 tokens = {key: encodings[key] for key in keys if key in encodings} 

1152 if move_to_device: 1152 ↛ 1154line 1152 didn't jump to line 1154 because the condition on line 1152 was always true

1153 tokens = {key: value.to(self.cfg.device) for key, value in tokens.items()} 

1154 return tokens 

1155 

1156 def predict_next_sentence( 

1157 self, 

1158 sentence_a: str, 

1159 sentence_b: str, 

1160 return_type: Optional[str] = "predictions", 

1161 truncate: bool = True, 

1162 ) -> Any: 

1163 """Run next-sentence prediction over a sentence pair given as strings. 

1164 

1165 Owns the ``token_type_ids`` plumbing that a hand-rolled pair forward has 

1166 to remember. Requires a bridge booted onto an NSP head — otherwise the 

1167 model has no 2-class output to decode. Mirrors 

1168 ``BertNextSentencePrediction.forward``. 

1169 

1170 Args: 

1171 sentence_a: First sentence of the pair. 

1172 sentence_b: Second sentence of the pair. 

1173 return_type: ``"predictions"`` for the decoded verdict, or 

1174 ``"logits"`` for the raw 2-class scores. 

1175 truncate: Truncate to the model's context window. 

1176 """ 

1177 tokens = self.to_sentence_pair_tokens(sentence_a, sentence_b, truncate=truncate) 

1178 forward_kwargs: Dict[str, Any] = { 

1179 key: value for key, value in tokens.items() if key != "input_ids" 

1180 } 

1181 logits = self(tokens["input_ids"], return_type="logits", **forward_kwargs) 

1182 if logits.shape[-1] != 2: 

1183 raise ValueError( 

1184 "predict_next_sentence needs a next-sentence-prediction head, but this " 

1185 f"bridge produces {logits.shape[-1]} output classes. Boot it with " 

1186 "model_class=BertForNextSentencePrediction." 

1187 ) 

1188 if return_type == "logits": 

1189 return logits 

1190 return self._finalize_return(return_type, logits, tokens["input_ids"]) 

1191 

1192 def to_string( 

1193 self, tokens: Union[List[int], torch.Tensor, np.ndarray] 

1194 ) -> Union[str, List[str]]: 

1195 """Convert tokens to string(s). 

1196 

1197 Args: 

1198 tokens: Tokens to convert 

1199 

1200 Returns: 

1201 Decoded string(s) 

1202 """ 

1203 if not isinstance(tokens, torch.Tensor): 1203 ↛ 1204line 1203 didn't jump to line 1204 because the condition on line 1203 was never true

1204 tokens = torch.tensor(tokens) 

1205 if len(tokens.shape) == 2: 

1206 return self.tokenizer.batch_decode(tokens, clean_up_tokenization_spaces=False) 

1207 elif len(tokens.shape) <= 1: 1207 ↛ 1210line 1207 didn't jump to line 1210 because the condition on line 1207 was always true

1208 return self.tokenizer.decode(tokens, clean_up_tokenization_spaces=False) 

1209 else: 

1210 raise ValueError(f"Invalid shape passed in: {tokens.shape}") 

1211 

1212 def to_str_tokens( 

1213 self, 

1214 input: Union[str, torch.Tensor, np.ndarray, List], 

1215 prepend_bos: Optional[bool] = None, 

1216 padding_side: Optional[str] = None, 

1217 ) -> Union[List[str], List[List[str]]]: 

1218 """Map text or tokens to a list of tokens as strings. 

1219 

1220 See the class-level "Tokenization notes" for full ``prepend_bos`` 

1221 semantics. **Pass ``prepend_bos=False`` whenever you're tokenizing 

1222 only part of a prompt.** When ``input`` is already a tensor or 

1223 array, ``prepend_bos`` and ``padding_side`` are ignored. 

1224 

1225 Args: 

1226 input: A string, list of strings, or tensor/array of token IDs. 

1227 prepend_bos: Overrides ``self.cfg.default_prepend_bos``. Only 

1228 applies when ``input`` is a string. Defaults to ``None`` 

1229 (use the cfg setting). 

1230 padding_side: Which side to pad on. Only applies when ``input`` 

1231 is a string. 

1232 

1233 Returns: 

1234 List of token strings. 

1235 """ 

1236 if isinstance(input, list): 

1237 return cast( 

1238 List[List[str]], 

1239 [self.to_str_tokens(item, prepend_bos, padding_side) for item in input], 

1240 ) 

1241 elif isinstance(input, str): 1241 ↛ 1243line 1241 didn't jump to line 1243 because the condition on line 1241 was always true

1242 tokens = self.to_tokens(input, prepend_bos=prepend_bos, padding_side=padding_side)[0] 

1243 elif isinstance(input, torch.Tensor): 

1244 tokens = input.squeeze() 

1245 if tokens.dim() == 0: 

1246 tokens = tokens.unsqueeze(0) 

1247 assert ( 

1248 tokens.dim() == 1 

1249 ), f"Invalid tokens input to to_str_tokens, has shape: {tokens.shape}" 

1250 elif isinstance(input, np.ndarray): 

1251 tokens_np = input.squeeze() 

1252 if tokens_np.ndim == 0: 

1253 tokens_np = np.expand_dims(tokens_np, axis=0) 

1254 assert ( 

1255 tokens_np.ndim == 1 

1256 ), f"Invalid tokens input to to_str_tokens, has shape: {tokens_np.shape}" 

1257 tokens = torch.tensor(tokens_np) 

1258 else: 

1259 raise ValueError(f"Invalid input type to to_str_tokens: {type(input)}") 

1260 # v5 compat: wrap each token so batch_decode decodes them individually 

1261 tokens_list = [[int(t)] for t in tokens.tolist()] 

1262 str_tokens = self.tokenizer.batch_decode(tokens_list, clean_up_tokenization_spaces=False) 

1263 return str_tokens 

1264 

1265 def to_single_token(self, string: str) -> int: 

1266 """Map a string that makes up a single token to the id for that token. 

1267 

1268 Args: 

1269 string: The string to convert 

1270 

1271 Returns: 

1272 Token ID 

1273 

1274 Raises: 

1275 AssertionError: If string is not a single token 

1276 """ 

1277 token = self.to_tokens(string, prepend_bos=False).squeeze() 

1278 if token.numel() != 1: 1278 ↛ 1279line 1278 didn't jump to line 1279 because the condition on line 1278 was never true

1279 raise AssertionError(f"Input string: {string} is not a single token!") 

1280 return int(token.item()) 

1281 

1282 def get_token_position( 

1283 self, 

1284 single_token: Union[str, int], 

1285 input: Union[str, torch.Tensor], 

1286 mode="first", 

1287 prepend_bos: Optional[Union[bool, None]] = None, 

1288 padding_side: Optional[Union[Literal["left", "right"], None]] = None, 

1289 ): 

1290 """Get the position of a single_token in a string or sequence of tokens. 

1291 

1292 Raises an error if the token is not present. 

1293 

1294 When ``input`` is a string it's tokenized internally — see the 

1295 class-level "Tokenization notes" for ``prepend_bos`` semantics. 

1296 Off-by-one position errors usually mean ``prepend_bos`` is on 

1297 when it shouldn't be (or vice versa); pass ``prepend_bos=False`` 

1298 when ``input`` is a fragment of a larger prompt. 

1299 

1300 Args: 

1301 single_token (Union[str, int]): The token to search for. Can 

1302 be a token index, or a string (but the string must correspond to a single token). 

1303 input (Union[str, torch.Tensor]): The sequence to 

1304 search in. Can be a string or a rank 1 tensor of tokens or a rank 2 tensor of tokens 

1305 with a dummy batch dimension. 

1306 mode (str, optional): If there are multiple matches, which match to return. Supports 

1307 "first" or "last". Defaults to "first". 

1308 prepend_bos (bool, optional): Overrides ``self.cfg.default_prepend_bos``. Only 

1309 applies when ``input`` is a string. Defaults to ``None`` (use the cfg setting). 

1310 padding_side (Union[Literal["left", "right"], None], optional): Specifies which 

1311 side to pad when tokenizing multiple strings of different lengths. 

1312 """ 

1313 if isinstance(input, str): 

1314 tokens = self.to_tokens(input, prepend_bos=prepend_bos, padding_side=padding_side) 

1315 else: 

1316 tokens = input 

1317 if len(tokens.shape) == 2: 

1318 assert ( 

1319 tokens.shape[0] == 1 

1320 ), f"If tokens are rank two, they must have shape [1, seq_len], not {tokens.shape}" 

1321 tokens = tokens[0] 

1322 if isinstance(single_token, str): 

1323 single_token = self.to_single_token(single_token) 

1324 elif isinstance(single_token, torch.Tensor): 1324 ↛ 1325line 1324 didn't jump to line 1325 because the condition on line 1324 was never true

1325 single_token = single_token.item() 

1326 indices = torch.arange(len(tokens), device=tokens.device)[tokens == single_token] 

1327 assert len(indices) > 0, "The token does not occur in the prompt" 

1328 if mode == "first": 

1329 return indices[0].item() 

1330 elif mode == "last": 1330 ↛ 1333line 1330 didn't jump to line 1333 because the condition on line 1330 was always true

1331 return indices[-1].item() 

1332 else: 

1333 raise ValueError(f"mode must be 'first' or 'last', not {mode}") 

1334 

1335 def to_single_str_token(self, int_token: int) -> str: 

1336 """Get the single token corresponding to an int in string form. 

1337 

1338 Args: 

1339 int_token: The token ID 

1340 

1341 Returns: 

1342 The token string 

1343 """ 

1344 assert isinstance(int_token, int) 

1345 token = self.to_str_tokens(torch.tensor([int_token])) 

1346 if isinstance(token, list) and len(token) == 1: 

1347 return str(token[0]) 

1348 raise AssertionError("Expected a single string token.") 

1349 

1350 def _enumerate_blocks(self) -> List[Tuple[int, Any]]: 

1351 """(index, block) over every registered block list, encoder before decoder. 

1352 

1353 Decoder-only models register a single ``blocks``, so the indices are the 

1354 plain layer indices. Encoder-decoder models register ``encoder_blocks`` 

1355 and ``decoder_blocks`` instead; those are concatenated into one index 

1356 space, matching ``HookedEncoderDecoder``'s ``chain(encoder, decoder)``. 

1357 

1358 Non-standard architectures (e.g. Raven/Huginn's ``prelude`` / 

1359 ``core_block`` / ``coda``) register block lists under other names 

1360 entirely, so ``_BLOCK_LIST_ATTRS`` alone would silently enumerate zero 

1361 blocks for them (#1791). After the known names, any other 

1362 ``nn.ModuleList`` in ``_modules`` whose items are *all* list-item 

1363 components (``is_list_item``, which ``setup_components`` sets on every 

1364 block of a stack it builds) is discovered structurally and appended in 

1365 registration order, so a new adapter's block lists are picked up 

1366 automatically without a name to add here. This is the same criterion the 

1367 named path accepts, so block types that never set 

1368 ``hook_out_is_single_residual_stream`` (T5, AltUp, T5Gemma, DeepSeek V4) 

1369 are enumerated regardless of the name they are registered under. A list 

1370 mixing blocks with other modules is skipped whole rather than partly 

1371 enumerated. 

1372 """ 

1373 pairs: List[Tuple[int, Any]] = [] 

1374 modules = self.__dict__.get("_modules") or {} 

1375 known_names = set(_BLOCK_LIST_ATTRS) 

1376 for list_name in _BLOCK_LIST_ATTRS: 

1377 block_list = modules.get(list_name) 

1378 if not isinstance(block_list, nn.ModuleList): 

1379 continue 

1380 for block in block_list: 

1381 pairs.append((len(pairs), block)) 

1382 for list_name, block_list in modules.items(): 

1383 if list_name in known_names or not isinstance(block_list, nn.ModuleList): 

1384 continue 

1385 if len(block_list) == 0 or not all( 

1386 getattr(block, "is_list_item", False) for block in block_list 

1387 ): 

1388 continue 

1389 for block in block_list: 

1390 pairs.append((len(pairs), block)) 

1391 return pairs 

1392 

1393 def _resolve_submodule_name(self, block: Any, submodule: str) -> Optional[str]: 

1394 """The block's actual name for ``submodule``. 

1395 

1396 Encoder blocks name self-attention ``attn`` while decoder blocks name it 

1397 ``self_attn``, so a caller asking for ``attn`` means "this block's 

1398 self-attention" on either side. Cross-attention is never resolved here: 

1399 ``HookedEncoderDecoder`` omits it from stacked weights, and this mirrors 

1400 that so the two stacks line up layer for layer. 

1401 """ 

1402 for candidate in _SELF_ATTENTION_NAMES.get(submodule, (submodule,)): 

1403 if candidate in block._modules: 

1404 return candidate 

1405 return None 

1406 

1407 def _rewrite_submodule_path(self, attr_path: str, submodule: str, actual: Optional[str]) -> str: 

1408 """Re-point ``attr_path``'s leading segment at the block's actual submodule.""" 

1409 if actual is None or actual == submodule: 

1410 return attr_path 

1411 if attr_path.split(".")[0] != submodule: 1411 ↛ 1412line 1411 didn't jump to line 1412 because the condition on line 1411 was never true

1412 return attr_path 

1413 return actual + attr_path[len(submodule) :] 

1414 

1415 def blocks_with(self, submodule: str) -> List[Tuple[int, "GeneralizedComponent"]]: 

1416 """Return (index, block) pairs for blocks with the named bridged submodule. 

1417 

1418 Checks _modules (not hasattr) so HF-internal attrs don't match. 

1419 Use instead of assuming blocks[0] is representative on hybrid models. 

1420 On encoder-decoder models the indices span encoder then decoder blocks, 

1421 and ``"attn"`` matches the decoder's ``self_attn`` too. 

1422 """ 

1423 return [ 

1424 (index, block) 

1425 for index, block in self._enumerate_blocks() 

1426 if self._resolve_submodule_name(block, submodule) is not None 

1427 ] 

1428 

1429 def stack_params_for( 

1430 self, submodule: str, attr_path: str, reshape_fn: Optional[Callable] = None 

1431 ) -> Tuple[List[int], torch.Tensor]: 

1432 """Stack a parameter across matching blocks only. Returns (layer_indices, tensor). 

1433 

1434 Use for hybrid models where not all blocks have the submodule. 

1435 """ 

1436 matching = self.blocks_with(submodule) 

1437 if not matching: 

1438 raise ValueError( 

1439 f"No blocks have submodule '{submodule}'. " 

1440 f"Available submodules can be checked with blocks_with()." 

1441 ) 

1442 indices: List[int] = [] 

1443 weights: List[torch.Tensor] = [] 

1444 for idx, block in matching: 

1445 resolved = self._resolve_submodule_name(block, submodule) 

1446 w = _resolve_attr_path( 

1447 block, self._rewrite_submodule_path(attr_path, submodule, resolved) 

1448 ) 

1449 if w is None: 1449 ↛ 1450line 1449 didn't jump to line 1450 because the condition on line 1449 was never true

1450 raise AttributeError( 

1451 f"blocks[{idx}].{attr_path} is None — this checkpoint has no such " 

1452 f"parameter (bias-free projection)." 

1453 ) 

1454 if reshape_fn is not None: 

1455 w = reshape_fn(w) 

1456 weights.append(w) 

1457 indices.append(idx) 

1458 return indices, torch.stack(weights, dim=0) 

1459 

1460 def _stack_block_params( 

1461 self, attr_path: str, reshape_fn: Optional[Callable] = None 

1462 ) -> torch.Tensor: 

1463 """Stack a parameter across all blocks; falls back to matching-only on hybrids. 

1464 

1465 Filters on FULL-path resolution, not the first segment: on interleaved 

1466 MoE, every block has `mlp` but only dense layers expose `mlp.W_in`, so 

1467 a first-segment filter matched everything and the sparse layer's 

1468 AttributeError killed the accessor for the whole model. 

1469 """ 

1470 first_attr = attr_path.split(".")[0] 

1471 all_blocks = self._enumerate_blocks() 

1472 matching_blocks: List[Tuple[int, torch.Tensor]] = [] 

1473 for i, block in all_blocks: 

1474 resolved = self._resolve_submodule_name(block, first_attr) 

1475 if resolved is None: 

1476 continue 

1477 try: 

1478 weight = _resolve_attr_path( 

1479 block, self._rewrite_submodule_path(attr_path, first_attr, resolved) 

1480 ) 

1481 except AttributeError: 

1482 continue 

1483 if weight is None: 

1484 # Bias-free checkpoints (e.g. qkv_bias=False) expose None here; 

1485 # stacking would raise an opaque TypeError. 

1486 raise AttributeError( 

1487 f"blocks[{i}].{attr_path} is None — this checkpoint has no " 

1488 f"such parameter (bias-free projection). Bias-free models expose no " 

1489 f"stacked {attr_path.rsplit('.', 1)[-1]}; construct zeros explicitly " 

1490 f"if your analysis needs one." 

1491 ) 

1492 matching_blocks.append((i, weight)) 

1493 

1494 if len(matching_blocks) == 0: 

1495 raise AttributeError( 

1496 f"No blocks resolve '{attr_path}'. " 

1497 f"Use bridge.blocks_with('{first_attr}') to check availability." 

1498 ) 

1499 

1500 if len(matching_blocks) < len(all_blocks): 

1501 indices = [i for i, _ in matching_blocks] 

1502 logging.warning( 

1503 "Hybrid model: only %d/%d blocks resolve '%s'. Returning stacked tensor " 

1504 "for layers %s only. Tensor index i corresponds to original layer " 

1505 "indices[i], not layer i. For explicit index mapping, use " 

1506 "bridge.stack_params_for('%s', '%s').", 

1507 len(matching_blocks), 

1508 len(all_blocks), 

1509 attr_path, 

1510 indices, 

1511 first_attr, 

1512 attr_path, 

1513 ) 

1514 

1515 weights: List[torch.Tensor] = [] 

1516 for _, weight in matching_blocks: 

1517 w = reshape_fn(weight) if reshape_fn is not None else weight 

1518 weights.append(w) 

1519 # Under a device_map split, per-block tensors live on different devices. 

1520 # torch.stack requires a common device; gather onto cfg.device (the embedding / 

1521 # input device — a natural "home" for cross-layer reductions). 

1522 if getattr(self.cfg, "n_devices", 1) > 1 and weights and self.cfg.device is not None: 

1523 target_device = torch.device(self.cfg.device) 

1524 weights = [w.to(target_device) for w in weights] 

1525 return torch.stack(weights, dim=0) 

1526 

1527 def _reshape_qkv(self, w: torch.Tensor) -> torch.Tensor: 

1528 """Reshape 2D [d_model, d_model] QKV weight to 3D [n_heads, d_model, d_head].""" 

1529 if w.shape == (self.cfg.d_model, self.cfg.d_model): 1529 ↛ 1530line 1529 didn't jump to line 1530 because the condition on line 1529 was never true

1530 d_head = self.cfg.d_model // self.cfg.n_heads 

1531 return w.reshape(self.cfg.n_heads, self.cfg.d_model, d_head) 

1532 return w 

1533 

1534 def _reshape_o(self, w: torch.Tensor) -> torch.Tensor: 

1535 """Reshape 2D [d_model, d_model] O weight to 3D [n_heads, d_head, d_model].""" 

1536 if w.shape == (self.cfg.d_model, self.cfg.d_model): 1536 ↛ 1537line 1536 didn't jump to line 1537 because the condition on line 1536 was never true

1537 d_head = self.cfg.d_model // self.cfg.n_heads 

1538 return w.reshape(self.cfg.n_heads, d_head, self.cfg.d_model) 

1539 return w 

1540 

1541 def _expand_kv_heads(self, w: torch.Tensor) -> torch.Tensor: 

1542 """Expand stacked grouped K/V weights along the head axis to n_heads. 

1543 

1544 GQA models store one K/V projection per key-value head while W_Q/W_O are 

1545 per-query-head, so weight circuits must repeat the grouped K/V up to 

1546 n_heads before factoring: query head h reads kv head 

1547 h // (n_heads // n_kv_heads), i.e. repeat_interleave — the same layout 

1548 GroupedQueryAttention.W_K/W_V expose on HookedTransformer. No-op for MHA, 

1549 where the head axes already match. 

1550 """ 

1551 if w.ndim != 4 or w.shape[1] == self.cfg.n_heads: 

1552 return w 

1553 n_kv_heads = w.shape[1] 

1554 if self.cfg.n_heads % n_kv_heads != 0: 

1555 raise ValueError( 

1556 f"Cannot expand {n_kv_heads} key-value heads to {self.cfg.n_heads} " 

1557 f"query heads: n_heads must be a multiple of n_kv_heads." 

1558 ) 

1559 return w.repeat_interleave(self.cfg.n_heads // n_kv_heads, dim=1) 

1560 

1561 @property 

1562 def W_K(self) -> torch.Tensor: 

1563 """Stack the key weights across all layers.""" 

1564 return self._stack_block_params("attn.W_K", self._reshape_qkv) 

1565 

1566 @property 

1567 def W_Q(self) -> torch.Tensor: 

1568 """Stack the query weights across all layers.""" 

1569 return self._stack_block_params("attn.W_Q", self._reshape_qkv) 

1570 

1571 @property 

1572 def W_V(self) -> torch.Tensor: 

1573 """Stack the value weights across all layers.""" 

1574 return self._stack_block_params("attn.W_V", self._reshape_qkv) 

1575 

1576 @property 

1577 def W_O(self) -> torch.Tensor: 

1578 """Stack the attn output weights across all layers.""" 

1579 return self._stack_block_params("attn.W_O", self._reshape_o) 

1580 

1581 @property 

1582 def W_in(self) -> torch.Tensor: 

1583 """Stack the MLP input weights across all layers.""" 

1584 return self._stack_block_params("mlp.W_in") 

1585 

1586 @property 

1587 def W_gate(self) -> Union[torch.Tensor, None]: 

1588 """Stack the MLP gate weights across all layers (gated MLPs only).""" 

1589 if getattr(self.cfg, "gated_mlp", False): 

1590 return self._stack_block_params("mlp.W_gate") 

1591 return None 

1592 

1593 @property 

1594 def W_out(self) -> torch.Tensor: 

1595 """Stack the MLP output weights across all layers.""" 

1596 return self._stack_block_params("mlp.W_out") 

1597 

1598 @property 

1599 def b_K(self) -> torch.Tensor: 

1600 """Stack the key biases across all layers.""" 

1601 return self._stack_block_params("attn.b_K") 

1602 

1603 @property 

1604 def b_Q(self) -> torch.Tensor: 

1605 """Stack the query biases across all layers.""" 

1606 return self._stack_block_params("attn.b_Q") 

1607 

1608 @property 

1609 def b_V(self) -> torch.Tensor: 

1610 """Stack the value biases across all layers.""" 

1611 return self._stack_block_params("attn.b_V") 

1612 

1613 @property 

1614 def b_O(self) -> torch.Tensor: 

1615 """Stack the attn output biases across all layers.""" 

1616 return self._stack_block_params("attn.b_O") 

1617 

1618 @property 

1619 def b_in(self) -> torch.Tensor: 

1620 """Stack the MLP input biases across all layers.""" 

1621 return self._stack_block_params("mlp.b_in") 

1622 

1623 @property 

1624 def b_out(self) -> torch.Tensor: 

1625 """Stack the MLP output biases across all layers.""" 

1626 return self._stack_block_params("mlp.b_out") 

1627 

1628 @property 

1629 def W_U(self) -> torch.Tensor: 

1630 """Unembedding matrix (d_model, d_vocab). Maps residual stream to logits.""" 

1631 return self.unembed.W_U 

1632 

1633 @property 

1634 def b_U(self) -> torch.Tensor: 

1635 """Unembedding bias (d_vocab).""" 

1636 return self.unembed.b_U 

1637 

1638 @property 

1639 def W_E(self) -> torch.Tensor: 

1640 """Token embedding matrix (d_vocab, d_model).""" 

1641 return self.embed.W_E 

1642 

1643 @property 

1644 def W_pos(self) -> torch.Tensor: 

1645 """Positional embedding matrix (n_ctx, d_model). 

1646 

1647 Only defined for models with learned absolute positional embeddings; 

1648 rotary/ALiBi models have no such matrix. Reflects the weights as 

1649 currently processed, like every other accessor — equal to 

1650 ``HookedTransformer.W_pos`` only under matching processing 

1651 (``from_pretrained_no_processing`` vs the bridge default, or 

1652 compatibility mode vs HT defaults). 

1653 """ 

1654 pos_embed = getattr(self, "pos_embed", None) 

1655 pos_type = getattr(self.cfg, "positional_embedding_type", "unknown") 

1656 if pos_embed is None or not hasattr(pos_embed, "W_pos"): 

1657 raise AttributeError( 

1658 "W_pos is only defined for models with a learned absolute positional " 

1659 f"embedding component; this model exposes none " 

1660 f"(positional_embedding_type={pos_type!r})." 

1661 ) 

1662 w = pos_embed.W_pos 

1663 # T5-family adapters map pos_embed to the relative attention bias — a 

1664 # [num_buckets, n_heads] table, not a positional matrix. The legacy 

1665 # accessor refused these models; keep refusing rather than hand back a 

1666 # wrong-shaped tensor. 

1667 if w.ndim != 2 or w.shape[-1] != self.cfg.d_model: 

1668 raise AttributeError( 

1669 "W_pos is only defined for learned absolute positional embeddings; " 

1670 f"this model's pos_embed holds a {tuple(w.shape)} table " 

1671 f"(positional_embedding_type={pos_type!r})." 

1672 ) 

1673 # OPT/BART-family checkpoints allocate max_position_embeddings + 2 rows 

1674 # (positions are offset by 2 in HF's forward). HookedTransformer's 

1675 # converters slice those rows off; mirror that so shapes and values agree. 

1676 if w.shape[0] == self.cfg.n_ctx + 2: 

1677 return w[2:] 

1678 return w 

1679 

1680 @property 

1681 def W_E_pos(self) -> torch.Tensor: 

1682 """Concatenated ``[W_E; W_pos]`` (d_vocab + n_ctx, d_model). 

1683 

1684 A full (overcomplete) basis of the input space, used for full QK/OV 

1685 circuits. Mirrors ``HookedTransformer.W_E_pos``. 

1686 """ 

1687 return torch.cat([self.W_E, self.W_pos], dim=0) 

1688 

1689 @property 

1690 def QK(self): 

1691 """QK circuit. On hybrids, returns attn layers only (with warning). See QK_for_attn_layers().""" 

1692 return FactoredMatrix(self.W_Q, self._expand_kv_heads(self.W_K).transpose(-2, -1)) 

1693 

1694 @property 

1695 def OV(self): 

1696 """OV circuit. On hybrids, returns attn layers only (with warning). See OV_for_attn_layers().""" 

1697 return FactoredMatrix(self._expand_kv_heads(self.W_V), self.W_O) 

1698 

1699 def QK_for_attn_layers(self) -> Tuple[List[int], FactoredMatrix]: 

1700 """QK circuit for attention layers only. Returns (layer_indices, FactoredMatrix).""" 

1701 q_indices, W_Q = self.stack_params_for("attn", "attn.W_Q", self._reshape_qkv) 

1702 _, W_K = self.stack_params_for("attn", "attn.W_K", self._reshape_qkv) 

1703 return q_indices, FactoredMatrix(W_Q, self._expand_kv_heads(W_K).transpose(-2, -1)) 

1704 

1705 def OV_for_attn_layers(self) -> Tuple[List[int], FactoredMatrix]: 

1706 """OV circuit for attention layers only. Returns (layer_indices, FactoredMatrix).""" 

1707 v_indices, W_V = self.stack_params_for("attn", "attn.W_V", self._reshape_qkv) 

1708 _, W_O = self.stack_params_for("attn", "attn.W_O", self._reshape_o) 

1709 return v_indices, FactoredMatrix(self._expand_kv_heads(W_V), W_O) 

1710 

1711 # ------------------------------------------------------------------ 

1712 # Mechanistic interpretability analysis methods 

1713 # ------------------------------------------------------------------ 

1714 

1715 def tokens_to_residual_directions( 

1716 self, 

1717 tokens: Union[str, int, torch.Tensor], 

1718 ) -> torch.Tensor: 

1719 """Map tokens to their unembedding vectors (residual stream directions). 

1720 

1721 Returns the columns of W_U corresponding to the given tokens — i.e. the 

1722 directions in the residual stream that the model dots with to produce the 

1723 logit for each token. 

1724 

1725 WARNING: If you use this without folding in LayerNorm (compatibility mode), 

1726 the results will be misleading because LN weights change the unembed map. 

1727 

1728 Args: 

1729 tokens: A single token (str, int, or scalar tensor), a 1-D tensor of 

1730 token IDs, or a 2-D batch of token IDs. 

1731 

1732 Returns: 

1733 Tensor of unembedding vectors with shape matching the input token shape 

1734 plus a trailing d_model dimension. 

1735 """ 

1736 if isinstance(tokens, torch.Tensor) and tokens.numel() > 1: 

1737 residual_directions = self.W_U[:, tokens] 

1738 residual_directions = einops.rearrange( 

1739 residual_directions, "d_model ... -> ... d_model" 

1740 ) 

1741 return residual_directions 

1742 else: 

1743 if isinstance(tokens, str): 

1744 token = self.to_single_token(tokens) 

1745 elif isinstance(tokens, int): 

1746 token = tokens 

1747 elif isinstance(tokens, torch.Tensor) and tokens.numel() == 1: 1747 ↛ 1750line 1747 didn't jump to line 1750 because the condition on line 1747 was always true

1748 token = int(tokens.item()) 

1749 else: 

1750 raise ValueError(f"Invalid token type: {type(tokens)}") 

1751 residual_direction = self.W_U[:, token] 

1752 return residual_direction 

1753 

1754 # Variant → attr paths for the output bias that feeds the residual stream. 

1755 _VARIANT_OUTPUT_BIAS_ATTRS: Dict[str, tuple] = { 

1756 "attn": ("b_O",), 

1757 "linear_attn": ("out_proj.bias",), 

1758 "mamba": ("out_proj.bias",), 

1759 "mixer": ("out_proj.bias",), 

1760 "ssm": ("out_proj.bias",), 

1761 } 

1762 

1763 def _get_block_variant_bias(self, block: "GeneralizedComponent") -> Optional[torch.Tensor]: 

1764 """Return the output bias from this block's variant submodule, or None.""" 

1765 for name in VARIANT_SUBMODULE_NAMES: 

1766 if name not in block._modules: 

1767 continue 

1768 variant = block._modules[name] 

1769 for attr_path in self._VARIANT_OUTPUT_BIAS_ATTRS.get(name, ()): 

1770 obj = variant 

1771 try: 

1772 for attr in attr_path.split("."): 

1773 obj = getattr(obj, attr) 

1774 except AttributeError: 

1775 continue 

1776 if obj is not None and isinstance(obj, torch.Tensor): 

1777 return obj 

1778 return None 

1779 

1780 def accumulated_bias( 

1781 self, 

1782 layer: int, 

1783 mlp_input: bool = False, 

1784 include_mlp_biases: bool = True, 

1785 ) -> torch.Tensor: 

1786 """Sum of variant + MLP output biases through the residual stream up to `layer`. 

1787 

1788 Includes all layer types (attn, SSM, linear-attn). Set mlp_input=True 

1789 to target ``layer``'s MLP input, adding its variant bias unless the block is parallel. 

1790 """ 

1791 accumulated = torch.zeros(self.cfg.d_model, device=self.cfg.device) 

1792 for i in range(layer): 

1793 block = self.blocks[i] 

1794 scale = getattr(block, "residual_contribution_scale", 1.0) 

1795 b_O = self._get_block_variant_bias(block) 

1796 if b_O is not None: 

1797 accumulated = accumulated + b_O.to(accumulated.device) * scale 

1798 if include_mlp_biases and "mlp" in block._modules: 

1799 b_out = getattr(block.mlp, "b_out", None) 

1800 if b_out is not None: 

1801 accumulated = accumulated + b_out.to(accumulated.device) * scale 

1802 if mlp_input: 

1803 assert layer < self.cfg.n_layers, "Cannot include attn_bias from beyond the final layer" 

1804 block = self.blocks[layer] 

1805 if getattr(block, "mlp_input_includes_attn", True): 

1806 scale = getattr(block, "residual_contribution_scale", 1.0) 

1807 b_O = self._get_block_variant_bias(block) 

1808 if b_O is not None: 

1809 accumulated = accumulated + b_O.to(accumulated.device) * scale 

1810 return accumulated 

1811 

1812 def all_composition_scores(self, mode: str) -> CompositionScores: 

1813 """Composition scores for all attention head pairs. Returns CompositionScores. 

1814 

1815 See https://transformer-circuits.pub/2021/framework/index.html 

1816 On hybrid models, only attention layers are included; layer_indices 

1817 maps tensor position i to original layer number. 

1818 """ 

1819 self._reject_encoder_decoder_composition() 

1820 attn_blocks = self.blocks_with("attn") 

1821 if not attn_blocks: 1821 ↛ 1822line 1821 didn't jump to line 1822 because the condition on line 1821 was never true

1822 raise ValueError("No attention layers found — cannot compute composition scores.") 

1823 

1824 indices = [idx for idx, _ in attn_blocks] 

1825 blocks_list = [block for _, block in attn_blocks] 

1826 

1827 def _stack(attr_path: str, reshape_fn: Optional[Callable] = None) -> torch.Tensor: 

1828 weights: List[torch.Tensor] = [] 

1829 for block_idx, block in zip(indices, blocks_list): 

1830 w = _resolve_attr_path(block, attr_path) 

1831 if w is None: 1831 ↛ 1832line 1831 didn't jump to line 1832 because the condition on line 1831 was never true

1832 raise AttributeError( 

1833 f"blocks[{block_idx}].{attr_path} is None — this checkpoint has " 

1834 f"no such parameter (bias-free projection)." 

1835 ) 

1836 if reshape_fn is not None: 1836 ↛ 1838line 1836 didn't jump to line 1838 because the condition on line 1836 was always true

1837 w = reshape_fn(w) 

1838 weights.append(w) 

1839 # See _stack_block_params: gather per-block tensors onto cfg.device when split. 

1840 if getattr(self.cfg, "n_devices", 1) > 1 and weights and self.cfg.device is not None: 1840 ↛ 1841line 1840 didn't jump to line 1841 because the condition on line 1840 was never true

1841 target_device = torch.device(self.cfg.device) 

1842 weights = [w.to(target_device) for w in weights] 

1843 return torch.stack(weights, dim=0) 

1844 

1845 W_V = self._expand_kv_heads(_stack("attn.W_V", self._reshape_qkv)) 

1846 W_O = _stack("attn.W_O", self._reshape_o) 

1847 left = FactoredMatrix(W_V, W_O) 

1848 

1849 if mode == "Q": 

1850 W_Q = _stack("attn.W_Q", self._reshape_qkv) 

1851 W_K = self._expand_kv_heads(_stack("attn.W_K", self._reshape_qkv)) 

1852 right = FactoredMatrix(W_Q, W_K.transpose(-2, -1)) 

1853 elif mode == "K": 

1854 W_Q = _stack("attn.W_Q", self._reshape_qkv) 

1855 W_K = self._expand_kv_heads(_stack("attn.W_K", self._reshape_qkv)) 

1856 right = FactoredMatrix(W_Q, W_K.transpose(-2, -1)).T 

1857 elif mode == "V": 

1858 right = left 

1859 else: 

1860 raise ValueError(f"mode must be one of ['Q', 'K', 'V'] not {mode}") 

1861 

1862 scores = utils.composition_scores(left, right, broadcast_dims=True) 

1863 n_attn = len(indices) 

1864 idx_tensor = torch.arange(n_attn, device=self.cfg.device) 

1865 mask = idx_tensor[:, None, None, None] < idx_tensor[None, None, :, None] 

1866 scores = torch.where(mask, scores, torch.zeros_like(scores)) 

1867 

1868 labels = [f"L{l}H{h}" for l in indices for h in range(self.cfg.n_heads)] 

1869 return CompositionScores(scores=scores, layer_indices=indices, head_labels=labels) 

1870 

1871 def _reject_encoder_decoder_composition(self) -> None: 

1872 """Composition scores live in one residual stream; enc-dec models have two.""" 

1873 if any(hasattr(self, a) for a in ("encoder_blocks", "decoder_blocks")): 

1874 raise NotImplementedError( 

1875 "Composition scores are not defined across an encoder-decoder " 

1876 "model's two residual streams (HookedTransformer never " 

1877 "supported them there either)." 

1878 ) 

1879 

1880 def composition_layer_indices(self) -> List[int]: 

1881 """Original layer indices for attention layers (maps composition score positions).""" 

1882 self._reject_encoder_decoder_composition() 

1883 return [idx for idx, _ in self.blocks_with("attn")] 

1884 

1885 def block_hooks(self, layer_idx: int) -> List[str]: 

1886 """Sorted hook names available on block `layer_idx` (block-relative paths).""" 

1887 prefix = f"blocks.{layer_idx}." 

1888 return sorted(name[len(prefix) :] for name in self.hook_dict if name.startswith(prefix)) 

1889 

1890 def block_submodules(self, layer_idx: int) -> List[str]: 

1891 """Return bridged submodule names on block `layer_idx`.""" 

1892 block = self.blocks[layer_idx] 

1893 return [name for name in block._modules if name not in _BLOCK_INTERNAL_MODULES] 

1894 

1895 def layer_types(self) -> List[str]: 

1896 """Per-block type labels, e.g. ["attn+mlp", "ssm+mlp", ...]. Deterministic order.""" 

1897 types = [] 

1898 for block in self.blocks: 

1899 variants = [n for n in VARIANT_SUBMODULE_NAMES if n in block._modules] 

1900 universals = sorted( 

1901 n 

1902 for n in block._modules 

1903 if n not in _VARIANT_SUBMODULE_SET 

1904 and n not in _BLOCK_INTERNAL_MODULES 

1905 and not n.startswith(_NORM_PREFIXES) 

1906 ) 

1907 parts = variants + universals 

1908 types.append("+".join(parts) if parts else "unknown") 

1909 return types 

1910 

1911 @property 

1912 def all_head_labels(self) -> list[str]: 

1913 """Human-readable labels for all attention heads, e.g. ['L0H0', 'L0H1', ...]. 

1914 

1915 Encoder-decoder models use ``HookedEncoderDecoder``'s ``EL{l}H{h}`` / 

1916 ``DL{l}H{h}`` scheme so encoder and decoder heads stay distinguishable; 

1917 a plain ``L{l}H{h}`` list would name only half of them. 

1918 """ 

1919 encoder_blocks = self._modules.get("encoder_blocks") 

1920 decoder_blocks = self._modules.get("decoder_blocks") 

1921 if isinstance(encoder_blocks, nn.ModuleList) and isinstance(decoder_blocks, nn.ModuleList): 

1922 heads = range(self.cfg.n_heads) 

1923 return [f"EL{l}H{h}" for l in range(len(encoder_blocks)) for h in heads] + [ 

1924 f"DL{l}H{h}" for l in range(len(decoder_blocks)) for h in heads 

1925 ] 

1926 return [f"L{l}H{h}" for l in range(self.cfg.n_layers) for h in range(self.cfg.n_heads)] 

1927 

1928 @property 

1929 def attn_head_labels(self) -> list[str]: 

1930 """Head labels for attention layers only — matches all_composition_scores() dims.""" 

1931 self._reject_encoder_decoder_composition() 

1932 return [ 

1933 f"L{l}H{h}" for l in self.composition_layer_indices() for h in range(self.cfg.n_heads) 

1934 ] 

1935 

1936 def parameters(self, recurse: bool = True) -> Iterator[nn.Parameter]: 

1937 """Returns parameters following standard PyTorch semantics. 

1938 

1939 This method delegates to the underlying HuggingFace model's parameters(). 

1940 For TransformerLens-style parameter generator, use tl_parameters() instead. 

1941 

1942 Args: 

1943 recurse: If True, yields parameters of this module and all submodules 

1944 

1945 Returns: 

1946 Iterator of nn.Parameter objects 

1947 """ 

1948 return self.original_model.parameters(recurse=recurse) 

1949 

1950 def named_parameters( 

1951 self, prefix: str = "", recurse: bool = True, remove_duplicate: bool = True 

1952 ) -> Iterator[tuple[str, nn.Parameter]]: 

1953 """Returns named parameters following standard PyTorch semantics. 

1954 

1955 This method delegates to the underlying HuggingFace model's named_parameters(). 

1956 For TransformerLens-style generator, use tl_named_parameters() instead. 

1957 

1958 Args: 

1959 prefix: Prefix to prepend to all parameter names 

1960 recurse: If True, yields parameters of this module and all submodules 

1961 remove_duplicate: If True, removes duplicate parameters 

1962 

1963 Returns: 

1964 Iterator of (name, parameter) tuples 

1965 """ 

1966 return self.original_model.named_parameters(prefix, recurse, remove_duplicate) 

1967 

1968 def tl_parameters(self) -> dict[str, torch.Tensor]: 

1969 """Returns TransformerLens-style parameter dictionary. 

1970 

1971 Parameter names follow TransformerLens conventions (e.g., 'blocks.0.attn.W_Q') and may 

1972 include processed weights (non-leaf tensors). This format is expected by SVDInterpreter 

1973 among other analysis tools. 

1974 

1975 Returns: 

1976 Dictionary mapping TransformerLens parameter names to tensors 

1977 

1978 Example: 

1979 >>> bridge = TransformerBridge.boot_transformers("gpt2") 

1980 >>> tl_params = bridge.tl_parameters() 

1981 >>> W_Q = tl_params["blocks.0.attn.W_Q"] # Shape: [n_heads, d_model, d_head] 

1982 """ 

1983 return self.get_params() 

1984 

1985 def tl_named_parameters(self) -> Iterator[tuple[str, torch.Tensor]]: 

1986 """Returns iterator of TransformerLens-style named parameters. 

1987 

1988 This provides the same parameters as tl_parameters() but as an iterator 

1989 for consistency with PyTorch's named_parameters() API pattern. 

1990 

1991 Returns: 

1992 Iterator of (name, tensor) tuples with TransformerLens naming conventions 

1993 

1994 Example: 

1995 >>> bridge = TransformerBridge.boot_transformers("gpt2") 

1996 >>> for name, param in bridge.tl_named_parameters(): 

1997 ... if "attn.W_Q" in name: 

1998 ... print(f"{name}: {param.shape}") # doctest: +ELLIPSIS 

1999 blocks.0.attn.W_Q: torch.Size([12, 768, 64]) 

2000 ... 

2001 """ 

2002 return iter(self.get_params().items()) 

2003 

2004 def input_to_embed( 

2005 self, 

2006 input: Union[str, List[str], torch.Tensor], 

2007 prepend_bos: Optional[bool] = None, 

2008 padding_side: Optional[str] = None, 

2009 attention_mask: Optional[torch.Tensor] = None, 

2010 ) -> Tuple[torch.Tensor, torch.Tensor, None, Optional[torch.Tensor]]: 

2011 """Convert input to the residual stream entering block 0 (``resid_pre[0]``). 

2012 

2013 Bridge analog of :meth:`HookedTransformer.input_to_embed`. Returns 

2014 ``(residual, tokens, shortformer_pos_embed, attention_mask)``; feed the 

2015 residual to ``forward(..., start_at_layer=0)`` to resume the pass. 

2016 

2017 ``shortformer_pos_embed`` is always ``None``: for the models the bridge 

2018 supports the residual already carries positional information, so there is 

2019 no separate positional stream to return. 

2020 """ 

2021 if isinstance(input, (str, list)): 

2022 assert self.tokenizer is not None, "Must provide a tokenizer for string input." 

2023 tokens = self.to_tokens(input, prepend_bos=prepend_bos, padding_side=padding_side) 

2024 else: 

2025 tokens = input 

2026 if isinstance(tokens, torch.Tensor) and tokens.ndim == 1: 2026 ↛ 2027line 2026 didn't jump to line 2027 because the condition on line 2026 was never true

2027 tokens = tokens.unsqueeze(0) 

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

2029 attention_mask is None 

2030 and self.tokenizer is not None 

2031 and self.tokenizer.padding_side == "left" 

2032 ): 

2033 _prepend = self.cfg.default_prepend_bos if prepend_bos is None else prepend_bos 

2034 attention_mask = utils.get_attention_mask(self.tokenizer, tokens, _prepend) 

2035 residual = self.forward(tokens, stop_at_layer=0, attention_mask=attention_mask) 

2036 return residual, tokens, None, attention_mask 

2037 

2038 def _accepts_derived_position_ids(self) -> bool: 

2039 """Whether it is safe to hand the wrapped model a mask-derived ``position_ids``. 

2040 

2041 Two families of model must be left alone, so the injection below is 

2042 gated on the target the same way ``output_attentions`` is in 

2043 :meth:`BridgeCore.run_with_cache`: 

2044 

2045 * **Fixed-signature models.** Remote-code forwards such as 

2046 ``LLaDAModelLM.forward`` take neither ``position_ids`` nor 

2047 ``**kwargs``, so passing it raises ``TypeError`` where the model 

2048 previously returned logits. 

2049 * **Models that own their position derivation.** mRoPE architectures 

2050 (Qwen2-VL, Qwen2.5-VL, Qwen3-VL, GLM-4V) build a 3-D temporal / 

2051 height / width index in ``get_rope_index``, and only while 

2052 ``position_ids is None``; a supplied 2-D tensor is silently expanded 

2053 across all three streams instead. Their derivation already scatters 

2054 positions onto attended slots only, so it handles left padding 

2055 correctly on its own and needs no help from us. 

2056 * **Mask-consuming positional embeddings.** OPT's 

2057 ``OPTLearnedPositionalEmbedding.forward`` takes the mask and derives 

2058 the same positions we would, so injection buys nothing — but it does 

2059 replace the model's own padding-slot convention with ours, which 

2060 shows up as a whole-tensor diff. 

2061 

2062 Non-torch drivers (vLLM, Inspect) expose no module to introspect and 

2063 manage positions internally, so they are excluded as well. 

2064 """ 

2065 underlying = getattr(self._driver, "underlying_model", None) 

2066 if underlying is None: 

2067 return False 

2068 

2069 cached = self.__dict__.get("_derived_position_ids_ok") 

2070 if cached is not None and cached[0] is underlying: 

2071 return bool(cached[1]) 

2072 

2073 accepts = accepts_mask_derived_position_ids(underlying) 

2074 self.__dict__["_derived_position_ids_ok"] = (underlying, accepts) 

2075 return accepts 

2076 

2077 @staticmethod 

2078 def _seq2seq_loss( 

2079 logits: torch.Tensor, 

2080 labels: torch.Tensor, 

2081 native_loss: Any, 

2082 *, 

2083 per_token: bool, 

2084 ) -> torch.Tensor: 

2085 """Return encoder-decoder loss without the causal LM token shift.""" 

2086 if labels.device != logits.device: 2086 ↛ 2087line 2086 didn't jump to line 2087 because the condition on line 2086 was never true

2087 labels = labels.to(logits.device) 

2088 if labels.shape != logits.shape[:-1]: 2088 ↛ 2089line 2088 didn't jump to line 2089 because the condition on line 2088 was never true

2089 raise ValueError( 

2090 "seq2seq labels must match the decoder logits batch and position " 

2091 f"dimensions, got labels {tuple(labels.shape)} and logits " 

2092 f"{tuple(logits.shape)}" 

2093 ) 

2094 if not per_token and isinstance(native_loss, torch.Tensor): 

2095 return native_loss 

2096 

2097 losses = F.cross_entropy( 

2098 logits.flatten(0, 1), 

2099 labels.flatten(), 

2100 reduction="none" if per_token else "mean", 

2101 ignore_index=-100, 

2102 ) 

2103 return losses.view_as(labels) if per_token else losses 

2104 

2105 def _finalize_seq2seq_return( 

2106 self, 

2107 return_type: str, 

2108 logits: torch.Tensor, 

2109 labels: torch.Tensor, 

2110 native_output: Any, 

2111 *, 

2112 loss_per_token: bool, 

2113 ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]: 

2114 loss = self._seq2seq_loss( 

2115 logits, 

2116 labels, 

2117 getattr(native_output, "loss", None), 

2118 per_token=loss_per_token, 

2119 ) 

2120 return (logits, loss) if return_type == "both" else loss 

2121 

2122 def forward( 

2123 self, 

2124 input: Union[str, List[str], torch.Tensor], 

2125 return_type: Optional[str] = "logits", 

2126 loss_per_token: bool = False, 

2127 prepend_bos: Optional[bool] = None, 

2128 padding_side: Optional[str] = None, 

2129 attention_mask: Optional[torch.Tensor] = None, 

2130 labels: Optional[torch.Tensor] = None, 

2131 start_at_layer: Optional[int] = None, 

2132 stop_at_layer: Optional[int] = None, 

2133 pixel_values: Optional[torch.Tensor] = None, 

2134 input_values: Optional[torch.Tensor] = None, 

2135 past_key_values: Optional[Any] = None, 

2136 **kwargs, 

2137 ) -> Any: 

2138 """Forward pass through the model. 

2139 

2140 Args: 

2141 input: Input to the model 

2142 return_type: Type of output to return ('logits', 'loss', 'both', 'predictions', 

2143 'logits_and_cache', None). 'logits_and_cache' returns 

2144 ``(logits, past_key_values)`` — the HuggingFace cache after this step, to 

2145 feed back on the next call for incremental decoding. 

2146 loss_per_token: Whether to return loss per token 

2147 prepend_bos: Whether to prepend BOS token 

2148 padding_side: Which side to pad on when tokenizing a list of strings. For a 

2149 token tensor, the side it was already padded on: the attention mask is 

2150 then read off the pad token. Pass ``attention_mask`` instead when the pad 

2151 id also occurs as a real token. 

2152 labels: Explicit language-model targets. Encoder-decoder models require 

2153 labels for loss; decoder-only models fall back to input IDs when omitted. 

2154 past_key_values: HuggingFace KV cache from a prior ``use_cache=True`` step 

2155 (e.g. the second element of a ``return_type='logits_and_cache'`` return). 

2156 When provided, KV caching is enabled automatically and only the new 

2157 tokens' keys/values are computed; HF derives the position offset from the 

2158 cache length. This is the bridge's manual KV-cache entry point — it uses 

2159 HF's native cache object rather than a TransformerLens cache. 

2160 start_at_layer: Resume the forward from block ``k``, treating ``input`` as 

2161 the residual-stream tensor ``[batch, pos, d_model]`` entering that block 

2162 (mirrors HookedTransformer). Blocks 0..k-1 still execute internally (their 

2163 output is discarded when block k swaps in the residual) but are excluded 

2164 from ``run_with_cache`` output. Requires an HF model that accepts 

2165 ``inputs_embeds``; only supported on the standard ``blocks`` stack. 

2166 stop_at_layer: Return the residual stream entering this block instead of the 

2167 model output. ``n_layers`` returns what leaves the last block, before the 

2168 final norm and unembed, and a value outside ``[-n_layers, n_layers]`` 

2169 raises ``ValueError``. Only supported on the 

2170 standard ``blocks`` stack; architectures that register no ``blocks`` 

2171 (e.g. Raven's ``prelude``/``core_block``/``coda``) raise 

2172 ``NotImplementedError`` rather than running to completion. 

2173 pixel_values: Optional image tensor for multimodal models (e.g., LLaVA, Gemma3) 

2174 and vision models (eg. ViT, DeiT). 

2175 The tensor is passed directly to the underlying HuggingFace model. 

2176 Only valid when cfg.is_multimodal is True or cfg.is_visual_model is True. 

2177 input_values: Optional audio waveform tensor for audio models (e.g., HuBERT). 

2178 The tensor is passed directly to the underlying HuggingFace model. 

2179 Only valid when cfg.is_audio_model is True. Audio seq2seq models 

2180 (cfg.is_audio_seq2seq, e.g. Whisper) instead take their features as 

2181 ``input`` and require ``decoder_input`` (decoder token ids) or ``labels``, 

2182 with one row per clip or a single row shared by every clip. 

2183 **kwargs: Additional arguments passed to the model. Hook/cache helper 

2184 options belong to run_with_hooks, run_with_cache or hooks, not forward; 

2185 misplaced options and singular fwd_hook/bwd_hook raise TypeError. 

2186 

2187 Returns: 

2188 Model output based on return_type 

2189 """ 

2190 

2191 _validate_execution_kwargs(kwargs, "forward") 

2192 underlying_model = getattr(getattr(self, "_driver", None), "underlying_model", None) 

2193 model_config = getattr(underlying_model, "config", None) 

2194 is_encoder_decoder = bool(getattr(model_config, "is_encoder_decoder", False)) 

2195 if return_type in ("loss", "both"): 

2196 if is_encoder_decoder and labels is None: 

2197 raise ValueError( 

2198 "labels are required for seq2seq return_type='loss' or 'both'; " 

2199 "encoder input_ids are not decoder targets" 

2200 ) 

2201 if ( 

2202 return_type in ("loss", "both") 

2203 and not is_encoder_decoder 

2204 and not self.adapter.supports_causal_loss 

2205 ): 

2206 architecture = self.cfg.architecture or type(self.adapter).__name__ 

2207 raise NotImplementedError( 

2208 f"{architecture} does not support TransformerBridge's shifted causal " 

2209 "loss. Request return_type='logits' and compute the architecture-specific " 

2210 "masked-token objective explicitly." 

2211 ) 

2212 

2213 if labels is not None: 

2214 kwargs["labels"] = labels 

2215 

2216 # Resolved before start_at_layer is armed, so a bad value leaves nothing to tear down. 

2217 effective_stop_at_layer: Optional[int] = None 

2218 if stop_at_layer is not None: 

2219 if not self._has_registered_blocks(): 

2220 raise NotImplementedError( 

2221 "stop_at_layer requires a 'blocks' stack; this architecture " 

2222 "does not register one." 

2223 ) 

2224 effective_stop_at_layer = self._resolve_stop_at_layer(stop_at_layer, len(self.blocks)) 

2225 if start_at_layer is not None: 

2226 input = self._setup_start_at_layer(input, start_at_layer) 

2227 if effective_stop_at_layer is not None: 

2228 for block in self.blocks: 

2229 block._stop_at_layer_idx = effective_stop_at_layer 

2230 

2231 # Map HookedEncoderDecoder-style kwargs to HF-compatible names 

2232 if "decoder_input" in kwargs: 

2233 kwargs["decoder_input_ids"] = kwargs.pop("decoder_input") 

2234 if "one_zero_attention_mask" in kwargs: 2234 ↛ 2235line 2234 didn't jump to line 2235 because the condition on line 2234 was never true

2235 if attention_mask is None: 

2236 attention_mask = kwargs.pop("one_zero_attention_mask") 

2237 else: 

2238 kwargs.pop("one_zero_attention_mask") 

2239 

2240 # Detect batched list input that may need padding. Forward follows the 

2241 # requested/tokenizer side; generation separately forces left-padding. 

2242 _is_batched_list = ( 

2243 isinstance(input, list) 

2244 and len(input) > 1 

2245 and not getattr(self.cfg, "is_audio_model", False) 

2246 and not getattr(self.cfg, "is_visual_model", False) 

2247 ) 

2248 _resolved_padding_side = padding_side 

2249 if _resolved_padding_side is None and self.tokenizer is not None: 

2250 _resolved_padding_side = getattr(self.tokenizer, "padding_side", "right") 

2251 

2252 final_stop_handle: Optional[RemovableHandle] = None 

2253 try: 

2254 # Blocks stop on entry and nothing follows the last one, so that stop fires as it 

2255 # exits. On the module rather than hook_out: raising in a HookPoint's forward hook 

2256 # would cut off its backward hooks, and not every block's output reaches hook_out. 

2257 if effective_stop_at_layer is not None and effective_stop_at_layer == len(self.blocks): 

2258 final_stop_handle = self.blocks[-1].register_forward_hook(_stop_on_block_exit) 

2259 if isinstance(input, (str, list)): 

2260 if getattr(self.cfg, "is_audio_seq2seq", False): 

2261 raise ValueError( 

2262 "Audio seq2seq models take the audio features tensor as `input` " 

2263 f"(passed to the model as {self.adapter.audio_input_name!r}); " 

2264 "decoder token ids go in decoder_input." 

2265 ) 

2266 if getattr(self.cfg, "is_audio_model", False): 2266 ↛ 2267line 2266 didn't jump to line 2267 because the condition on line 2266 was never true

2267 raise ValueError( 

2268 "Audio models require tensor input (raw waveform), not text. " 

2269 "Pass a torch.Tensor or use the input_values parameter." 

2270 ) 

2271 if getattr(self.cfg, "is_visual_model", False): 2271 ↛ 2272line 2271 didn't jump to line 2272 because the condition on line 2271 was never true

2272 raise ValueError( 

2273 "Visual models require tensor input (pixel values), not text. " 

2274 "Pass a torch.Tensor or use the pixel_values parameter." 

2275 ) 

2276 input_ids = self.to_tokens( 

2277 input, prepend_bos=prepend_bos, padding_side=padding_side 

2278 ) 

2279 else: 

2280 input_ids = input 

2281 # Promote 1D integer token tensors to 2D [batch=1, seq] to match 

2282 # HookedTransformer's contract. Float tensors (inputs_embeds, 

2283 # audio waveforms) are passed through unchanged. 

2284 if ( 

2285 isinstance(input_ids, torch.Tensor) 

2286 and input_ids.ndim == 1 

2287 and not input_ids.is_floating_point() 

2288 ): 

2289 input_ids = input_ids.unsqueeze(0) 

2290 

2291 # Detect inputs_embeds: if the tensor is floating point, it's pre-computed 

2292 # embeddings (e.g., from multimodal models) rather than token IDs. 

2293 _is_inputs_embeds = ( 

2294 isinstance(input_ids, torch.Tensor) and input_ids.is_floating_point() 

2295 ) 

2296 

2297 # A token tensor carries no record of its padding. As in generate(), an 

2298 # explicit padding_side says how it was padded, so the mask is read off 

2299 # the pad token; without one the tensor is used as given. 

2300 _is_padded_tokens = ( 

2301 padding_side is not None 

2302 and isinstance(input, torch.Tensor) 

2303 and not _is_inputs_embeds 

2304 ) 

2305 

2306 # Left padding needs a mask and corrected positions. Right padding is 

2307 # harmless for causal real-token positions and remains unmasked to 

2308 # match HookedTransformer; bidirectional/encoder inputs still need it. 

2309 _layout_needs_mask = ( 

2310 _resolved_padding_side == "left" 

2311 or is_encoder_decoder 

2312 or not self.adapter.supports_causal_loss 

2313 or getattr(self.cfg, "attention_dir", "causal") != "causal" 

2314 ) 

2315 # The loss is the exception: it must skip the transitions into the pads 

2316 # whichever side they are on, for strings and token input alike. 

2317 _loss_needs_mask = (_is_batched_list or _is_padded_tokens) and return_type in ( 

2318 "loss", 

2319 "both", 

2320 ) 

2321 _loss_attention_mask: Optional[torch.Tensor] = None 

2322 if ( 

2323 (_is_batched_list or _is_padded_tokens) 

2324 and attention_mask is None 

2325 and not _is_inputs_embeds 

2326 and (_layout_needs_mask or _loss_needs_mask) 

2327 ): 

2328 if self.tokenizer is None or self.tokenizer.pad_token_id is None: 

2329 if _is_padded_tokens: 2329 ↛ 2372line 2329 didn't jump to line 2372 because the condition on line 2329 was always true

2330 raise ValueError( 

2331 "padding_side=... on token input reads the padding off the " 

2332 "pad token, which needs a tokenizer with a pad_token_id. " 

2333 "Pass attention_mask=... to state the padding directly instead." 

2334 ) 

2335 else: 

2336 derived_mask = utils.get_attention_mask( 

2337 self.tokenizer, 

2338 input_ids, 

2339 prepend_bos=( 

2340 getattr(self.cfg, "default_prepend_bos", True) 

2341 if prepend_bos is None 

2342 else prepend_bos 

2343 ), 

2344 padding_side=_resolved_padding_side, 

2345 ).to(self.cfg.device) 

2346 # A tensor with no pads stays on the unmasked path, so its logits are unchanged. 

2347 _is_unpadded = _is_padded_tokens and bool(derived_mask.all()) 

2348 if not _is_unpadded and not _layout_needs_mask: 

2349 # Causal right padding: the model still runs unmasked, so the 

2350 # logits are unchanged, and only the loss reads the mask. 

2351 _loss_attention_mask = derived_mask 

2352 elif not _is_unpadded: 

2353 attention_mask = derived_mask 

2354 # Gated on the target for the same reason the derivation below 

2355 # is: a fixed-signature forward raises TypeError on the kwarg, 

2356 # and a model that owns its own position derivation is 

2357 # overridden by it (#1626). 

2358 if "position_ids" not in kwargs and self._accepts_derived_position_ids(): 

2359 position_ids = attention_mask.long().cumsum(-1) - 1 

2360 position_ids.masked_fill_(attention_mask == 0, 1) 

2361 kwargs["position_ids"] = position_ids 

2362 

2363 # Any masked-out token shifts the absolute position of every real token 

2364 # after it, so positions must be derived from the mask rather than left 

2365 # to HF's default arange. This is the same derivation HookedTransformer 

2366 # applies in pos_embed; without it the bridge silently returns wrong 

2367 # logits. An all-ones mask reduces to arange, so this is a no-op there. 

2368 # 

2369 # The mask spans any cached prefix as well as the new tokens, so it is 

2370 # offset back to just the tokens actually being passed — matching how 

2371 # AbstractAttention/PosEmbed use past_kv_pos_offset. 

2372 if ( 

2373 attention_mask is not None 

2374 and "position_ids" not in kwargs 

2375 and not _is_inputs_embeds 

2376 and attention_mask.ndim == 2 

2377 and isinstance(input_ids, torch.Tensor) 

2378 and input_ids.ndim == 2 

2379 and attention_mask.shape[1] >= input_ids.shape[1] 

2380 and self._accepts_derived_position_ids() 

2381 ): 

2382 # .long() because callers may hand in a float 0/1 mask, and 

2383 # positions index an embedding table. 

2384 _derived = utils.get_offset_position_ids(0, attention_mask.long()) 

2385 _arange = torch.arange(attention_mask.shape[1], device=_derived.device) 

2386 # Decide per row, not per batch. A row only needs the derived 

2387 # positions when its mask actually moves one of its attended 

2388 # tokens off the default position — i.e. a masked token precedes 

2389 # a real one (left padding, or an interior gap). Rows that are 

2390 # unpadded or purely right-padded keep arange verbatim, so one 

2391 # left-padded row in a batch cannot perturb its neighbours. 

2392 _needs = ((_derived != _arange) & (attention_mask != 0)).any(dim=1, keepdim=True) 

2393 if bool(_needs.any()): 

2394 _positions = torch.where(_needs, _derived, _arange.expand_as(_derived)) 

2395 kwargs["position_ids"] = _positions[ 

2396 :, attention_mask.shape[1] - input_ids.shape[1] : 

2397 ] 

2398 

2399 if attention_mask is not None: 

2400 kwargs["attention_mask"] = attention_mask 

2401 if past_key_values is not None: 

2402 # Manual KV-cache injection: hand HF its own cache back and let it 

2403 # extend it, computing only the new tokens' keys/values. 

2404 kwargs["past_key_values"] = past_key_values 

2405 kwargs["use_cache"] = True 

2406 if kwargs.pop("use_past_kv_cache", False) or kwargs.get("use_cache", False): 

2407 kwargs["use_cache"] = True 

2408 is_audio_seq2seq = getattr(self.cfg, "is_audio_seq2seq", False) 

2409 # Auto-generate decoder_input_ids for encoder-decoder models. Audio 

2410 # seq2seq is excluded: its encoder input is audio, not decoder tokens. 

2411 if ( 

2412 "decoder_input_ids" not in kwargs 

2413 and labels is None 

2414 and is_encoder_decoder 

2415 and not is_audio_seq2seq 

2416 ): 

2417 decoder_start_token_id = getattr( 

2418 self.original_model.config, "decoder_start_token_id", None 

2419 ) 

2420 if decoder_start_token_id is not None: 

2421 shifted = input_ids[:, :-1] 

2422 start_tokens = torch.full( 

2423 (input_ids.shape[0], 1), 

2424 decoder_start_token_id, 

2425 dtype=input_ids.dtype, 

2426 device=input_ids.device, 

2427 ) 

2428 kwargs["decoder_input_ids"] = torch.cat([start_tokens, shifted], dim=1) 

2429 else: 

2430 kwargs["decoder_input_ids"] = input_ids 

2431 

2432 # Tell PosEmbedBridge to expand batch=1 position_ids to full batch. 

2433 if hasattr(self, "pos_embed"): 

2434 self.pos_embed._current_batch_size = input_ids.shape[0] 

2435 

2436 # Handle pixel_values for multimodal and vision models 

2437 if pixel_values is not None: 

2438 if not ( 

2439 getattr(self.cfg, "is_multimodal", False) 

2440 or getattr(self.cfg, "is_visual_model", False) 

2441 ): 

2442 raise ValueError( 

2443 "pixel_values can only be passed to multimodal or vision models " 

2444 "(cfg.is_multimodal or cfg.is_visual_model must be True)" 

2445 ) 

2446 kwargs["pixel_values"] = pixel_values 

2447 

2448 # Handle input_values for audio models 

2449 if input_values is not None: 

2450 if not getattr(self.cfg, "is_audio_model", False): 2450 ↛ 2451line 2450 didn't jump to line 2451 because the condition on line 2450 was never true

2451 raise ValueError( 

2452 "input_values can only be passed to audio models " 

2453 "(cfg.is_audio_model must be True)" 

2454 ) 

2455 kwargs["input_values"] = input_values 

2456 

2457 if is_audio_seq2seq: 

2458 if input_values is not None: 

2459 raise ValueError( 

2460 "Audio seq2seq models take the audio features tensor as `input` " 

2461 f"(passed to the model as {self.adapter.audio_input_name!r}), " 

2462 "not input_values." 

2463 ) 

2464 if "decoder_input_ids" not in kwargs and labels is None: 

2465 raise ValueError( 

2466 "Audio seq2seq models require decoder_input (decoder token ids, " 

2467 "e.g. the start-of-transcript prompt) or labels." 

2468 ) 

2469 assert isinstance(input, torch.Tensor) # str/list input is rejected above 

2470 n_clips = input.shape[0] 

2471 decoder_input_ids = kwargs.get("decoder_input_ids") 

2472 if isinstance(decoder_input_ids, torch.Tensor): 

2473 kwargs["decoder_input_ids"] = self._align_decoder_batch( 

2474 decoder_input_ids, n_clips, "decoder_input" 

2475 ) 

2476 if labels is not None: 

2477 labels = self._align_decoder_batch(labels, n_clips, "labels") 

2478 kwargs["labels"] = labels 

2479 decoder_attention_mask = kwargs.get("decoder_attention_mask") 

2480 if isinstance(decoder_attention_mask, torch.Tensor): 

2481 kwargs["decoder_attention_mask"] = self._align_decoder_batch( 

2482 decoder_attention_mask, n_clips, "decoder_attention_mask" 

2483 ) 

2484 kwargs[self.adapter.audio_input_name] = input 

2485 result = self._driver.forward(**kwargs) 

2486 # Audio models use input_values (waveform), not input_ids 

2487 elif getattr(self.cfg, "is_audio_model", False): 

2488 if input_values is not None: 2488 ↛ 2489line 2488 didn't jump to line 2489 because the condition on line 2488 was never true

2489 result = self._driver.forward(**kwargs) 

2490 elif isinstance(input, torch.Tensor): 2490 ↛ 2494line 2490 didn't jump to line 2494 because the condition on line 2490 was always true

2491 kwargs["input_values"] = input 

2492 result = self._driver.forward(**kwargs) 

2493 else: 

2494 raise ValueError( 

2495 "Audio models require tensor input (raw waveform). " 

2496 "Pass a torch.Tensor or use input_values parameter." 

2497 ) 

2498 elif getattr(self.cfg, "is_visual_model", False): 

2499 # "pixel_values" may already be in kwargs from the "if pixel_values is not None:" 

2500 # gate above (explicit pixel_values=... call); otherwise treat `input` itself as 

2501 # the image tensor, matching how the audio branch treats `input` as the waveform. 

2502 if "pixel_values" not in kwargs: 2502 ↛ 2510line 2502 didn't jump to line 2510 because the condition on line 2502 was always true

2503 if isinstance(input, torch.Tensor): 2503 ↛ 2506line 2503 didn't jump to line 2506 because the condition on line 2503 was always true

2504 kwargs["pixel_values"] = input 

2505 else: 

2506 raise ValueError( 

2507 "Visual models require tensor input (pixel values). " 

2508 "Pass a torch.Tensor as `input` or use the pixel_values parameter." 

2509 ) 

2510 result = self._driver.forward(**kwargs) 

2511 elif _is_inputs_embeds: 

2512 result = self._driver.forward(inputs_embeds=input_ids, **kwargs) 

2513 else: 

2514 # By keyword so kw-only ``input_ids`` drivers don't TypeError. 

2515 result = self._driver.forward(input_ids=input_ids, **kwargs) 

2516 output = result.raw_output 

2517 # No-op for HF (its hooks already fired); load-bearing for vLLM/Inspect. 

2518 if result.captured: 2518 ↛ 2519line 2518 didn't jump to line 2519 because the condition on line 2518 was never true

2519 self._replay_captures(result.captured) 

2520 # Convert TensorLike to torch at the boundary; let weird shapes 

2521 # (audio/CTC dataclasses, tuple-of-tuples) pass through unchanged — 

2522 # downstream return_type branches catch them with specific errors. 

2523 logits = result.logits 

2524 if isinstance(logits, torch.Tensor): 2524 ↛ 2526line 2524 didn't jump to line 2526 because the condition on line 2524 was always true

2525 pass 

2526 elif logits is not None and isinstance(logits, TensorLike): 

2527 logits = to_torch(logits) 

2528 # Stash only the cache object (not the full output) for generate(). 

2529 if getattr(self, "_capture_hf_cache", False): 

2530 self._last_hf_cache = getattr(output, "past_key_values", None) 

2531 if return_type == "logits_and_cache": 

2532 past_key_values = getattr(output, "past_key_values", None) 

2533 return (logits, past_key_values) 

2534 if is_encoder_decoder and return_type in ("loss", "both"): 

2535 assert isinstance( 

2536 logits, torch.Tensor 

2537 ), f"Expected seq2seq logits tensor, got {type(logits)}" 

2538 assert isinstance(labels, torch.Tensor) 

2539 return self._finalize_seq2seq_return( 

2540 return_type, 

2541 logits, 

2542 labels, 

2543 output, 

2544 loss_per_token=loss_per_token, 

2545 ) 

2546 return self._finalize_return( 

2547 return_type, 

2548 logits, 

2549 input_ids, 

2550 attention_mask=( 

2551 attention_mask if attention_mask is not None else _loss_attention_mask 

2552 ), 

2553 labels=labels, 

2554 is_audio_model=getattr(self.cfg, "is_audio_model", False), 

2555 is_visual_model=getattr(self.cfg, "is_visual_model", False), 

2556 inputs_embeds_was_used=_is_inputs_embeds, 

2557 loss_per_token=loss_per_token, 

2558 ) 

2559 except StopAtLayerException as e: 

2560 # Execution stopped at the requested layer 

2561 return e.layer_output 

2562 finally: 

2563 # Clean up state that may be inconsistent after StopAtLayerException 

2564 if final_stop_handle is not None: 

2565 final_stop_handle.remove() 

2566 if stop_at_layer is not None: 

2567 for bl_name in ( 

2568 "blocks", 

2569 "encoder_blocks", 

2570 "decoder_blocks", 

2571 "L_blocks", 

2572 "H_blocks", 

2573 ): 

2574 if hasattr(self, bl_name): 

2575 for block in getattr(self, bl_name): 

2576 block._stop_at_layer_idx = None 

2577 

2578 # Clear any stale KV cache — layers after the stop point didn't 

2579 # execute, so the cache is incomplete and would corrupt subsequent 

2580 # generate() calls that expect a full cache. 

2581 if hasattr(self, "_last_hf_cache"): 2581 ↛ 2582line 2581 didn't jump to line 2582 because the condition on line 2581 was never true

2582 del self._last_hf_cache 

2583 

2584 if start_at_layer is not None: 

2585 self._teardown_start_at_layer() 

2586 

2587 @staticmethod 

2588 def _align_decoder_batch(ids: torch.Tensor, n_clips: int, name: str) -> torch.Tensor: 

2589 """Line decoder ids or masks up with the audio batch: one row per clip, or one shared row. 

2590 

2591 HF does not check this, and a single row against several clips returns one row 

2592 of logits that matches none of them. 

2593 """ 

2594 if ids.ndim == 1: 

2595 ids = ids.unsqueeze(0) 

2596 if ids.shape[0] == n_clips: 

2597 return ids 

2598 if ids.shape[0] == 1: 

2599 return ids.repeat(n_clips, 1) 

2600 raise ValueError( 

2601 f"{name} has batch size {ids.shape[0]} but the audio features have {n_clips}; " 

2602 "pass one row per clip, or a single row shared by every clip." 

2603 ) 

2604 

2605 def _audio_generation_inputs( 

2606 self, input: Any, kwargs: Dict[str, Any], max_new_tokens: int 

2607 ) -> tuple[torch.Tensor, torch.Tensor]: 

2608 """Audio features and decoder prompt for audio seq2seq generation. 

2609 

2610 The prompt is ``decoder_input`` if given, else the tokenizer's prefix tokens 

2611 (Whisper: <|startoftranscript|>, the language and task set with 

2612 ``tokenizer.set_prefix_tokens``, <|notimestamps|>), else decoder_start alone. 

2613 """ 

2614 if not (isinstance(input, torch.Tensor) and input.is_floating_point()): 

2615 raise ValueError( 

2616 "Audio seq2seq generation takes the audio features tensor (e.g. Whisper's " 

2617 "log-mel input_features) as input, not text or token ids. Pass the " 

2618 "decoder prompt as decoder_input." 

2619 ) 

2620 features = input.to(self.cfg.device) 

2621 prompt = kwargs.pop("decoder_input", None) 

2622 if prompt is None: 

2623 prompt = kwargs.pop("decoder_input_ids", None) 

2624 if prompt is None: 

2625 prefix = getattr(self.tokenizer, "prefix_tokens", None) or [ 

2626 self.cfg.decoder_start_token_id 

2627 ] 

2628 prompt = torch.tensor([prefix]) 

2629 prompt = self._align_decoder_batch( 

2630 torch.as_tensor(prompt, device=self.cfg.device), features.shape[0], "decoder_input" 

2631 ) 

2632 if prompt.shape[1] + max_new_tokens > self.cfg.n_ctx: 

2633 raise ValueError( 

2634 f"The decoder prompt ({prompt.shape[1]} tokens) plus max_new_tokens " 

2635 f"({max_new_tokens}) exceeds the decoder's {self.cfg.n_ctx} positions." 

2636 ) 

2637 return features, prompt 

2638 

2639 def _setup_start_at_layer(self, input: Any, start_at_layer: int) -> torch.Tensor: 

2640 """Arm residual-stream injection at block ``start_at_layer``. 

2641 

2642 ``input`` is the residual entering that block. It is returned (batch-promoted) 

2643 to drive the HF forward as ``inputs_embeds`` so position ids / attention mask 

2644 are computed for the right sequence length; block ``start_at_layer`` then swaps 

2645 it back in for its own input, discarding whatever blocks 0..k-1 produced. 

2646 """ 

2647 if getattr(self.cfg, "is_visual_model", False): 

2648 raise NotImplementedError( 

2649 "start_at_layer is not supported for vision models: the residual " 

2650 "re-entry path assumes token inputs_embeds." 

2651 ) 

2652 if getattr(self.cfg, "is_audio_model", False): 

2653 raise NotImplementedError( 

2654 "start_at_layer is not supported for audio models: audio encoders " 

2655 "process waveforms through convolutional feature extraction before " 

2656 "the transformer blocks, making residual-stream injection infeasible." 

2657 ) 

2658 for alt in ("encoder_blocks", "decoder_blocks", "L_blocks", "H_blocks"): 

2659 if hasattr(self, alt): 2659 ↛ 2660line 2659 didn't jump to line 2660 because the condition on line 2659 was never true

2660 raise NotImplementedError( 

2661 "start_at_layer is only supported on the standard 'blocks' stack, " 

2662 f"not {alt!r}." 

2663 ) 

2664 if not self._has_registered_blocks(): 

2665 raise NotImplementedError("start_at_layer requires a 'blocks' stack.") 

2666 

2667 if not (isinstance(input, torch.Tensor) and input.is_floating_point()): 

2668 raise ValueError( 

2669 "start_at_layer requires a residual-stream tensor [batch, pos, d_model]; " 

2670 f"got {type(input).__name__}. Capture it from a prior run_with_cache " 

2671 "(e.g. cache['blocks.k.hook_in'])." 

2672 ) 

2673 residual = input if input.ndim == 3 else input.unsqueeze(0) 

2674 n_blocks = len(self.blocks) 

2675 if start_at_layer < 0: 

2676 start_at_layer += n_blocks 

2677 if not 0 <= start_at_layer < n_blocks: 

2678 raise ValueError(f"start_at_layer={start_at_layer} out of range [0, {n_blocks}).") 

2679 # The returned tensor is fed to HF as inputs_embeds; stash a clone so an 

2680 # architecture that mutates inputs_embeds in place can't corrupt the value 

2681 # block ``start_at_layer`` swaps back in. 

2682 injected = residual.clone() 

2683 for block in self.blocks: 

2684 block._start_at_layer_idx = start_at_layer 

2685 block._start_residual = injected 

2686 return residual 

2687 

2688 def _teardown_start_at_layer(self) -> None: 

2689 """Clear the residual-injection state set by ``_setup_start_at_layer``.""" 

2690 if hasattr(self, "blocks"): 2690 ↛ exitline 2690 didn't return from function '_teardown_start_at_layer' because the condition on line 2690 was always true

2691 for block in self.blocks: 

2692 block._start_at_layer_idx = None 

2693 block._start_residual = None 

2694 

2695 # loss_fn inherited from BridgeCore 

2696 

2697 def _resolve_stopping_criteria( 

2698 self, 

2699 stop_strings: Optional[Union[str, List[str]]], 

2700 stopping_criteria: Optional[Any], 

2701 ) -> Optional[Any]: 

2702 """Combine ``stop_strings`` and ``stopping_criteria`` into one StoppingCriteriaList. 

2703 

2704 Returns ``None`` when neither is supplied (or both reduce to no-ops), 

2705 so callers can cheaply check whether any extra stop signal is active. 

2706 ``stop_strings`` is turned into a HuggingFace ``StopStringCriteria`` (which reproduces 

2707 HF's exact partial-token-aware, end-anchored matching: it fires when the stop string 

2708 ends the generated text, even if the string straddles token boundaries) and therefore 

2709 requires a tokenizer. 

2710 A user-supplied ``stopping_criteria`` may be a single ``StoppingCriteria``, 

2711 a list of them, or a ``StoppingCriteriaList``. 

2712 

2713 Raises: 

2714 ValueError: if ``stop_strings`` is supplied without a tokenizer. 

2715 TypeError: if ``stopping_criteria`` is not a ``StoppingCriteria``, a 

2716 list/tuple of them, or a ``StoppingCriteriaList``. 

2717 """ 

2718 if stop_strings is None and stopping_criteria is None: 

2719 return None 

2720 

2721 from transformers import ( # local import: matches the file's transformers usage 

2722 StoppingCriteria, 

2723 StoppingCriteriaList, 

2724 StopStringCriteria, 

2725 ) 

2726 

2727 criteria = StoppingCriteriaList() 

2728 

2729 if stop_strings is not None: 

2730 strings = [stop_strings] if isinstance(stop_strings, str) else list(stop_strings) 

2731 strings = [s for s in strings if s] # drop empty strings (HF errors on them) 

2732 if strings: 

2733 if self.tokenizer is None: 

2734 raise ValueError( 

2735 "stop_strings requires a tokenizer (stop strings are detected by " 

2736 "matching against the tokenizer vocabulary), but this TransformerBridge " 

2737 "has no tokenizer. Pass a stopping_criteria callable that operates on " 

2738 "token ids instead, or use hf_generate()." 

2739 ) 

2740 criteria.append(StopStringCriteria(tokenizer=self.tokenizer, stop_strings=strings)) 

2741 

2742 if stopping_criteria is not None: 

2743 if isinstance(stopping_criteria, StoppingCriteriaList): 

2744 criteria.extend(stopping_criteria) 

2745 elif isinstance(stopping_criteria, (list, tuple)): 

2746 criteria.extend(stopping_criteria) 

2747 elif isinstance(stopping_criteria, StoppingCriteria): 

2748 criteria.append(stopping_criteria) 

2749 else: 

2750 raise TypeError( 

2751 "stopping_criteria must be a transformers.StoppingCriteria, a list of " 

2752 f"them, or a StoppingCriteriaList, but got {type(stopping_criteria).__name__}." 

2753 ) 

2754 

2755 return criteria if len(criteria) > 0 else None 

2756 

2757 def _encdec_ngram_processor(self) -> Optional[Any]: 

2758 """generation_config.no_repeat_ngram_size as transformers' own 

2759 processor, or None. HF applies it by default; parity for models whose 

2760 greedy decode needs it to escape token attractors.""" 

2761 size = getattr( 

2762 getattr(self.original_model, "generation_config", None), 

2763 "no_repeat_ngram_size", 

2764 None, 

2765 ) 

2766 if not size: 

2767 return None 

2768 from transformers.generation.logits_process import NoRepeatNGramLogitsProcessor 

2769 

2770 return NoRepeatNGramLogitsProcessor(size) 

2771 

2772 def _encdec_forced_eos_token_id(self) -> Optional[int]: 

2773 """generation_config.forced_eos_token_id, or None. HF forces EOS as the 

2774 final token when max length is reached; BART-family configs set it by 

2775 default and their summaries otherwise end mid-sentence.""" 

2776 value = getattr( 

2777 getattr(self.original_model, "generation_config", None), 

2778 "forced_eos_token_id", 

2779 None, 

2780 ) 

2781 return value if isinstance(value, int) else None 

2782 

2783 def _encdec_suppress_processors(self, prompt_length: int) -> list[Any]: 

2784 """generation_config.suppress_tokens / begin_suppress_tokens as transformers' 

2785 own processors. HF applies both by default; Whisper sets them so greedy 

2786 decoding neither emits its non-speech symbols nor ends before any text.""" 

2787 generation_config = getattr(self.original_model, "generation_config", None) 

2788 device = str(self.cfg.device or "cpu") 

2789 processors: list[Any] = [] 

2790 suppress = getattr(generation_config, "suppress_tokens", None) 

2791 if suppress: 

2792 from transformers.generation.logits_process import ( 

2793 SuppressTokensLogitsProcessor, 

2794 ) 

2795 

2796 processors.append(SuppressTokensLogitsProcessor(suppress, device=device)) 

2797 begin_suppress = getattr(generation_config, "begin_suppress_tokens", None) 

2798 if begin_suppress: 

2799 from transformers.generation.logits_process import ( 

2800 SuppressTokensAtBeginLogitsProcessor, 

2801 ) 

2802 

2803 processors.append( 

2804 SuppressTokensAtBeginLogitsProcessor(begin_suppress, prompt_length, device=device) 

2805 ) 

2806 return processors 

2807 

2808 def _encoder_decoder_setup( 

2809 self, 

2810 input_tokens: torch.Tensor, 

2811 forced_bos_token_id: Optional[int], 

2812 decoder_prompt: Optional[torch.Tensor] = None, 

2813 ) -> tuple[torch.Tensor, Optional[int]]: 

2814 """Share decoder initialization and length defaults across generation paths. 

2815 

2816 ``decoder_prompt`` replaces the decoder_start seed (audio seq2seq models start 

2817 from a multi-token prompt such as Whisper's <|startoftranscript|> prefix). 

2818 """ 

2819 config = self.original_model.config 

2820 generation_config = getattr(self.original_model, "generation_config", None) 

2821 if forced_bos_token_id is None: 

2822 # HF defaults such as bart-large-cnn's forced BOS apply to both loops. 

2823 forced_bos_token_id = getattr(generation_config, "forced_bos_token_id", None) 

2824 min_decoder_length = getattr(generation_config, "min_length", None) 

2825 if decoder_prompt is not None: 

2826 return decoder_prompt, min_decoder_length 

2827 start = getattr(config, "decoder_start_token_id", None) 

2828 if start is None: 

2829 # HF falls back to BOS, then EOS; IndicBART starts decoding from EOS. 

2830 start = getattr(config, "bos_token_id", None) 

2831 if start is None: 

2832 start = getattr(config, "eos_token_id", None) 

2833 if isinstance(start, (list, tuple)): 

2834 start = start[0] 

2835 if start is None: 

2836 start = 0 

2837 seed = torch.full( 

2838 (input_tokens.shape[0], 1), 

2839 start, 

2840 dtype=input_tokens.dtype, 

2841 device=input_tokens.device, 

2842 ) 

2843 if forced_bos_token_id is not None: 

2844 # Multilingual seq2seq selects the target language after decoder_start. 

2845 forced = torch.full_like(seed, forced_bos_token_id) 

2846 seed = torch.cat([seed, forced], dim=1) 

2847 return seed, min_decoder_length 

2848 

2849 def _left_padded_prompt_mask( 

2850 self, prompts: List[str], tokens: torch.Tensor, prepend_bos: Optional[bool] 

2851 ) -> torch.Tensor: 

2852 """Attention mask for ``prompts`` left-padded into ``tokens``, from each one's length. 

2853 

2854 The tokens alone can't give this when the pad id is also a real token, as BOS is on 

2855 GPT-2-style tokenizers: a row's last pad and a leading BOS look the same. 

2856 """ 

2857 mask = torch.zeros_like(tokens) 

2858 for row, prompt in enumerate(prompts): 

2859 n_real = self.to_tokens( 

2860 prompt, prepend_bos=prepend_bos, move_to_device=False, truncate=False 

2861 ).shape[-1] 

2862 # An empty prompt keeps its last pad as context, and -0 would select the whole row. 

2863 mask[row, -max(n_real, 1) :] = 1 

2864 return mask 

2865 

2866 def _generate_tokens( 

2867 self, 

2868 current_tokens: torch.Tensor, 

2869 input_tokens: torch.Tensor, 

2870 batch_size: int, 

2871 *, 

2872 max_new_tokens: int, 

2873 do_sample: bool, 

2874 top_k: Optional[int], 

2875 top_p: Optional[float], 

2876 temperature: float, 

2877 freq_penalty: float, 

2878 repetition_penalty: float, 

2879 stop_at_eos: bool, 

2880 stop_tokens: List[int], 

2881 eos_token_for_padding: int, 

2882 finished_sequences: torch.Tensor, 

2883 use_past_kv_cache: bool, 

2884 use_stateful_cache: bool, 

2885 mamba_cache: Any, 

2886 mamba_conv_kernel: int, 

2887 is_encoder_decoder: bool, 

2888 batched_prompt_mask: Optional[torch.Tensor], 

2889 _generate_from_embeds: bool, 

2890 encoder_input: Optional[torch.Tensor], 

2891 decoder_tokens: Optional[torch.Tensor], 

2892 generated_token_ids: Optional[List[torch.Tensor]], 

2893 pixel_values: Optional[torch.Tensor], 

2894 multimodal_kwargs: Dict[str, Any], 

2895 verbose: bool, 

2896 stopping_criteria_list: Optional[Any] = None, 

2897 initial_attention_mask: Optional[torch.Tensor] = None, 

2898 min_decoder_length: Optional[int] = None, 

2899 ngram_processor: Optional[Any] = None, 

2900 encoder_attention_mask: Optional[torch.Tensor] = None, 

2901 forced_eos_token_id: Optional[int] = None, 

2902 suppress_processors: Sequence[Any] = (), 

2903 encoder_outputs: Optional[Any] = None, 

2904 ) -> Generator[Tuple[torch.Tensor, torch.Tensor, bool], None, None]: 

2905 """Core generation loop. Yields (sampled_tokens, raw_logits, all_finished) per step. 

2906 

2907 Owns the forward pass, sampling, stop handling (EOS and any 

2908 ``stopping_criteria_list``), token accumulation, and KV cache management. Callers 

2909 are responsible for try/finally cleanup of ``_capture_hf_cache``. 

2910 

2911 ``stopping_criteria_list`` (from ``_resolve_stopping_criteria``) is evaluated on 

2912 the running sequence each step and folded into the finished-sequence mask alongside 

2913 EOS, so when it is ``None`` the loop runs the EOS-only path unchanged. 

2914 """ 

2915 _hf_kv_cache = None 

2916 # A prior multimodal forward caches mrope deltas on the wrapped model, and a 

2917 # text-only generation would inherit them through the KV-cache position path 

2918 # (HF's own generate recomputes them at prefill; driving forward() directly 

2919 # makes that reset this loop's job). 

2920 base = getattr(self.original_model, "base_model", self.original_model) 

2921 if getattr(base, "rope_deltas", None) is not None: 

2922 base.rope_deltas = None 

2923 # A row may finish via EOS and/or any of the configured stopping criteria. 

2924 any_stop_active = stop_at_eos or stopping_criteria_list is not None 

2925 

2926 # Models that own their position derivation (the gate refuses them) cache 

2927 # mRoPE deltas on the module between calls; a text-only prefill never 

2928 # refreshes them, so a stale delta from an earlier multimodal forward gets 

2929 # added to every cached-step position. HF's generate recomputes them at 

2930 # prefill via prepare_inputs_for_generation, which this loop bypasses — 

2931 # so match it by clearing before the prompt pass. A multimodal prefill 

2932 # recomputes its own fresh deltas regardless. 

2933 if not self._accepts_derived_position_ids(): 

2934 underlying = getattr(self, "original_model", None) 

2935 for module in ( 

2936 underlying, 

2937 getattr(underlying, "model", None), 

2938 getattr(underlying, "language_model", None), 

2939 ): 

2940 if module is not None and hasattr(module, "rope_deltas"): 

2941 module.rope_deltas = None 

2942 

2943 # Pure-SSM models (Mamba-1/2) take the stateful cache as `cache_params`; 

2944 # modern hybrids (Bamba, NemotronH, FalconH1) take `past_key_values` and 

2945 # would receive a duplicate cache_params via **kwargs cascade otherwise. 

2946 stateful_cache_kwarg = "cache_params" 

2947 if use_stateful_cache: 

2948 forward_params = inspect.signature(self.original_model.forward).parameters 

2949 if "cache_params" not in forward_params: 

2950 stateful_cache_kwarg = "past_key_values" 

2951 

2952 for gen_step_idx in tqdm.tqdm(range(max_new_tokens), disable=not verbose): 

2953 with torch.no_grad(): 

2954 if is_encoder_decoder: 

2955 assert encoder_input is not None 

2956 encdec_kwargs: Dict[str, Any] = {} 

2957 if encoder_attention_mask is not None: 

2958 encdec_kwargs["attention_mask"] = encoder_attention_mask.to( 

2959 encoder_input.device 

2960 ) 

2961 if encoder_outputs is not None: 

2962 encdec_kwargs["encoder_outputs"] = encoder_outputs 

2963 logits = self( 

2964 encoder_input, 

2965 return_type="logits", 

2966 decoder_input=decoder_tokens, 

2967 **encdec_kwargs, 

2968 ) 

2969 else: 

2970 forward_kwargs: Dict[str, Any] = {} 

2971 # A prompt mask covers only the prompt, so extend it by one 

2972 # attended column per token generated so far. position_ids are 

2973 # left to forward(), which derives them from the mask for the 

2974 # models that can take them. 

2975 running_attention_mask: Optional[torch.Tensor] = None 

2976 if initial_attention_mask is not None: 

2977 running_attention_mask = _extend_prompt_attention_mask( 

2978 initial_attention_mask, current_tokens 

2979 ) 

2980 forward_kwargs["attention_mask"] = running_attention_mask 

2981 # Compute attention mask and position_ids for batched 

2982 # inputs with padding. 

2983 if initial_attention_mask is None and batched_prompt_mask is not None: 

2984 attn_mask = _extend_prompt_attention_mask( 

2985 batched_prompt_mask, current_tokens 

2986 ) 

2987 forward_kwargs["attention_mask"] = attn_mask 

2988 # Same target gate as the forward() path: the mask is safe 

2989 # for every model, the derived positions are not (#1626). 

2990 if self._accepts_derived_position_ids(): 

2991 position_ids = attn_mask.long().cumsum(-1) - 1 

2992 position_ids.masked_fill_(attn_mask == 0, 1) 

2993 forward_kwargs["position_ids"] = position_ids 

2994 if gen_step_idx == 0: 

2995 if pixel_values is not None: 

2996 forward_kwargs["pixel_values"] = pixel_values 

2997 if multimodal_kwargs: 

2998 forward_kwargs.update(multimodal_kwargs) 

2999 if use_stateful_cache: 

3000 forward_kwargs[stateful_cache_kwarg] = mamba_cache 

3001 forward_kwargs["use_cache"] = True 

3002 if gen_step_idx == 0: 

3003 # Mamba's conv-window warmup positions vs standard 

3004 # full-prompt positions for past_key_values hybrids. 

3005 prefill_len = ( 

3006 mamba_conv_kernel 

3007 if stateful_cache_kwarg == "cache_params" 

3008 else current_tokens.shape[1] 

3009 ) 

3010 cache_position = torch.arange(0, prefill_len, device=self.cfg.device) 

3011 forward_kwargs["cache_position"] = cache_position 

3012 logits = self( 

3013 current_tokens, 

3014 return_type="logits", 

3015 **forward_kwargs, 

3016 ) 

3017 else: 

3018 input_seq_pos = input_tokens.shape[1] + gen_step_idx - 1 

3019 cache_position = torch.tensor([input_seq_pos], device=self.cfg.device) 

3020 forward_kwargs["cache_position"] = cache_position 

3021 if "position_ids" in forward_kwargs: 3021 ↛ 3022line 3021 didn't jump to line 3022 because the condition on line 3021 was never true

3022 forward_kwargs["position_ids"] = forward_kwargs["position_ids"][ 

3023 :, -1: 

3024 ] 

3025 logits = self( 

3026 current_tokens[:, -1:], 

3027 return_type="logits", 

3028 **forward_kwargs, 

3029 ) 

3030 elif use_past_kv_cache: 

3031 forward_kwargs["use_cache"] = True 

3032 if _hf_kv_cache is not None: 

3033 forward_kwargs["past_key_values"] = _hf_kv_cache 

3034 # HF v5 + macOS-arm64 NaNs when these are inferred 

3035 # from cache state alone. Mirror HF generate(): pass 

3036 # both an (batch, total_len) attention_mask and a 

3037 # (batch, 1) position_ids for the new token. 

3038 batch_size = current_tokens.shape[0] 

3039 total_len = current_tokens.shape[1] 

3040 device = current_tokens.device 

3041 if "attention_mask" not in forward_kwargs: 

3042 forward_kwargs["attention_mask"] = torch.ones( 

3043 (batch_size, total_len), 

3044 dtype=torch.long, 

3045 device=device, 

3046 ) 

3047 # Gated as a whole (#1626): every branch below supplies 

3048 # position_ids, so gating only the prompt derivation 

3049 # above would divert a refused model into the 

3050 # total_len - 1 fallback, which counts pad slots and is 

3051 # wrong per row for a left-padded batch. A model that 

3052 # owns its position derivation gets the mask alone, 

3053 # matching the uncached path. 

3054 if self._accepts_derived_position_ids(): 

3055 if "position_ids" in forward_kwargs: 

3056 forward_kwargs["position_ids"] = forward_kwargs["position_ids"][ 

3057 :, -1: 

3058 ] 

3059 elif running_attention_mask is not None: 

3060 # total_len - 1 counts pad slots, so it is wrong 

3061 # for a left-padded prompt. Derive the new token's 

3062 # position from the mask instead. 

3063 forward_kwargs["position_ids"] = utils.get_offset_position_ids( 

3064 0, running_attention_mask.long() 

3065 )[:, -1:] 

3066 else: 

3067 forward_kwargs["position_ids"] = torch.full( 

3068 (batch_size, 1), 

3069 total_len - 1, 

3070 dtype=torch.long, 

3071 device=device, 

3072 ) 

3073 logits = self( 

3074 current_tokens[:, -1:], 

3075 return_type="logits", 

3076 **forward_kwargs, 

3077 ) 

3078 else: 

3079 logits = self( 

3080 current_tokens, 

3081 return_type="logits", 

3082 **forward_kwargs, 

3083 ) 

3084 else: 

3085 logits = self(current_tokens, return_type="logits", **forward_kwargs) 

3086 if use_past_kv_cache and hasattr(self, "_last_hf_cache"): 

3087 _hf_kv_cache = self._last_hf_cache or _hf_kv_cache 

3088 del self._last_hf_cache 

3089 raw_logits = logits[:, -1, :] 

3090 # Clone so processors may edit scores in place without leaking into raw_logits. 

3091 final_logits = raw_logits.clone() 

3092 

3093 # Sample next token 

3094 penalty_tokens = ( 

3095 torch.stack(generated_token_ids, dim=1) 

3096 if _generate_from_embeds and generated_token_ids 

3097 else None 

3098 ) 

3099 # transformers' own NoRepeatNGramLogitsProcessor, honoring 

3100 # generation_config (bart-large-cnn pins 3; without it greedy 

3101 # decoding falls into a BOS attractor and emits nothing). 

3102 if ngram_processor is not None and decoder_tokens is not None: 

3103 final_logits = ngram_processor(decoder_tokens, final_logits) 

3104 if decoder_tokens is not None: 

3105 for processor in suppress_processors: 

3106 final_logits = processor(decoder_tokens, final_logits) 

3107 # HF's generate() suppresses EOS below generation_config.min_length 

3108 # (bart-large-cnn pins 56); without this the loop can EOS on step 

3109 # one and emit an empty summary. 

3110 if ( 

3111 min_decoder_length is not None 

3112 and is_encoder_decoder 

3113 and decoder_tokens is not None 

3114 and decoder_tokens.shape[1] < min_decoder_length 

3115 and stop_tokens 

3116 ): 

3117 final_logits[:, stop_tokens] = float("-inf") 

3118 # Force EOS as the last allowed token, applied after the other 

3119 # processors so it wins — the same ordering HF uses for 

3120 # ForcedEOSTokenLogitsProcessor. 

3121 if forced_eos_token_id is not None and gen_step_idx == max_new_tokens - 1: 

3122 final_logits = torch.full_like(final_logits, float("-inf")) 

3123 final_logits[:, forced_eos_token_id] = 0.0 

3124 if do_sample: 

3125 sampled_tokens = utils.sample_logits( 

3126 final_logits, 

3127 top_k=top_k, 

3128 top_p=top_p, 

3129 temperature=temperature, 

3130 freq_penalty=freq_penalty, 

3131 repetition_penalty=repetition_penalty, 

3132 tokens=( 

3133 penalty_tokens 

3134 if _generate_from_embeds 

3135 else (decoder_tokens if is_encoder_decoder else current_tokens) 

3136 ), 

3137 ).to(self.cfg.device) 

3138 else: 

3139 sampled_tokens = utils.sample_logits( 

3140 final_logits, 

3141 temperature=0.0, 

3142 # Greedy ignores the penalty but still validates it. 

3143 freq_penalty=freq_penalty, 

3144 repetition_penalty=repetition_penalty, 

3145 tokens=( 

3146 penalty_tokens 

3147 if _generate_from_embeds 

3148 else (decoder_tokens if is_encoder_decoder else current_tokens) 

3149 ), 

3150 ).to(self.cfg.device) 

3151 

3152 # Freeze rows that finished on an earlier step so they stop emitting 

3153 # real tokens. Applies to every active stop mechanism, not just EOS. 

3154 if any_stop_active: 

3155 sampled_tokens[finished_sequences] = eos_token_for_padding 

3156 

3157 # Fold this step's EOS matches into the finished mask. 

3158 if stop_at_eos: 

3159 finished_sequences.logical_or_( 

3160 torch.isin( 

3161 sampled_tokens.to(self.cfg.device), 

3162 torch.tensor(stop_tokens).to(self.cfg.device), 

3163 ) 

3164 ) 

3165 

3166 # Update token sequences 

3167 if is_encoder_decoder: 

3168 assert decoder_tokens is not None 

3169 decoder_tokens = torch.cat([decoder_tokens, sampled_tokens.unsqueeze(1)], dim=1) 

3170 elif _generate_from_embeds: 

3171 assert generated_token_ids is not None 

3172 generated_token_ids.append(sampled_tokens) 

3173 embed_fn = self.original_model.get_input_embeddings() # type: ignore[operator] 

3174 assert embed_fn is not None 

3175 new_embed = embed_fn(sampled_tokens.unsqueeze(1)).to(current_tokens.dtype) 

3176 current_tokens = torch.cat([current_tokens, new_embed], dim=1) 

3177 else: 

3178 current_tokens = torch.cat([current_tokens, sampled_tokens.unsqueeze(1)], dim=1) 

3179 

3180 # Fold stop_strings / stopping_criteria into the finished mask. They are 

3181 # evaluated on the full running sequence (prompt + everything generated so 

3182 # far, including the token just appended) with this step's logits as the 

3183 # scores argument, matching transformers' StoppingCriteria contract. The 

3184 # combined list returns a per-row bool [batch] OR-ing every criterion. 

3185 # generate()/generate_stream() guarantee this is plain decoder-only token 

3186 # generation, so current_tokens is the running token sequence. 

3187 if stopping_criteria_list is not None: 

3188 criteria_finished = stopping_criteria_list(current_tokens, final_logits).to( 

3189 device=self.cfg.device, dtype=torch.bool 

3190 ) 

3191 if criteria_finished.shape != finished_sequences.shape: 

3192 raise ValueError( 

3193 "A stopping criterion returned shape " 

3194 f"{tuple(criteria_finished.shape)}, expected a per-row bool of " 

3195 f"shape {tuple(finished_sequences.shape)} (one entry per sequence)." 

3196 ) 

3197 finished_sequences.logical_or_(criteria_finished) 

3198 

3199 all_finished = bool(any_stop_active and finished_sequences.all().item()) 

3200 

3201 yield sampled_tokens, raw_logits, all_finished 

3202 

3203 if all_finished: 3203 ↛ 3204line 3203 didn't jump to line 3204 because the condition on line 3203 was never true

3204 return 

3205 

3206 def _resolve_generation_caching(self, use_past_kv_cache: bool, batched: bool) -> bool: 

3207 """Honor adapter caching/batching limits (recurrent/conv decoders have no KV 

3208 cache; batching is rejected where padding can't be masked, not mis-generated).""" 

3209 if batched and not getattr(self.adapter, "supports_batched_generation", True): 

3210 architecture = self.cfg.architecture or type(self.adapter).__name__ 

3211 raise NotImplementedError( 

3212 f"Batched generation is not supported by {architecture}: its forward does not " 

3213 "apply an attention mask, so padded rows would corrupt the output. Generate one " 

3214 "sequence at a time, or pass equal-length inputs as a tensor." 

3215 ) 

3216 if not getattr(self.adapter, "supports_kv_cache", True): 

3217 return False 

3218 return use_past_kv_cache 

3219 

3220 def _ensure_generation_supported(self, api_name: str) -> None: 

3221 """Reject autoregressive generation for forward-only architectures.""" 

3222 if not self.adapter.supports_generation: 

3223 architecture = self.cfg.architecture or type(self.adapter).__name__ 

3224 hint = ( 

3225 " Use diffusion_generate() — this architecture samples by iterative denoising, " 

3226 "not left-to-right." 

3227 if getattr(self.adapter, "native_sampler", None) 

3228 else "" 

3229 ) 

3230 raise NotImplementedError( 

3231 f"TransformerBridge.{api_name}() generation is not supported by " 

3232 f"the {architecture} architecture.{hint}" 

3233 ) 

3234 

3235 def generate( 

3236 self, 

3237 input: Union[str, List[str], torch.Tensor] = "", 

3238 max_new_tokens: int = 10, 

3239 stop_at_eos: bool = True, 

3240 eos_token_id: Optional[int] = None, 

3241 do_sample: bool = True, 

3242 top_k: Optional[int] = None, 

3243 top_p: Optional[float] = None, 

3244 temperature: float = 1.0, 

3245 freq_penalty: float = 0.0, 

3246 repetition_penalty: float = 1.0, 

3247 use_past_kv_cache: bool = True, 

3248 prepend_bos: Optional[bool] = None, 

3249 padding_side: Optional[str] = None, 

3250 return_type: Optional[str] = "input", 

3251 verbose: bool = True, 

3252 output_logits: bool = False, 

3253 return_cache: bool = False, 

3254 return_input_tokens: bool = False, 

3255 names_filter: Optional[Union[str, List[str], Callable[[str], bool]]] = None, 

3256 device: Optional[Union[str, torch.device]] = None, 

3257 pixel_values: Optional[torch.Tensor] = None, 

3258 stop_strings: Optional[Union[str, List[str]]] = None, 

3259 stopping_criteria: Optional[Any] = None, 

3260 attention_mask: Optional[torch.Tensor] = None, 

3261 forced_bos_token_id: Optional[int] = None, 

3262 **multimodal_kwargs, 

3263 ) -> ( 

3264 str 

3265 | list[str] 

3266 | torch.Tensor 

3267 | Any 

3268 | tuple[Any, ActivationCache] 

3269 | tuple[Any, torch.Tensor] 

3270 ): # Any for transformers.utils.ModelOutput 

3271 # Any: beartype forward ref limitation (beartype#546) 

3272 """Sample tokens from the model. 

3273 

3274 Sample tokens from the model until the model outputs eos_token or max_new_tokens is reached. 

3275 This implementation is based on HookedTransformer.generate() to ensure consistent behavior. 

3276 

3277 Args: 

3278 input: Text string, list of strings, or tensor of tokens. Audio seq2seq models 

3279 (e.g. Whisper) take the audio features tensor instead and decode from 

3280 ``decoder_input`` (one row, shared by every clip, or one per clip), which 

3281 defaults to the tokenizer's prefix tokens. The audio is encoded once per 

3282 call, so encoder hooks fire once and decoder hooks fire every step. The 

3283 default return is the decoder tokens, prompt included, and 

3284 ``return_type="str"`` gives the transcripts. 

3285 max_new_tokens: Maximum number of tokens to generate 

3286 stop_at_eos: If True, stop generating tokens when the model outputs eos_token 

3287 eos_token_id: The token ID to use for end of sentence 

3288 do_sample: If True, sample from the model's output distribution. Otherwise, use greedy search 

3289 top_k: Number of tokens to sample from. If None, sample from all tokens 

3290 top_p: Probability mass to sample from. If 1.0, sample from all tokens 

3291 temperature: Temperature for sampling. Higher values will make the model more random 

3292 freq_penalty: Non-negative frequency penalty for sampling - how much to penalise 

3293 previous tokens (applied only when do_sample=True; negative values raise 

3294 ValueError). Nonzero values require the hooked generation loop; a 

3295 stateful/SSM model that falls back to hf_generate() raises 

3296 NotImplementedError. 

3297 repetition_penalty: HuggingFace-style repetition penalty. Values > 1.0 discourage 

3298 repetition by dividing positive logits and multiplying negative logits for 

3299 previously seen tokens. Default 1.0 (no penalty). 

3300 use_past_kv_cache: If True, use KV caching for faster generation 

3301 prepend_bos: Whether to prepend a BOS token when tokenizing string inputs. 

3302 Defaults to None (uses ``cfg.default_prepend_bos``, typically True). 

3303 Pass ``prepend_bos=False`` when the input is pre-formatted chat-template 

3304 text that already contains the BOS token to avoid double-BOS. 

3305 Ignored when input is already a token tensor. 

3306 padding_side: Which side to pad when tokenizing multiple strings of different 

3307 lengths. For batched list inputs, left-padding is forced internally for 

3308 correct generation behavior. Defaults to None (tokenizer default). 

3309 return_type: The type of output to return - 'input', 'str', or 'tokens' 

3310 verbose: Not used in Bridge (kept for API compatibility) 

3311 output_logits: If True, return a ModelOutput with sequences and a tuple of raw 

3312 per-step model logits, before decoding constraints or sampling transforms. 

3313 return_cache: If True, also return an ActivationCache for the full prompt + 

3314 generated sequence, identical to ``run_with_cache(output)`` with the 

3315 effective prompt attention mask extended over the generated tokens. The call 

3316 returns an ``(output, cache)`` tuple. Implemented as one extra clean forward 

3317 over the output, so the cache includes every hook point (attention patterns 

3318 included). Supported only for single-sequence, decoder-only text generation; 

3319 encoder-decoder, SSM, multimodal, batched, and inputs_embeds inputs raise 

3320 NotImplementedError. The cache spans prompt + actually generated tokens and can be large, 

3321 use ``names_filter`` to scope it and/or ``device`` to offload it. 

3322 return_input_tokens: If True, return an ``(output, input_tokens)`` tuple where 

3323 ``input_tokens`` is the token tensor that was actually fed to the model 

3324 (after BOS handling). Useful for debugging tokenization, especially when 

3325 using chat templates where BOS handling can be subtle. Can be combined 

3326 with ``return_cache`` to get ``(output, cache, input_tokens)``. 

3327 names_filter: Passed to ``run_with_cache`` when ``return_cache=True``; restricts 

3328 which activations are cached (str, list of str, or callable). 

3329 device: Passed through when ``return_cache=True`` to offload the cached tensors 

3330 to this device (e.g. "cpu") to save accelerator memory. 

3331 pixel_values: Optional image tensor for multimodal models. Only passed on the 

3332 first generation step (the vision encoder processes the image once, then 

3333 embeddings are part of the token sequence for subsequent steps). 

3334 stop_strings: Optional string or list of strings. A sequence stops once its 

3335 generated text ends with one of these strings, using HuggingFace's 

3336 StopStringCriteria (partial-token-aware, end-anchored) matching. 

3337 Requires a tokenizer (raises ValueError otherwise). 

3338 Independent of stop_at_eos: either can stop a sequence. 

3339 stopping_criteria: Optional HuggingFace stopping criteria, a single 

3340 transformers.StoppingCriteria, a list of them, or a StoppingCriteriaList. 

3341 Each is called as criterion(input_ids, scores) after every step and ORed 

3342 with the other stop signals, where input_ids is the running sequence and 

3343 scores is this step's logits ([batch, d_vocab]). Each criterion must return 

3344 a per-row bool [batch] (or a scalar bool). stop_strings and stopping_criteria 

3345 are supported only for standard decoder-only text generation. Encoder-decoder, 

3346 inputs_embeds, and multimodal generation always raise NotImplementedError. 

3347 Stateful/SSM models raise only when run with use_past_kv_cache=False (the 

3348 default keeps them on the hooked loop). Each error names the supported 

3349 alternative. 

3350 attention_mask: Optional ``[batch, pos]`` 0/1 mask over the prompt, marking 

3351 which prompt tokens are real. Required to generate correctly from an 

3352 already-padded token tensor: without it the pad tokens are treated as 

3353 real context and every real token's position is shifted, so the 

3354 continuation differs from the same prompt unpadded. The mask is extended 

3355 by one attended column per generated token. Takes precedence over the 

3356 ``padding_side`` heuristic, and unlike it can express an interior gap or 

3357 a pad id that also occurs as a real token. Passing ``padding_side`` 

3358 instead reads the padding off the pad token, which is enough for the 

3359 common single-edge case, and raises if this bridge has no tokenizer 

3360 or pad id to read it from. On the encoder-decoder and inputs_embeds 

3361 paths the mask is forwarded to the model as-is rather than grown per 

3362 step, which is what processors emitting one alongside 

3363 ``pixel_values`` expect. 

3364 forced_bos_token_id: Optional token id seeded as the first decoder token 

3365 after ``decoder_start`` on encoder-decoder models. Multilingual 

3366 translators (M2M100/MBart/NLLB) select their target language this way. 

3367 Raises ValueError on decoder-only models. 

3368 

3369 Returns: 

3370 Generated sequence as string, list of strings, or tensor depending on input type and return_type. 

3371 If output_logits=True, returns a ModelOutput-like object with 'sequences' and 'logits' attributes. 

3372 If return_cache=True, returns an ``(output, ActivationCache)`` tuple where ``output`` is the 

3373 value that would otherwise be returned and the cache equals ``run_with_cache(output)`` 

3374 with the effective prompt attention mask extended over the generated tokens. 

3375 If return_input_tokens=True, returns an ``(output, input_tokens)`` tuple. 

3376 If both return_cache and return_input_tokens are True, returns ``(output, cache, input_tokens)``. 

3377 

3378 Example: 

3379 ``out, cache = model.generate(prompt, max_new_tokens=20, return_cache=True)`` returns a 

3380 normal ActivationCache over the full prompt + generated sequence (equivalent to 

3381 ``run_with_cache(out)``). 

3382 

3383 ``out, input_tokens = model.generate(prompt, return_input_tokens=True)`` returns 

3384 the tokens that were fed to the model, useful for verifying BOS handling with 

3385 chat templates. 

3386 """ 

3387 self._ensure_generation_supported("generate") 

3388 # padding_side is handled internally: for batched list inputs, left-padding 

3389 # is forced to ensure correct generation. See _is_batched_list logic below. 

3390 

3391 # Stateful dispatch is decided after input parsing so we can fall back 

3392 # to hf_generate() for input types the stateful loop doesn't handle. 

3393 is_stateful_model = getattr(self.cfg, "is_stateful", False) 

3394 

3395 _is_batched_list = isinstance(input, list) and len(input) > 1 

3396 use_past_kv_cache = self._resolve_generation_caching(use_past_kv_cache, _is_batched_list) 

3397 

3398 _generate_from_embeds = False 

3399 _encdec_early = hasattr(self.original_model, "config") and getattr( 

3400 self.original_model.config, "is_encoder_decoder", False 

3401 ) 

3402 audio_decoder_prompt: Optional[torch.Tensor] = None 

3403 if getattr(self.cfg, "is_audio_seq2seq", False): 

3404 input_tokens, audio_decoder_prompt = self._audio_generation_inputs( 

3405 input, multimodal_kwargs, max_new_tokens 

3406 ) 

3407 input_type = "audio" 

3408 elif isinstance(input, str): 

3409 if _encdec_early: 

3410 # Deliberate divergence: prepend_bos is IGNORED for enc-dec 

3411 # string/list input. Encoder input follows the tokenizer's own 

3412 # recipe (lang token + trailing </s>); to_tokens' decoder-style 

3413 # BOS policy corrupts it — m2m100 degenerates to loops. 

3414 input_tokens = self.tokenizer(input, return_tensors="pt")["input_ids"].to( 

3415 self.cfg.device 

3416 ) 

3417 else: 

3418 input_tokens = self.to_tokens( 

3419 input, prepend_bos=prepend_bos, move_to_device=True, truncate=False 

3420 ) 

3421 input_type = "str" 

3422 elif isinstance(input, list): 

3423 if _encdec_early: 

3424 # Same native-recipe rule as the str branch: to_tokens' BOS 

3425 # policy corrupts encoder inputs (stray <s>, dropped </s>). 

3426 # Keep the tokenizer's mask too — unequal rows otherwise 

3427 # attend over pads in the encoder. 

3428 _enc_batch = self.tokenizer(input, return_tensors="pt", padding=True) 

3429 input_tokens = _enc_batch["input_ids"].to(self.cfg.device) 

3430 if attention_mask is None and "attention_mask" in _enc_batch: 3430 ↛ 3444line 3430 didn't jump to line 3444 because the condition on line 3430 was always true

3431 attention_mask = _enc_batch["attention_mask"].to(self.cfg.device) 

3432 else: 

3433 # Force left-padding for batched generation so real tokens are 

3434 # flush-right and logits[:, -1, :] is always the last real token. 

3435 # Passed as a kwarg rather than assigned: a raise between assignment 

3436 # and restore would pin the shared tokenizer left for the session. 

3437 input_tokens = self.to_tokens( 

3438 input, 

3439 prepend_bos=prepend_bos, 

3440 padding_side="left" if _is_batched_list else None, 

3441 move_to_device=True, 

3442 truncate=False, 

3443 ) 

3444 input_type = "list" 

3445 elif isinstance(input, torch.Tensor) and input.is_floating_point(): 

3446 # inputs_embeds: pre-computed embeddings (e.g., from multimodal models) 

3447 input_tokens = input.to(self.cfg.device) 

3448 input_type = "embeds" 

3449 _generate_from_embeds = True 

3450 else: 

3451 input_tokens = input.to(self.cfg.device) 

3452 input_type = "tokens" 

3453 

3454 # Without one of these a pre-padded tensor generates as though its pads were 

3455 # real context, shifting every real token's position (#1612). An explicit 

3456 # mask wins; otherwise the padding is read off the tokens, but only when the 

3457 # caller asked for that by passing padding_side. Deriving a mask on the 

3458 # default path would silently change behaviour for every existing caller, 

3459 # and would demand a real tokenizer where today none is required. 

3460 initial_attention_mask: Optional[torch.Tensor] = attention_mask 

3461 if initial_attention_mask is not None and ( 

3462 _generate_from_embeds 

3463 or getattr(getattr(self.original_model, "config", None), "is_encoder_decoder", False) 

3464 ): 

3465 # Growing the mask per step only means something for decoder-only token 

3466 # generation. On these paths the mask used to arrive via 

3467 # **multimodal_kwargs and be forwarded to the model untouched — as 

3468 # processors emit it alongside pixel_values — so keep doing that rather 

3469 # than reject a call that worked before this parameter existed. 

3470 multimodal_kwargs = {**multimodal_kwargs, "attention_mask": initial_attention_mask} 

3471 initial_attention_mask = None 

3472 if initial_attention_mask is not None: 

3473 if initial_attention_mask.shape != input_tokens.shape: 

3474 raise ValueError( 

3475 f"attention_mask shape {tuple(initial_attention_mask.shape)} does not " 

3476 f"match the prompt shape {tuple(input_tokens.shape)}. Pass a 0/1 mask " 

3477 "covering exactly the prompt tokens; generate() extends it itself." 

3478 ) 

3479 initial_attention_mask = initial_attention_mask.to(self.cfg.device) 

3480 elif padding_side is not None and input_type == "tokens": 

3481 # Reading the padding off the tokens needs a tokenizer with a pad id. 

3482 # Without one the argument would be inert, leaving exactly the bug this 

3483 # fixes — silently, on a bridge booted without a tokenizer. Say so 

3484 # rather than generate something quietly wrong. 

3485 if not isinstance(self.tokenizer, PreTrainedTokenizerBase): 

3486 raise ValueError( 

3487 "generate(padding_side=...) reads the padding off the pad token, " 

3488 "which needs a tokenizer; this bridge has none. Pass " 

3489 "attention_mask=... to state the padding directly instead." 

3490 ) 

3491 if self.tokenizer.pad_token_id is None: 

3492 raise ValueError( 

3493 "generate(padding_side=...) reads the padding off the pad token, " 

3494 "but this tokenizer has no pad_token_id. Set one, or pass " 

3495 "attention_mask=... to state the padding directly instead." 

3496 ) 

3497 _prepend = self.cfg.default_prepend_bos if prepend_bos is None else prepend_bos 

3498 _orig_side = self.tokenizer.padding_side 

3499 self.tokenizer.padding_side = padding_side 

3500 try: 

3501 initial_attention_mask = utils.get_attention_mask( 

3502 self.tokenizer, input_tokens, _prepend 

3503 ).to(self.cfg.device) 

3504 finally: 

3505 self.tokenizer.padding_side = _orig_side 

3506 # An all-ones mask is what the model assumes anyway; skipping it keeps 

3507 # the unpadded path byte-identical to before. 

3508 if initial_attention_mask is not None and bool(initial_attention_mask.all()): 3508 ↛ 3509line 3508 didn't jump to line 3509 because the condition on line 3508 was never true

3509 initial_attention_mask = None 

3510 

3511 # Determine return type 

3512 if return_type == "input": 

3513 if input_type in ["str", "list"]: 

3514 return_type = "str" 

3515 elif input_type == "embeds": 

3516 return_type = "tokens" 

3517 else: 

3518 return_type = "tokens" 

3519 

3520 batch_size = input_tokens.shape[0] 

3521 

3522 # Setup EOS token handling 

3523 stop_tokens = [] 

3524 eos_token_for_padding = 0 

3525 if stop_at_eos: 

3526 tokenizer_has_eos_token = ( 

3527 self.tokenizer is not None and self.tokenizer.eos_token_id is not None 

3528 ) 

3529 if eos_token_id is None: 

3530 # Some chat models use a turn-end token that differs from the 

3531 # tokenizer's primary EOS. Let adapters provide the full stop 

3532 # set via cfg.eos_token_id; otherwise fall back to the tokenizer. 

3533 eos_token_id = getattr(self.cfg, "eos_token_id", None) 

3534 if eos_token_id is None: 

3535 assert ( 

3536 tokenizer_has_eos_token 

3537 ), "Must pass eos_token_id if stop_at_eos is True and tokenizer is None or has no eos_token_id" 

3538 assert self.tokenizer is not None 

3539 eos_token_id = self.tokenizer.eos_token_id 

3540 

3541 if isinstance(eos_token_id, int): 

3542 stop_tokens = [eos_token_id] 

3543 eos_token_for_padding = eos_token_id 

3544 else: 

3545 stop_tokens = list(eos_token_id) 

3546 if tokenizer_has_eos_token: 

3547 assert self.tokenizer is not None 

3548 eos_token_for_padding = self.tokenizer.eos_token_id 

3549 else: 

3550 eos_token_for_padding = eos_token_id[0] 

3551 

3552 # Track which sequences have finished 

3553 finished_sequences = torch.zeros(batch_size, dtype=torch.bool, device=self.cfg.device) 

3554 

3555 # Optionally collect logits at each generation step for downstream tooling/tests 

3556 logits_seq_list: list[torch.Tensor] | None = [] if output_logits else None 

3557 

3558 # Detect encoder-decoder models (T5, BART, etc.) 

3559 is_encoder_decoder = hasattr(self.original_model, "config") and getattr( 

3560 self.original_model.config, "is_encoder_decoder", False 

3561 ) 

3562 if forced_bos_token_id is not None and not is_encoder_decoder: 3562 ↛ 3565line 3562 didn't jump to line 3565 because the condition on line 3562 was never true

3563 # Raise before any state mutation (_capture_hf_cache) and before 

3564 # the stateful hf_generate early-return would drop the kwarg. 

3565 raise ValueError("forced_bos_token_id is only meaningful for encoder-decoder models") 

3566 

3567 # return_cache recomputes run_with_cache on the generated output (see issue #697). 

3568 # That is well-defined only for single-sequence, decoder-only text generation, so 

3569 # reject the paths whose cache would be wrong/undefined, with a clear pointer to the 

3570 # run_with_cache workaround. Fail fast here, before any generation work. 

3571 if return_cache: 

3572 if is_encoder_decoder: 3572 ↛ 3573line 3572 didn't jump to line 3573 because the condition on line 3572 was never true

3573 raise NotImplementedError( 

3574 "generate(return_cache=True) is not supported for encoder-decoder " 

3575 "models yet. Run run_with_cache on the generated output instead." 

3576 ) 

3577 if is_stateful_model: 3577 ↛ 3578line 3577 didn't jump to line 3578 because the condition on line 3577 was never true

3578 raise NotImplementedError( 

3579 "generate(return_cache=True) is not supported for stateful/SSM models " 

3580 "(e.g. Mamba); they do not expose standard transformer hook points." 

3581 ) 

3582 if pixel_values is not None or multimodal_kwargs: 3582 ↛ 3583line 3582 didn't jump to line 3583 because the condition on line 3582 was never true

3583 raise NotImplementedError( 

3584 "generate(return_cache=True) is not supported for multimodal generation " 

3585 "yet. Run run_with_cache on the generated output instead." 

3586 ) 

3587 if _generate_from_embeds: 

3588 raise NotImplementedError( 

3589 "generate(return_cache=True) requires token input, not inputs_embeds." 

3590 ) 

3591 if batch_size > 1: 

3592 raise NotImplementedError( 

3593 "generate(return_cache=True) is not supported for batched/multi-prompt " 

3594 "generation yet. Pass a single prompt, or run run_with_cache on each " 

3595 "output sequence." 

3596 ) 

3597 

3598 # HF cache flows opaquely through the component chain via 

3599 # _reconstruct_attention() → _update_kv_cache() on each layer. 

3600 _hf_kv_cache = None 

3601 if use_past_kv_cache and is_encoder_decoder: 

3602 # Encoder-decoder models (T5, BART) don't support the opaque 

3603 # cache path — silently disable rather than crash, since 

3604 # use_past_kv_cache=True is the default. 

3605 use_past_kv_cache = False 

3606 

3607 # SSMs (Mamba/Mamba-2) run through a dedicated cache path so hooks 

3608 # fire on every step. Unsupported input types fall back to hf_generate(). 

3609 use_stateful_cache = ( 

3610 is_stateful_model 

3611 and use_past_kv_cache 

3612 and not is_encoder_decoder 

3613 and not _generate_from_embeds 

3614 and pixel_values is None 

3615 and not multimodal_kwargs 

3616 ) 

3617 

3618 # stop_strings / stopping_criteria are applied inside the hooked _generate_tokens 

3619 # loop, so they are supported only on the standard decoder-only text path. Reject 

3620 # the paths that route around that loop with a clear error rather than silently 

3621 # dropping the kwargs. This must run before the stateful delegation below. 

3622 stopping_criteria_list = self._resolve_stopping_criteria(stop_strings, stopping_criteria) 

3623 if stopping_criteria_list is not None: 

3624 if is_encoder_decoder: 

3625 _unsupported = "encoder-decoder models" 

3626 elif _generate_from_embeds: 

3627 _unsupported = "inputs_embeds generation" 

3628 elif pixel_values is not None or multimodal_kwargs: 

3629 _unsupported = "multimodal (pixel_values) generation" 

3630 else: 

3631 _unsupported = None 

3632 if _unsupported is not None: 

3633 raise NotImplementedError( 

3634 f"stop_strings/stopping_criteria are not supported for {_unsupported} in " 

3635 "TransformerBridge.generate(). Call hf_generate(...), which runs " 

3636 "HuggingFace's own generation loop and supports HF-native stopping on " 

3637 "those inputs." 

3638 ) 

3639 if is_stateful_model and not use_stateful_cache: 

3640 # Reached only for a stateful/SSM model with use_past_kv_cache=False: the 

3641 # hooked loop needs the stateful cache, so generate() would otherwise fall 

3642 # back to hf_generate() and drop these kwargs. The default cache setting 

3643 # keeps generation on the hooked loop, where stopping is applied. 

3644 raise NotImplementedError( 

3645 "stop_strings/stopping_criteria on a stateful/SSM model require the " 

3646 "stateful cache path, which runs only with use_past_kv_cache=True (the " 

3647 "default). With use_past_kv_cache=False generate() falls back to " 

3648 "hf_generate(). Set use_past_kv_cache=True to keep stopping on the hooked " 

3649 "loop, or call hf_generate(...) directly for HF-native stopping." 

3650 ) 

3651 # Finished rows are overwritten with this id so they stop emitting real tokens 

3652 # while the rest of a batch keeps going. stop_at_eos already set a sensible 

3653 # value, otherwise fall back to the tokenizer pad/eos id. (For a single 

3654 # sequence this id is never read: the loop exits when the row finishes.) 

3655 if not stop_at_eos: 

3656 _pad_id = None 

3657 if self.tokenizer is not None: 

3658 _pad_id = ( 

3659 self.tokenizer.pad_token_id 

3660 if self.tokenizer.pad_token_id is not None 

3661 else self.tokenizer.eos_token_id 

3662 ) 

3663 if _pad_id is not None: 

3664 eos_token_for_padding = _pad_id 

3665 elif batch_size > 1: 

3666 raise ValueError( 

3667 "Batched generation with stopping_criteria and stop_at_eos=False " 

3668 "needs a padding token to freeze finished rows, but no tokenizer " 

3669 "pad/eos id is available. Set stop_at_eos=True, use a tokenizer with " 

3670 "a pad or eos token, or generate one sequence at a time." 

3671 ) 

3672 

3673 if is_stateful_model and not use_stateful_cache: 

3674 if freq_penalty != 0.0: 

3675 # Only use_past_kv_cache=False is fixable by the caller; the other 

3676 # fallback triggers persist with the flag already set. 

3677 if is_encoder_decoder: 3677 ↛ 3678line 3677 didn't jump to line 3678 because the condition on line 3677 was never true

3678 _fallback_cause = "encoder-decoder models" 

3679 elif _generate_from_embeds: 

3680 _fallback_cause = "inputs_embeds generation" 

3681 elif pixel_values is not None or multimodal_kwargs: 

3682 _fallback_cause = "multimodal (pixel_values or extra model kwargs) generation" 

3683 else: 

3684 _fallback_cause = None 

3685 if _fallback_cause is not None: 

3686 raise NotImplementedError( 

3687 f"freq_penalty is not supported for {_fallback_cause} on a " 

3688 "stateful/SSM model: generate() falls back to hf_generate(), which " 

3689 "has no equivalent frequency penalty. Drop freq_penalty or use " 

3690 "repetition_penalty, which the fallback forwards." 

3691 ) 

3692 raise NotImplementedError( 

3693 "freq_penalty requires use_past_kv_cache=True for stateful/SSM models. " 

3694 "The HF generation fallback has no equivalent frequency penalty." 

3695 ) 

3696 hf_kwargs: dict[str, Any] = { 

3697 "max_new_tokens": max_new_tokens, 

3698 "do_sample": do_sample, 

3699 "temperature": temperature, 

3700 "repetition_penalty": repetition_penalty, 

3701 # hf_generate defaults this to True, so omitting it would make 

3702 # generate(stop_at_eos=False) silently stop at EOS on this path. 

3703 "stop_at_eos": stop_at_eos, 

3704 } 

3705 if top_k is not None: 3705 ↛ 3706line 3705 didn't jump to line 3706 because the condition on line 3705 was never true

3706 hf_kwargs["top_k"] = top_k 

3707 if top_p is not None: 3707 ↛ 3708line 3707 didn't jump to line 3708 because the condition on line 3707 was never true

3708 hf_kwargs["top_p"] = top_p 

3709 if eos_token_id is not None: 

3710 hf_kwargs["eos_token_id"] = eos_token_id 

3711 # generate() already derived and shape-validated this mask; dropping it here 

3712 # would let the model attend to pad positions on the stateful fallback. 

3713 if initial_attention_mask is not None: 

3714 hf_kwargs["attention_mask"] = initial_attention_mask 

3715 return self.hf_generate(input, **hf_kwargs) 

3716 

3717 # SSM cache is built once and mutated in place across forward calls. 

3718 # Adapter owns the cache-type choice; new SSMs just override 

3719 # create_stateful_cache(). 

3720 mamba_cache: Any = None 

3721 mamba_conv_kernel: int = 0 

3722 if use_stateful_cache: 

3723 hf_model: Any = self.original_model 

3724 mamba_conv_kernel = int(getattr(hf_model.config, "conv_kernel", 4)) 

3725 cache_dtype = self.cfg.dtype or torch.float32 

3726 mamba_cache = self.adapter.create_stateful_cache( 

3727 hf_model=hf_model, 

3728 batch_size=batch_size, 

3729 device=self.cfg.device, 

3730 dtype=cache_dtype, 

3731 ) 

3732 

3733 if use_past_kv_cache and not use_stateful_cache: 

3734 self._capture_hf_cache = True # Signal forward() to stash cache 

3735 

3736 # Generate tokens 

3737 current_tokens = input_tokens.clone() 

3738 # For inputs_embeds generation, also track generated token IDs for decoding 

3739 if _generate_from_embeds: 

3740 generated_token_ids: list[torch.Tensor] = [] 

3741 sampled_tokens_list = [] 

3742 

3743 # For encoder-decoder models, keep encoder input fixed and grow decoder input 

3744 min_decoder_length = None 

3745 suppress_processors: list[Any] = [] 

3746 audio_encoder_outputs = None 

3747 if is_encoder_decoder: 

3748 encoder_input = input_tokens.clone() 

3749 decoder_tokens, min_decoder_length = self._encoder_decoder_setup( 

3750 input_tokens, forced_bos_token_id, decoder_prompt=audio_decoder_prompt 

3751 ) 

3752 suppress_processors = self._encdec_suppress_processors(decoder_tokens.shape[1]) 

3753 if audio_decoder_prompt is not None: 

3754 # Encode the audio once, as HF's generate does: re-encoding every frame 

3755 # for each new token dominates the cost. Encoder hooks fire on this pass. 

3756 # output_attentions=False stops HF from holding every layer's 

3757 # [frames, frames] attention weights until the pass ends; the bridge's 

3758 # attention hooks capture their patterns regardless. 

3759 with torch.no_grad(): 

3760 encoder = getattr(self.original_model, "get_encoder")() 

3761 audio_encoder_outputs = encoder( 

3762 **{self.adapter.audio_input_name: encoder_input}, 

3763 output_attentions=False, 

3764 ) 

3765 

3766 try: 

3767 for sampled_tokens, raw_logits, all_finished in self._generate_tokens( 

3768 current_tokens, 

3769 input_tokens, 

3770 batch_size, 

3771 max_new_tokens=max_new_tokens, 

3772 do_sample=do_sample, 

3773 top_k=top_k, 

3774 top_p=top_p, 

3775 temperature=temperature, 

3776 freq_penalty=freq_penalty, 

3777 repetition_penalty=repetition_penalty, 

3778 stop_at_eos=stop_at_eos, 

3779 stop_tokens=stop_tokens, 

3780 eos_token_for_padding=eos_token_for_padding, 

3781 finished_sequences=finished_sequences, 

3782 use_past_kv_cache=use_past_kv_cache, 

3783 use_stateful_cache=use_stateful_cache, 

3784 mamba_cache=mamba_cache, 

3785 mamba_conv_kernel=mamba_conv_kernel, 

3786 is_encoder_decoder=is_encoder_decoder, 

3787 batched_prompt_mask=( 

3788 self._left_padded_prompt_mask(input, input_tokens, prepend_bos) 

3789 if _is_batched_list 

3790 and isinstance(input, list) 

3791 and not is_encoder_decoder 

3792 and initial_attention_mask is None 

3793 else None 

3794 ), 

3795 _generate_from_embeds=_generate_from_embeds, 

3796 encoder_input=encoder_input if is_encoder_decoder else None, 

3797 decoder_tokens=decoder_tokens if is_encoder_decoder else None, 

3798 generated_token_ids=generated_token_ids if _generate_from_embeds else None, 

3799 pixel_values=pixel_values, 

3800 multimodal_kwargs=multimodal_kwargs if multimodal_kwargs else {}, 

3801 verbose=verbose, 

3802 stopping_criteria_list=stopping_criteria_list, 

3803 initial_attention_mask=initial_attention_mask, 

3804 min_decoder_length=min_decoder_length, 

3805 ngram_processor=(self._encdec_ngram_processor() if is_encoder_decoder else None), 

3806 encoder_attention_mask=(attention_mask if is_encoder_decoder else None), 

3807 forced_eos_token_id=( 

3808 self._encdec_forced_eos_token_id() if is_encoder_decoder else None 

3809 ), 

3810 suppress_processors=suppress_processors, 

3811 encoder_outputs=audio_encoder_outputs, 

3812 ): 

3813 sampled_tokens_list.append(sampled_tokens.unsqueeze(1)) 

3814 if logits_seq_list is not None: 

3815 logits_seq_list.append(raw_logits.clone()) 

3816 if all_finished: 

3817 break 

3818 finally: 

3819 self._capture_hf_cache = False 

3820 if hasattr(self, "_last_hf_cache"): 3820 ↛ 3821line 3820 didn't jump to line 3821 because the condition on line 3820 was never true

3821 del self._last_hf_cache 

3822 

3823 sampled_tokens = torch.cat(sampled_tokens_list, dim=1) 

3824 if is_encoder_decoder: 

3825 # Reconstruct full decoder sequence: start token + generated tokens 

3826 output_tokens = torch.cat([decoder_tokens, sampled_tokens], dim=1) 

3827 elif _generate_from_embeds: 

3828 # For inputs_embeds, we only have the generated token IDs (no input token IDs) 

3829 output_tokens = sampled_tokens 

3830 else: 

3831 output_tokens = torch.cat([input_tokens, sampled_tokens], dim=1) 

3832 

3833 # Build the formatted output (shape unchanged: ModelOutput / str / list[str] / tokens). 

3834 result: Any 

3835 if output_logits and logits_seq_list is not None: 

3836 from transformers.utils import ModelOutput # type: ignore 

3837 

3838 def _logits_to_tuple(logits_list: list[torch.Tensor]) -> tuple[torch.Tensor, ...]: 

3839 assert logits_list is not None 

3840 # Convert list of [batch, vocab] tensors to tuple 

3841 return tuple(logits_list) 

3842 

3843 try: 

3844 from transformers.generation.utils import GenerateDecoderOnlyOutput 

3845 

3846 # HF-compatible ModelOutput structure. 

3847 # GenerateDecoderOnlyOutput expects: sequences, scores (optional), logits (optional) 

3848 result = GenerateDecoderOnlyOutput( 

3849 sequences=cast(torch.LongTensor, output_tokens), 

3850 # HF's type hint says tuple[FloatTensor] but should be tuple[FloatTensor, ...] 

3851 # (variable-length tuple with one element per generated token) 

3852 logits=_logits_to_tuple(logits_seq_list), # type: ignore[arg-type] 

3853 ) 

3854 except (ImportError, AttributeError): 

3855 # Fallback if GenerateDecoderOnlyOutput not available in this transformers version 

3856 result = ModelOutput( 

3857 sequences=output_tokens, 

3858 logits=_logits_to_tuple(logits_seq_list), 

3859 ) 

3860 elif return_type == "str": 

3861 assert self.tokenizer is not None 

3862 if input_type == "str": 

3863 result = self.tokenizer.decode(output_tokens[0], skip_special_tokens=True) 

3864 else: 

3865 decoded_texts = [ 

3866 self.tokenizer.decode(tokens, skip_special_tokens=True) 

3867 for tokens in output_tokens 

3868 ] 

3869 result = decoded_texts[0] if len(decoded_texts) == 1 else decoded_texts 

3870 else: # return_type == "tokens" 

3871 result = output_tokens 

3872 

3873 if not return_cache and not return_input_tokens: 

3874 return result 

3875 

3876 if return_cache: 

3877 # Replay the loop's final mask so the cache sees the context and positions 

3878 # generation did. 

3879 _, cache = self.run_with_cache( 

3880 output_tokens, 

3881 names_filter=names_filter, 

3882 device=device, 

3883 attention_mask=( 

3884 _extend_prompt_attention_mask(initial_attention_mask, output_tokens) 

3885 if initial_attention_mask is not None 

3886 else None 

3887 ), 

3888 ) 

3889 if return_input_tokens: 

3890 return result, cache, input_tokens 

3891 return result, cache 

3892 

3893 # return_input_tokens only (no cache) 

3894 return result, input_tokens 

3895 

3896 @torch.no_grad() 

3897 def diffusion_generate( 

3898 self, 

3899 input: Union[str, List[str], torch.Tensor], 

3900 max_new_tokens: int = 32, 

3901 prepend_bos: Optional[bool] = None, 

3902 **kwargs: Any, 

3903 ) -> Union[str, torch.Tensor]: 

3904 """Sample from a non-autoregressive (diffusion) architecture. 

3905 

3906 Delegates to the model's own sampler, which calls the model through 

3907 ``__call__`` so bridge hooks fire on every denoising step. 

3908 """ 

3909 sampler_name = getattr(self.adapter, "native_sampler", None) 

3910 architecture = self.cfg.architecture or type(self.adapter).__name__ 

3911 if sampler_name is None: 3911 ↛ 3912line 3911 didn't jump to line 3912 because the condition on line 3911 was never true

3912 raise NotImplementedError( 

3913 f"{architecture} has no native sampler; use generate() for autoregressive " 

3914 "architectures." 

3915 ) 

3916 sampler = getattr(self.original_model, sampler_name, None) 

3917 if sampler is None: 3917 ↛ 3918line 3917 didn't jump to line 3918 because the condition on line 3917 was never true

3918 raise NotImplementedError( 

3919 f"{architecture} declares native_sampler={sampler_name!r} but the loaded model " 

3920 "has no such method." 

3921 ) 

3922 

3923 was_string = isinstance(input, str) 

3924 if isinstance(input, list) and len(input) > 1: 3924 ↛ 3928line 3924 didn't jump to line 3928 because the condition on line 3924 was never true

3925 # Unequal prompts would be right-padded into the sampler's canvas, 

3926 # where pad tokens read as real context. generate() gates batching 

3927 # for the same reason; do not silently corrupt rows here. 

3928 raise NotImplementedError( 

3929 f"diffusion_generate() does not support batched prompts for {architecture}: " 

3930 "the native samplers condition on a padded canvas. Sample one prompt at a time." 

3931 ) 

3932 if isinstance(input, torch.Tensor): 3932 ↛ 3937line 3932 didn't jump to line 3937 because the condition on line 3932 was always true

3933 tokens = input.to(self.cfg.device) 

3934 else: 

3935 # Tokenization is the bridge's concern, not the sampler's — absorb 

3936 # prepend_bos here rather than forwarding it into native kwargs. 

3937 tokens = self.to_tokens( 

3938 input, prepend_bos=prepend_bos, move_to_device=True, truncate=False 

3939 ) 

3940 

3941 sampler_kwargs = self.adapter.native_sampler_kwargs(max_new_tokens, tokens.shape[-1]) 

3942 sampler_kwargs.update(kwargs) 

3943 output = sampler(tokens, **sampler_kwargs) 

3944 # Samplers return either bare ids or a generation output object. 

3945 sequences = getattr(output, "sequences", output) 

3946 # They also disagree on whether the prompt is included: Dream and Gidd 

3947 # return the whole canvas, LLaDA2 slices it off. Normalize to 

3948 # generate()'s contract (prompt + continuation). 

3949 if isinstance(sequences, torch.Tensor) and sequences.ndim == tokens.ndim: 3949 ↛ 3960line 3949 didn't jump to line 3960 because the condition on line 3949 was always true

3950 prompt_len = tokens.shape[-1] 

3951 # Compare on one device: torch.equal raises on a device mismatch, 

3952 # which some samplers produce by assembling output on CPU. 

3953 sequences = sequences.to(tokens.device) 

3954 includes_prompt = sequences.shape[-1] >= prompt_len and torch.equal( 

3955 sequences[..., :prompt_len], tokens 

3956 ) 

3957 if not includes_prompt: 

3958 sequences = torch.cat([tokens, sequences], dim=-1) 

3959 

3960 if was_string and self.tokenizer is not None: 3960 ↛ 3961line 3960 didn't jump to line 3961 because the condition on line 3960 was never true

3961 return self.tokenizer.decode(sequences[0], skip_special_tokens=True) 

3962 return sequences 

3963 

3964 @torch.no_grad() 

3965 def generate_stream( 

3966 self, 

3967 input: Union[str, List[str], torch.Tensor] = "", 

3968 max_new_tokens: int = 10, 

3969 max_tokens_per_yield: int = 25, 

3970 stop_at_eos: bool = True, 

3971 eos_token_id: Optional[int] = None, 

3972 do_sample: bool = True, 

3973 top_k: Optional[int] = None, 

3974 top_p: Optional[float] = None, 

3975 temperature: float = 1.0, 

3976 freq_penalty: float = 0.0, 

3977 repetition_penalty: float = 1.0, 

3978 use_past_kv_cache: bool = True, 

3979 prepend_bos: Optional[bool] = None, 

3980 padding_side: Optional[str] = None, 

3981 return_type: Optional[str] = "input", 

3982 verbose: bool = True, 

3983 stop_strings: Optional[Union[str, List[str]]] = None, 

3984 stopping_criteria: Optional[Any] = None, 

3985 attention_mask: Optional[torch.Tensor] = None, 

3986 forced_bos_token_id: Optional[int] = None, 

3987 ) -> Generator[Union[torch.Tensor, str, List[str]], None, None]: 

3988 """Stream tokens from the model as they are generated. 

3989 

3990 Yields batches of tokens progressively during generation rather than 

3991 waiting for the entire sequence. Uses the same core loop as generate(). 

3992 

3993 Args: 

3994 input: Text string, list of strings, or tensor of tokens. 

3995 max_new_tokens: Maximum number of tokens to generate. 

3996 max_tokens_per_yield: Yield accumulated tokens every this many steps. 

3997 stop_at_eos: If True, stop when eos_token is produced. 

3998 eos_token_id: Token ID(s) for end of sentence. Defaults to tokenizer's. 

3999 do_sample: If True, sample; otherwise greedy. 

4000 top_k: Top-k sampling. None means no filtering. 

4001 top_p: Nucleus sampling threshold. 

4002 temperature: Sampling temperature. 

4003 freq_penalty: Non-negative frequency penalty for previous tokens (applied only 

4004 when do_sample=True; negative values raise ValueError). 

4005 repetition_penalty: HF-style repetition penalty (>1.0 discourages repeats). 

4006 use_past_kv_cache: Use KV caching for faster generation. 

4007 prepend_bos: Whether to prepend a BOS token when tokenizing string inputs. 

4008 Defaults to None (uses ``cfg.default_prepend_bos``, typically True). 

4009 Pass ``prepend_bos=False`` when the input is pre-formatted chat-template 

4010 text that already contains the BOS token to avoid double-BOS. 

4011 Ignored when input is already a token tensor. 

4012 padding_side: Which side to pad for batched list inputs. Left-padding 

4013 is forced internally for batched generation. 

4014 return_type: 'input' (match input type), 'str', or 'tokens'. 

4015 verbose: Show progress bar. 

4016 stop_strings: Optional string or list of strings. A sequence stops once its 

4017 generated text ends with one of them (HF StopStringCriteria). Requires a 

4018 tokenizer. See generate() for details. 

4019 stopping_criteria: Optional transformers StoppingCriteria, list, or 

4020 StoppingCriteriaList, called as criterion(input_ids, scores) each step 

4021 (scores is the step's logits). See generate() for the full contract. 

4022 attention_mask: Optional ``[batch, pos]`` 0/1 mask over the prompt, 

4023 required to generate correctly from an already-padded token tensor. 

4024 Extended by one attended column per generated token on decoder-only 

4025 models; forwarded to the encoder as-is on encoder-decoder models. 

4026 See generate() for the full contract. 

4027 forced_bos_token_id: Optional token id seeded as the first decoder token 

4028 after ``decoder_start`` on encoder-decoder models, overriding any 

4029 generation_config default. Raises ValueError on decoder-only models. 

4030 

4031 Yields: 

4032 Token tensors [batch, seq_len], or decoded text when return_type='str' - 

4033 a bare string for a single sequence and one string per batch row for a 

4034 larger batch, matching generate(). Chunks accumulate up to 

4035 max_tokens_per_yield tokens between yields; the first yield includes the 

4036 input tokens and subsequent yields contain only new tokens. For encoder-decoder 

4037 models, the first yield includes the decoder start token (and configured 

4038 forced BOS token), not the encoder input. Encoder-decoder streaming uses 

4039 the uncached loop, as generate() does; custom stopping criteria are unsupported. 

4040 """ 

4041 self._ensure_generation_supported("generate_stream") 

4042 if getattr(self.cfg, "is_audio_seq2seq", False): 

4043 raise NotImplementedError( 

4044 "generate_stream() is not supported for audio seq2seq models yet; use " 

4045 "generate(input_features, decoder_input=...) instead." 

4046 ) 

4047 # --- Input parsing (mirrors generate()) --- 

4048 _is_batched_list = isinstance(input, list) and len(input) > 1 

4049 use_past_kv_cache = self._resolve_generation_caching(use_past_kv_cache, _is_batched_list) 

4050 

4051 _encdec_early = hasattr(self.original_model, "config") and getattr( 

4052 self.original_model.config, "is_encoder_decoder", False 

4053 ) 

4054 encoder_attention_mask = None 

4055 if _encdec_early: 

4056 use_past_kv_cache = False 

4057 if isinstance(input, str): 

4058 if _encdec_early: 

4059 # Native recipe: to_tokens' BOS policy corrupts encoder inputs. 

4060 encoded = self.tokenizer(input, return_tensors="pt") 

4061 input_tokens = encoded["input_ids"].to(self.cfg.device) 

4062 encoder_attention_mask = encoded.get("attention_mask") 

4063 else: 

4064 input_tokens = self.to_tokens( 

4065 input, prepend_bos=prepend_bos, move_to_device=True, truncate=False 

4066 ) 

4067 input_type = "str" 

4068 elif isinstance(input, list): 

4069 if _encdec_early: 

4070 encoded = self.tokenizer(input, return_tensors="pt", padding=True) 

4071 input_tokens = encoded["input_ids"].to(self.cfg.device) 

4072 encoder_attention_mask = encoded.get("attention_mask") 

4073 else: 

4074 # Pass the side as a kwarg, as generate() does, instead of mutating the tokenizer. 

4075 input_tokens = self.to_tokens( 

4076 input, 

4077 prepend_bos=prepend_bos, 

4078 padding_side="left" if _is_batched_list else None, 

4079 move_to_device=True, 

4080 truncate=False, 

4081 ) 

4082 input_type = "list" 

4083 else: 

4084 input_tokens = input.to(self.cfg.device) 

4085 input_type = "tokens" 

4086 

4087 if return_type == "input": 

4088 return_type = "str" if input_type in ["str", "list"] else "tokens" 

4089 

4090 if forced_bos_token_id is not None and not _encdec_early: 

4091 raise ValueError("forced_bos_token_id is only meaningful for encoder-decoder models") 

4092 

4093 # An explicit mask wins over any tokenizer-derived one (mirrors generate()): 

4094 # the encoder consumes it as-is, a decoder-only prompt mask is grown per step. 

4095 initial_attention_mask: Optional[torch.Tensor] = None 

4096 if attention_mask is not None: 

4097 if _encdec_early: 

4098 encoder_attention_mask = attention_mask 

4099 else: 

4100 if attention_mask.shape != input_tokens.shape: 

4101 raise ValueError( 

4102 f"attention_mask shape {tuple(attention_mask.shape)} does not " 

4103 f"match the prompt shape {tuple(input_tokens.shape)}. Pass a 0/1 " 

4104 "mask covering exactly the prompt tokens; generate_stream() " 

4105 "extends it itself." 

4106 ) 

4107 initial_attention_mask = attention_mask.to(self.cfg.device) 

4108 

4109 batch_size = input_tokens.shape[0] 

4110 

4111 # --- EOS setup --- 

4112 stop_tokens: List[int] = [] 

4113 eos_token_for_padding = 0 

4114 if stop_at_eos: 

4115 tokenizer_has_eos_token = ( 

4116 self.tokenizer is not None and self.tokenizer.eos_token_id is not None 

4117 ) 

4118 if eos_token_id is None: 

4119 # Some chat models use a turn-end token that differs from the 

4120 # tokenizer's primary EOS. Let adapters provide the full stop 

4121 # set via cfg.eos_token_id; otherwise fall back to the tokenizer. 

4122 eos_token_id = getattr(self.cfg, "eos_token_id", None) 

4123 if eos_token_id is None: 

4124 assert ( 

4125 tokenizer_has_eos_token 

4126 ), "Must pass eos_token_id if stop_at_eos is True and tokenizer is None or has no eos_token_id" 

4127 assert self.tokenizer is not None 

4128 eos_token_id = self.tokenizer.eos_token_id 

4129 if isinstance(eos_token_id, int): 

4130 stop_tokens = [eos_token_id] 

4131 eos_token_for_padding = eos_token_id 

4132 else: 

4133 stop_tokens = list(eos_token_id) 

4134 if tokenizer_has_eos_token: 4134 ↛ 4135line 4134 didn't jump to line 4135 because the condition on line 4134 was never true

4135 assert self.tokenizer is not None 

4136 eos_token_for_padding = self.tokenizer.eos_token_id 

4137 else: 

4138 eos_token_for_padding = eos_token_id[0] 

4139 

4140 finished_sequences = torch.zeros(batch_size, dtype=torch.bool, device=self.cfg.device) 

4141 

4142 stopping_criteria_list = self._resolve_stopping_criteria(stop_strings, stopping_criteria) 

4143 if _encdec_early and stopping_criteria_list is not None: 

4144 raise NotImplementedError( 

4145 "stop_strings/stopping_criteria are not supported for encoder-decoder " 

4146 "generation in TransformerBridge.generate_stream(). Call hf_generate(...) " 

4147 "for HF-native stopping on those inputs." 

4148 ) 

4149 if stopping_criteria_list is not None and not stop_at_eos: 

4150 _pad_id = None 

4151 if self.tokenizer is not None: 

4152 _pad_id = ( 

4153 self.tokenizer.pad_token_id 

4154 if self.tokenizer.pad_token_id is not None 

4155 else self.tokenizer.eos_token_id 

4156 ) 

4157 if _pad_id is not None: 

4158 eos_token_for_padding = _pad_id 

4159 elif batch_size > 1: 4159 ↛ 4168line 4159 didn't jump to line 4168 because the condition on line 4159 was always true

4160 raise ValueError( 

4161 "Batched generate_stream with stopping_criteria and stop_at_eos=False " 

4162 "needs a padding token to freeze finished rows, but no tokenizer pad/eos " 

4163 "id is available. Set stop_at_eos=True or use a tokenizer with a pad/eos " 

4164 "token." 

4165 ) 

4166 

4167 # --- Cache setup --- 

4168 if use_past_kv_cache: 

4169 self._capture_hf_cache = True 

4170 

4171 current_tokens = input_tokens.clone() 

4172 encoder_input = input_tokens if _encdec_early else None 

4173 decoder_tokens = None 

4174 stream_prefix = input_tokens 

4175 min_decoder_length = None 

4176 if _encdec_early: 

4177 decoder_tokens, min_decoder_length = self._encoder_decoder_setup( 

4178 input_tokens, forced_bos_token_id 

4179 ) 

4180 stream_prefix = decoder_tokens 

4181 

4182 # --- Streaming loop --- 

4183 # All yields are token tensors [batch, seq_len]. Each yield contains 

4184 # only the newly generated tokens since the previous yield (the first 

4185 # yield additionally prepends the input tokens for context). 

4186 accumulated_tokens: Optional[torch.Tensor] = None 

4187 tokens_since_last_yield = 0 

4188 

4189 # Decoding each chunk alone splits any character whose bytes straddle a yield 

4190 # boundary into U+FFFD, and concatenating chunks cannot rebuild it. Decode the 

4191 # whole stream each time, emit only the new text, and hold back a trailing 

4192 # incomplete character until the tokens that finish it arrive. 

4193 decoded_history: Optional[torch.Tensor] = None 

4194 emitted_chars = [0] * batch_size 

4195 

4196 def _decode_delta(hold_incomplete: bool) -> List[str]: 

4197 assert self.tokenizer is not None and decoded_history is not None 

4198 deltas = [] 

4199 for row_idx, row in enumerate(decoded_history): 

4200 text = self.tokenizer.decode(row, skip_special_tokens=True) 

4201 if hold_incomplete: 

4202 text = text.rstrip("�") 

4203 deltas.append(text[emitted_chars[row_idx] :]) 

4204 emitted_chars[row_idx] = len(text) 

4205 return deltas 

4206 

4207 def _maybe_decode(tokens: torch.Tensor) -> Union[torch.Tensor, str, List[str]]: 

4208 nonlocal decoded_history 

4209 if return_type != "str": 

4210 return tokens 

4211 decoded_history = ( 

4212 tokens if decoded_history is None else torch.cat([decoded_history, tokens], dim=-1) 

4213 ) 

4214 deltas = _decode_delta(hold_incomplete=True) 

4215 return deltas[0] if len(deltas) == 1 else deltas 

4216 

4217 def _flush_held() -> Optional[Union[str, List[str]]]: 

4218 """Emit a withheld partial character at stream end rather than dropping it.""" 

4219 if return_type != "str" or decoded_history is None: 

4220 return None 

4221 deltas = _decode_delta(hold_incomplete=False) 

4222 if not any(deltas): 

4223 return None 

4224 return deltas[0] if len(deltas) == 1 else deltas 

4225 

4226 try: 

4227 for step_idx, (sampled_tokens, _, all_finished) in enumerate( 

4228 self._generate_tokens( 

4229 current_tokens, 

4230 input_tokens, 

4231 batch_size, 

4232 max_new_tokens=max_new_tokens, 

4233 do_sample=do_sample, 

4234 top_k=top_k, 

4235 top_p=top_p, 

4236 temperature=temperature, 

4237 freq_penalty=freq_penalty, 

4238 repetition_penalty=repetition_penalty, 

4239 stop_at_eos=stop_at_eos, 

4240 stop_tokens=stop_tokens, 

4241 eos_token_for_padding=eos_token_for_padding, 

4242 finished_sequences=finished_sequences, 

4243 use_past_kv_cache=use_past_kv_cache, 

4244 use_stateful_cache=False, 

4245 mamba_cache=None, 

4246 mamba_conv_kernel=0, 

4247 is_encoder_decoder=_encdec_early, 

4248 batched_prompt_mask=( 

4249 self._left_padded_prompt_mask(input, input_tokens, prepend_bos) 

4250 if _is_batched_list 

4251 and isinstance(input, list) 

4252 and not _encdec_early 

4253 and initial_attention_mask is None 

4254 else None 

4255 ), 

4256 _generate_from_embeds=False, 

4257 encoder_input=encoder_input, 

4258 decoder_tokens=decoder_tokens, 

4259 generated_token_ids=None, 

4260 pixel_values=None, 

4261 multimodal_kwargs={}, 

4262 verbose=verbose, 

4263 stopping_criteria_list=stopping_criteria_list, 

4264 initial_attention_mask=initial_attention_mask, 

4265 min_decoder_length=min_decoder_length, 

4266 ngram_processor=(self._encdec_ngram_processor() if _encdec_early else None), 

4267 encoder_attention_mask=encoder_attention_mask, 

4268 forced_eos_token_id=( 

4269 self._encdec_forced_eos_token_id() if _encdec_early else None 

4270 ), 

4271 suppress_processors=( 

4272 self._encdec_suppress_processors(decoder_tokens.shape[1]) 

4273 if decoder_tokens is not None 

4274 else () 

4275 ), 

4276 ) 

4277 ): 

4278 new_tokens = sampled_tokens.unsqueeze(-1) 

4279 

4280 if step_idx == 0: 

4281 accumulated_tokens = torch.cat([stream_prefix, new_tokens], dim=-1) 

4282 tokens_since_last_yield = accumulated_tokens.shape[1] 

4283 else: 

4284 if accumulated_tokens is None: 

4285 accumulated_tokens = new_tokens 

4286 else: 

4287 accumulated_tokens = torch.cat([accumulated_tokens, new_tokens], dim=-1) 

4288 tokens_since_last_yield += 1 

4289 

4290 if tokens_since_last_yield >= max_tokens_per_yield: 

4291 yield _maybe_decode(accumulated_tokens) 

4292 tokens_since_last_yield = 0 

4293 accumulated_tokens = None 

4294 

4295 if all_finished: 

4296 if accumulated_tokens is not None: 

4297 yield _maybe_decode(accumulated_tokens) 

4298 accumulated_tokens = None 

4299 break 

4300 

4301 # Yield remainder after loop completes without break 

4302 if accumulated_tokens is not None: 

4303 yield _maybe_decode(accumulated_tokens) 

4304 held_back = _flush_held() 

4305 if held_back is not None: 

4306 yield held_back 

4307 finally: 

4308 self._capture_hf_cache = False 

4309 if hasattr(self, "_last_hf_cache"): 4309 ↛ 4310line 4309 didn't jump to line 4310 because the condition on line 4309 was never true

4310 del self._last_hf_cache 

4311 

4312 def hf_generate( 

4313 self, 

4314 input: str | list[str] | torch.Tensor = "", 

4315 max_new_tokens: int = 10, 

4316 stop_at_eos: bool = True, 

4317 eos_token_id: int | Sequence[int] | None = None, 

4318 do_sample: bool = True, 

4319 top_k: int | None = None, 

4320 top_p: float | None = None, 

4321 temperature: float = 1.0, 

4322 use_past_kv_cache: bool = True, 

4323 return_type: str | None = "input", 

4324 pixel_values: torch.Tensor | None = None, 

4325 **generation_kwargs, 

4326 ) -> str | list[str] | torch.Tensor | Any: # Any for HF ModelOutput types 

4327 # Any: beartype forward ref limitation (beartype#546) 

4328 """Generate text using the underlying HuggingFace model with full HF API support. 

4329 

4330 This method provides direct access to HuggingFace's generation API, forwarding all 

4331 generation parameters (including output_scores, output_logits, output_attentions, 

4332 output_hidden_states) directly to the underlying HF model. Use this when you need 

4333 full HuggingFace generation features not supported by the standard generate() method. 

4334 

4335 For the standard TransformerLens generation interface, use generate() instead. 

4336 

4337 Args: 

4338 input: Text string, list of strings, or tensor of tokens 

4339 max_new_tokens: Maximum number of tokens to generate 

4340 stop_at_eos: If True, stop generating tokens when the model outputs eos_token. 

4341 If False, disable EOS stopping, including the model's configured EOS. 

4342 Custom stopping criteria still apply. 

4343 eos_token_id: The token ID (or sequence of IDs) to stop on. Ignored 

4344 when stop_at_eos=False, matching generate(). 

4345 do_sample: If True, sample from the model's output distribution 

4346 top_k: Number of tokens to sample from 

4347 top_p: Probability mass to sample from 

4348 temperature: Temperature for sampling 

4349 use_past_kv_cache: If True, use KV caching for faster generation 

4350 return_type: The type of output to return - 'input', 'str', or 'tokens' 

4351 **generation_kwargs: Additional HuggingFace generation parameters including: 

4352 - output_scores: Return generation scores 

4353 - output_logits: Return generation logits 

4354 - output_attentions: Return attention weights 

4355 - output_hidden_states: Return hidden states 

4356 - return_dict_in_generate: Return ModelOutput object 

4357 - And any other HF generation parameters 

4358 

4359 Returns: 

4360 Generated sequence as string, list of strings, tensor, or HF ModelOutput 

4361 depending on input type, return_type, and generation_kwargs. 

4362 

4363 Example:: 

4364 

4365 # Get full HF ModelOutput with logits and attentions 

4366 from transformer_lens import TransformerBridge 

4367 model = TransformerBridge.boot_transformers("tiny-stories-1M") 

4368 result = model.hf_generate( 

4369 "Hello world", 

4370 max_new_tokens=5, 

4371 output_logits=True, 

4372 output_attentions=True, 

4373 return_dict_in_generate=True 

4374 ) 

4375 print(result.sequences) # Generated tokens 

4376 print(result.logits) # Logits for each generation step 

4377 print(result.attentions) # Attention weights 

4378 """ 

4379 self._ensure_generation_supported("hf_generate") 

4380 input_attention_mask: torch.Tensor | None = None 

4381 # Handle string input by tokenizing it 

4382 if isinstance(input, str): 

4383 inputs = self.tokenizer(input, return_tensors="pt", padding=False, truncation=False).to( 

4384 self.cfg.device 

4385 ) 

4386 input_ids = inputs["input_ids"] 

4387 input_type = "str" 

4388 elif isinstance(input, list): 

4389 is_encoder_decoder = getattr( 

4390 getattr(self.original_model, "config", None), "is_encoder_decoder", False 

4391 ) 

4392 tokenizer_kwargs = {} if is_encoder_decoder else {"padding_side": "left"} 

4393 inputs = self.tokenizer( 

4394 input, 

4395 return_tensors="pt", 

4396 padding=True, 

4397 truncation=False, 

4398 **tokenizer_kwargs, 

4399 ).to(self.cfg.device) 

4400 input_ids = inputs["input_ids"] 

4401 input_attention_mask = inputs["attention_mask"] 

4402 input_type = "list" 

4403 else: 

4404 input_ids = input 

4405 # cfg.device is a str; comparing it to a torch.device is always unequal. 

4406 if self.cfg.device is not None and input_ids.device != torch.device(self.cfg.device): 4406 ↛ 4407line 4406 didn't jump to line 4407 because the condition on line 4406 was never true

4407 input_ids = input_ids.to(self.cfg.device) 

4408 input_type = "tokens" 

4409 

4410 # Build generation_kwargs from explicit args and kwargs 

4411 generation_kwargs = dict(generation_kwargs) if generation_kwargs is not None else {} 

4412 if input_attention_mask is not None: 

4413 generation_kwargs["attention_mask"] = input_attention_mask 

4414 generation_kwargs.update( 

4415 { 

4416 "max_new_tokens": max_new_tokens, 

4417 "do_sample": do_sample, 

4418 "pad_token_id": self.tokenizer.eos_token_id, 

4419 } 

4420 ) 

4421 # Temperature only matters when sampling. Whisper's generate samples whenever a 

4422 # temperature above 0 is passed, so a greedy call must not send one. 

4423 if do_sample: 

4424 generation_kwargs["temperature"] = temperature 

4425 

4426 if top_k is not None: 4426 ↛ 4427line 4426 didn't jump to line 4427 because the condition on line 4426 was never true

4427 generation_kwargs["top_k"] = top_k 

4428 if top_p is not None: 4428 ↛ 4429line 4428 didn't jump to line 4429 because the condition on line 4428 was never true

4429 generation_kwargs["top_p"] = top_p 

4430 if not stop_at_eos: 

4431 # Omitting the kwarg would restore generation_config's EOS stopping. 

4432 generation_kwargs["eos_token_id"] = None 

4433 elif eos_token_id is not None: 

4434 # cfg.eos_token_id can carry a chat model's full stop set; HF takes 

4435 # int or list, so normalize any other sequence to a list. 

4436 generation_kwargs["eos_token_id"] = ( 

4437 eos_token_id if isinstance(eos_token_id, int) else list(eos_token_id) 

4438 ) 

4439 elif self.tokenizer.eos_token_id is not None: 4439 ↛ 4442line 4439 didn't jump to line 4442 because the condition on line 4439 was always true

4440 generation_kwargs["eos_token_id"] = self.tokenizer.eos_token_id 

4441 

4442 if pixel_values is not None: 4442 ↛ 4443line 4442 didn't jump to line 4443 because the condition on line 4442 was never true

4443 generation_kwargs["pixel_values"] = pixel_values 

4444 

4445 if use_past_kv_cache: 4445 ↛ 4449line 4445 didn't jump to line 4449 because the condition on line 4445 was always true

4446 generation_kwargs["use_cache"] = True 

4447 

4448 # HF dict flags that trigger ModelOutput returns 

4449 hf_dict_flags = ( 

4450 "output_scores", 

4451 "output_logits", 

4452 "output_attentions", 

4453 "output_hidden_states", 

4454 ) 

4455 

4456 # If any HF-style output flags are provided, ensure return_dict_in_generate is set 

4457 any_flag_set = False 

4458 for f in hf_dict_flags: 

4459 if generation_kwargs.get(f) is not None: 

4460 generation_kwargs[f] = bool(generation_kwargs[f]) 

4461 any_flag_set = True 

4462 

4463 if any_flag_set: 

4464 generation_kwargs.setdefault("return_dict_in_generate", True) 

4465 

4466 with torch.no_grad(): 

4467 outputs = self.original_model.generate(input_ids, **generation_kwargs) # type: ignore[operator] 

4468 

4469 # Check if output is a ModelOutput 

4470 try: 

4471 from transformers.utils import ModelOutput # type: ignore 

4472 

4473 is_model_output = isinstance(outputs, ModelOutput) 

4474 except Exception: 

4475 is_model_output = False 

4476 

4477 # Return based on return_type and input format 

4478 if return_type == "input" or return_type is None: 

4479 if input_type == "str": 

4480 # Decode the full output back to string 

4481 if is_model_output and hasattr(outputs, "sequences"): 4481 ↛ 4483line 4481 didn't jump to line 4483 because the condition on line 4481 was always true

4482 return self.tokenizer.decode(outputs.sequences[0], skip_special_tokens=True) 

4483 return self.tokenizer.decode(outputs[0], skip_special_tokens=True) 

4484 elif input_type == "list": 

4485 # Decode each sequence in the batch 

4486 if is_model_output and hasattr(outputs, "sequences"): 4486 ↛ 4491line 4486 didn't jump to line 4491 because the condition on line 4486 was always true

4487 return [ 

4488 self.tokenizer.decode(seq, skip_special_tokens=True) 

4489 for seq in outputs.sequences 

4490 ] 

4491 return [self.tokenizer.decode(seq, skip_special_tokens=True) for seq in outputs] 

4492 else: 

4493 # Return the full token sequence including input 

4494 return outputs 

4495 elif return_type == "tokens": 4495 ↛ 4499line 4495 didn't jump to line 4499 because the condition on line 4495 was always true

4496 return outputs 

4497 else: 

4498 # For other return types, default to the decoded text 

4499 if input_type == "str": 

4500 if is_model_output and hasattr(outputs, "sequences"): 

4501 return self.tokenizer.decode(outputs.sequences[0], skip_special_tokens=True) 

4502 return self.tokenizer.decode(outputs[0], skip_special_tokens=True) 

4503 elif input_type == "list": 

4504 if is_model_output and hasattr(outputs, "sequences"): 

4505 return [ 

4506 self.tokenizer.decode(seq, skip_special_tokens=True) 

4507 for seq in outputs.sequences 

4508 ] 

4509 return [self.tokenizer.decode(seq, skip_special_tokens=True) for seq in outputs] 

4510 else: 

4511 return outputs 

4512 

4513 def prepare_multimodal_inputs( 

4514 self, 

4515 text: Union[str, List[str]], 

4516 images: Optional[Any] = None, 

4517 ) -> Dict[str, torch.Tensor]: 

4518 """Prepare multimodal inputs using the model's processor. 

4519 

4520 Converts text and images into model-ready tensors (input_ids, pixel_values, 

4521 attention_mask, etc.) using the HuggingFace processor loaded during boot(). 

4522 

4523 Args: 

4524 text: Text prompt(s), typically containing image placeholder tokens 

4525 (e.g., "<image>" for LLaVA). 

4526 images: PIL Image or list of PIL Images to process. Pass None for 

4527 text-only inputs on a multimodal model. 

4528 

4529 Returns: 

4530 Dictionary with 'input_ids', 'pixel_values', 'attention_mask', etc. 

4531 All tensors are moved to the model's device. 

4532 

4533 Raises: 

4534 ValueError: If model is not multimodal or processor is not available. 

4535 """ 

4536 if not getattr(self.cfg, "is_multimodal", False): 

4537 raise ValueError( 

4538 "prepare_multimodal_inputs() requires a multimodal model " 

4539 "(cfg.is_multimodal must be True)" 

4540 ) 

4541 if self.processor is None: 

4542 raise ValueError( 

4543 "No processor available. Load model with boot_transformers() or " 

4544 "set bridge.processor = AutoProcessor.from_pretrained(...) manually." 

4545 ) 

4546 inputs = self.processor(text=text, images=images, return_tensors="pt") 

4547 return {k: v.to(self.cfg.device) if hasattr(v, "to") else v for k, v in inputs.items()} 

4548 

4549 def to(self, *args, **kwargs) -> "TransformerBridge": 

4550 """Move model to device and/or change dtype. 

4551 

4552 Args: 

4553 args: Positional arguments for nn.Module.to 

4554 kwargs: Keyword arguments for nn.Module.to 

4555 print_details: Whether to print details about device/dtype changes (default: True) 

4556 

4557 Returns: 

4558 Self for chaining 

4559 """ 

4560 # Extract print_details if provided 

4561 print_details = kwargs.pop("print_details", True) 

4562 

4563 # Handle both device and dtype changes 

4564 # torch.nn.Module.to() supports: to(device), to(dtype), to(device, dtype), 

4565 # to(device=...), to(dtype=...), to(device=..., dtype=...) 

4566 target_device, target_dtype = None, None 

4567 

4568 if len(args) >= 1: 

4569 first_arg = args[0] 

4570 if isinstance(first_arg, (torch.device, str)): 

4571 target_device = first_arg 

4572 elif isinstance(first_arg, torch.dtype): 4572 ↛ 4574line 4572 didn't jump to line 4574 because the condition on line 4572 was always true

4573 target_dtype = first_arg 

4574 if len(args) >= 2: 

4575 second_arg = args[1] 

4576 if isinstance(second_arg, torch.dtype): 4576 ↛ 4580line 4576 didn't jump to line 4580 because the condition on line 4576 was always true

4577 target_dtype = second_arg 

4578 

4579 # these override positional args 

4580 if "device" in kwargs: 4580 ↛ 4581line 4580 didn't jump to line 4581 because the condition on line 4580 was never true

4581 target_device = kwargs["device"] 

4582 if "dtype" in kwargs: 

4583 target_dtype = kwargs["dtype"] 

4584 

4585 # Moving a multi-device (device_map-dispatched) model to a single device would 

4586 # collapse the split and break accelerate's hook routing. Warn and drop the 

4587 # device move; still honor dtype changes. 

4588 if target_device is not None and getattr(self.cfg, "n_devices", 1) > 1: 

4589 warnings.warn( 

4590 f"TransformerBridge.to({target_device!r}) ignored: model is dispatched " 

4591 f"across {self.cfg.n_devices} devices via device_map. Reload with " 

4592 "device=... (and no device_map/n_devices) to move to a single device.", 

4593 stacklevel=2, 

4594 ) 

4595 target_device = None 

4596 

4597 if target_device is not None: 

4598 move_to_and_update_config(self, target_device, print_details) 

4599 if target_dtype is not None: 

4600 move_to_and_update_config(self, target_dtype, print_details) 

4601 

4602 # Move the original model with all original args/kwargs (with print_details removed). 

4603 # When we've nulled target_device for multi-GPU safety, strip device args so the 

4604 # underlying module isn't moved either. 

4605 if target_device is None and (len(args) > 0 or "device" in kwargs): 

4606 kwargs.pop("device", None) 

4607 # Filter positional args: drop devices/strings, keep dtypes. 

4608 args = tuple(a for a in args if not isinstance(a, (torch.device, str))) 

4609 self.original_model = self.original_model.to(*args, **kwargs) 

4610 return self 

4611 

4612 def cuda(self, device: Optional[Union[int, torch.device]] = None) -> "TransformerBridge": 

4613 """Move model to CUDA. 

4614 

4615 Args: 

4616 device: CUDA device 

4617 

4618 Returns: 

4619 Self for chaining 

4620 """ 

4621 if isinstance(device, int): 

4622 return self.to(f"cuda:{device}") 

4623 elif device is None: 

4624 return self.to("cuda") 

4625 else: 

4626 return self.to(device) 

4627 

4628 def cpu(self) -> "TransformerBridge": 

4629 """Move model to CPU. 

4630 

4631 Returns: 

4632 Self for chaining 

4633 """ 

4634 return self.to(torch.device("cpu")) 

4635 

4636 def mps(self) -> "TransformerBridge": 

4637 """Move model to MPS. 

4638 

4639 Returns: 

4640 Self for chaining 

4641 """ 

4642 return self.to(torch.device("mps")) 

4643 

4644 def train(self, mode: bool = True) -> "TransformerBridge": 

4645 """Set training mode, propagating to the wrapped source model. 

4646 

4647 ``original_model`` lives in ``__dict__`` rather than the registered 

4648 module tree, so the inherited ``nn.Module.train()`` recursion does not 

4649 reach it. 

4650 """ 

4651 super().train(mode) 

4652 original = getattr(self, "original_model", None) 

4653 if isinstance(original, torch.nn.Module): 

4654 original.train(mode) 

4655 return self 

4656 

4657 def set_use_attn_result(self, use_attn_result: bool): 

4658 """Toggle whether to explicitly calculate and expose the result for each attention head. 

4659 

4660 Useful for interpretability but can easily burn through GPU memory. 

4661 """ 

4662 if use_attn_result: 

4663 self._validate_attention_fork_supported("use_attn_result") 

4664 self.cfg._set_bridge_managed_hook_flag("use_attn_result", use_attn_result) 

4665 self._propagate_attention_flag("use_attn_result", use_attn_result) 

4666 

4667 def set_use_split_qkv_input(self, use_split_qkv_input: bool): 

4668 """Toggle independent residual copies for Q/K/V so each path can be patched alone. 

4669 

4670 Mutually exclusive with `use_attn_in` — set that flag off first if it's on. 

4671 """ 

4672 if use_split_qkv_input: 

4673 if bool(getattr(self.cfg, "use_attn_in", False)): 

4674 raise ValueError( 

4675 "use_split_qkv_input and use_attn_in are mutually exclusive. " 

4676 "Call set_use_attn_in(False) before enabling use_split_qkv_input." 

4677 ) 

4678 self._validate_attention_fork_supported("use_split_qkv_input") 

4679 self.cfg._set_bridge_managed_hook_flag("use_split_qkv_input", use_split_qkv_input) 

4680 self._propagate_attention_flag("use_split_qkv_input", use_split_qkv_input) 

4681 

4682 def set_use_attn_in(self, use_attn_in: bool): 

4683 """Toggle a single 4D residual copy feeding all three Q/K/V projections. 

4684 

4685 Mutually exclusive with `use_split_qkv_input` — set that flag off first 

4686 if it's on. When on, `hook_attn_in` fires at 

4687 `[batch, pos, n_heads, d_model]`, enabling coarse-grained interventions 

4688 on the residual-stream copy shared across Q/K/V. 

4689 """ 

4690 if use_attn_in: 

4691 if bool(getattr(self.cfg, "use_split_qkv_input", False)): 

4692 raise ValueError( 

4693 "use_attn_in and use_split_qkv_input are mutually exclusive. " 

4694 "Call set_use_split_qkv_input(False) before enabling use_attn_in." 

4695 ) 

4696 self._validate_attention_fork_supported("use_attn_in") 

4697 self.cfg._set_bridge_managed_hook_flag("use_attn_in", use_attn_in) 

4698 self._propagate_attention_flag("use_attn_in", use_attn_in) 

4699 

4700 def set_use_hook_mlp_in(self, use_hook_mlp_in: bool) -> None: 

4701 """Toggle the ``hook_mlp_in`` HookPoint (the MLP-branch entry: pre-ln2, or 

4702 the MLP input on post-norm blocks), matching legacy semantics. 

4703 """ 

4704 self.cfg._set_bridge_managed_hook_flag("use_hook_mlp_in", use_hook_mlp_in) 

4705 if not hasattr(self, "blocks"): 4705 ↛ 4706line 4705 didn't jump to line 4706 because the condition on line 4705 was never true

4706 return 

4707 for block in self.blocks: 

4708 block_cfg = getattr(block, "config", None) 

4709 if block_cfg is not None and block_cfg is not self.cfg: 

4710 try: 

4711 self._write_propagated_hook_flag(block_cfg, "use_hook_mlp_in", use_hook_mlp_in) 

4712 except (AttributeError, TypeError): 

4713 pass 

4714 block._use_hook_mlp_in = use_hook_mlp_in 

4715 

4716 @staticmethod 

4717 def _write_propagated_hook_flag(config: Any, flag_name: str, value: bool) -> None: 

4718 """Write a cloned config flag without dispatching through its live Bridge.""" 

4719 if isinstance(config, TransformerBridgeConfig): 

4720 config._set_bridge_managed_hook_flag(flag_name, value) 

4721 else: 

4722 object.__setattr__(config, flag_name, value) 

4723 

4724 def _propagate_attention_flag(self, flag_name: str, value: bool) -> None: 

4725 """Mirror `bridge.cfg.<flag>` onto every block's attention config. 

4726 

4727 Some adapters (Llama family) deep-copy the block template during 

4728 `setup_blocks_bridge`, cloning the attention bridge's config along 

4729 with it. Others (Pythia, GPT-2) override `__deepcopy__` to share the 

4730 config. Setting the flag only on `self.cfg` silently misses the 

4731 cloned-config case. Propagating explicitly keeps both patterns 

4732 honest — a no-op when configs are shared, a correctness fix when 

4733 they aren't. 

4734 """ 

4735 if not hasattr(self, "blocks"): 4735 ↛ 4736line 4735 didn't jump to line 4736 because the condition on line 4735 was never true

4736 return 

4737 for block in self.blocks: 

4738 attn = block._modules.get("attn") if hasattr(block, "_modules") else None 

4739 if attn is None: 

4740 continue 

4741 attn_cfg = getattr(attn, "config", None) 

4742 if attn_cfg is not None and attn_cfg is not self.cfg: 

4743 try: 

4744 self._write_propagated_hook_flag(attn_cfg, flag_name, value) 

4745 except (AttributeError, TypeError): 

4746 # Some config-like objects reject attributes even when 

4747 # bypassing their custom __setattr__ implementation. 

4748 pass 

4749 

4750 def _validate_attention_fork_supported(self, flag_name: str) -> None: 

4751 """Raise / warn if the model can't honor a fine-grained attention flag. 

4752 

4753 The post-ln1 fork path lives on JointQKVAttentionBridge and 

4754 PositionEmbeddingsAttentionBridge. Plain AttentionBridge delegates to 

4755 HF and exposes no fork point; we raise rather than setting the flag 

4756 silently. For hybrid models (some attention layers, some not), we warn 

4757 and list which layers will honor the flag. 

4758 """ 

4759 # Deferred imports: tight circular dependency with bridge setup. 

4760 from transformer_lens.model_bridge.generalized_components.joint_qkv_attention import ( 

4761 JointQKVAttentionBridge, 

4762 ) 

4763 from transformer_lens.model_bridge.generalized_components.position_embeddings_attention import ( 

4764 PositionEmbeddingsAttentionBridge, 

4765 ) 

4766 

4767 if not hasattr(self, "blocks"): 4767 ↛ 4768line 4767 didn't jump to line 4768 because the condition on line 4767 was never true

4768 raise NotImplementedError( 

4769 f"{flag_name}: this bridge has no `blocks` attribute, so no " 

4770 "attention bridges to apply the flag to." 

4771 ) 

4772 supported_classes = (JointQKVAttentionBridge, PositionEmbeddingsAttentionBridge) 

4773 supporting_layers: list[int] = [] 

4774 attn_classes: set[str] = set() 

4775 total_with_attn = 0 

4776 for idx, block in enumerate(self.blocks): 

4777 attn = block._modules.get("attn") if hasattr(block, "_modules") else None 

4778 if attn is None: 

4779 continue 

4780 total_with_attn += 1 

4781 attn_classes.add(type(attn).__name__) 

4782 supports_flag = ( 

4783 bool(getattr(attn, "supports_attn_result", False)) 

4784 if flag_name == "use_attn_result" 

4785 else isinstance(attn, supported_classes) 

4786 ) 

4787 if supports_flag: 

4788 supporting_layers.append(idx) 

4789 if total_with_attn == 0: 4789 ↛ 4790line 4789 didn't jump to line 4790 because the condition on line 4789 was never true

4790 raise NotImplementedError(f"{flag_name}: no attention bridges found on self.blocks.") 

4791 if not supporting_layers: 

4792 if flag_name == "use_attn_result": 

4793 capability_detail = "Per-head result computation is unavailable." 

4794 else: 

4795 capability_detail = "No hook point is available before the Q/K/V projections." 

4796 raise NotImplementedError( 

4797 f"{flag_name}: none of this model's attention bridges support " 

4798 "the requested fine-grained attention hook. Found attention classes: " 

4799 f"{sorted(attn_classes)}. Supported classes: " 

4800 f"{[c.__name__ for c in supported_classes]}. {capability_detail}" 

4801 ) 

4802 if len(supporting_layers) < total_with_attn: 4802 ↛ 4803line 4802 didn't jump to line 4803 because the condition on line 4802 was never true

4803 skipped = total_with_attn - len(supporting_layers) 

4804 warnings.warn( 

4805 f"{flag_name}: {skipped} of {total_with_attn} attention layers " 

4806 "use an attention-bridge class that cannot honor this flag " 

4807 f"(attention classes present: {sorted(attn_classes)}). " 

4808 f"The flag will affect layers: {supporting_layers}.", 

4809 stacklevel=3, 

4810 ) 

4811 

4812 def _is_valid_bridge_path(self, hf_path: str) -> bool: 

4813 """Check if a HuggingFace path corresponds to a valid bridge component. 

4814 

4815 This validates that the path follows the bridge component structure and doesn't 

4816 contain nested HuggingFace components that should have been wrapped. 

4817 

4818 Args: 

4819 hf_path: HuggingFace path after removing _original_component 

4820 

4821 Returns: 

4822 True if the path is valid, False if it contains nested HF components 

4823 """ 

4824 parts = hf_path.split(".") 

4825 

4826 # Get the component mapping for validation 

4827 component_mapping = self.adapter.component_mapping 

4828 if not component_mapping: 4828 ↛ 4829line 4828 didn't jump to line 4829 because the condition on line 4828 was never true

4829 return True # If no mapping, accept all keys 

4830 

4831 # Walk through the path and check if each level is a registered bridge component 

4832 # For example, transformer.h.0.mlp.in.weight should be valid 

4833 # but transformer.h.0.mlp.c_fc.weight should be invalid (c_fc is nested HF component) 

4834 

4835 # Start from the root 

4836 current_component = None 

4837 idx = 0 

4838 

4839 # Find which top-level component this belongs to 

4840 for tl_name, component in component_mapping.items(): 

4841 if component.name and hf_path.startswith(component.name + "."): 

4842 current_component = component 

4843 # Skip past the HF prefix 

4844 remaining_path = hf_path[len(component.name) + 1 :] 

4845 parts = remaining_path.split(".") 

4846 idx = 0 

4847 break 

4848 

4849 if current_component is None: 

4850 return True # Path doesn't match any component, let it through 

4851 

4852 # Special handling for blocks 

4853 if hasattr(current_component, "is_list_item") and current_component.is_list_item: 

4854 # Skip the layer index 

4855 if idx < len(parts) and parts[idx].isdigit(): 4855 ↛ 4859line 4855 didn't jump to line 4859 because the condition on line 4855 was always true

4856 idx += 1 

4857 

4858 # Now validate the rest of the path against submodules 

4859 while idx < len(parts): 4859 ↛ 4886line 4859 didn't jump to line 4886 because the condition on line 4859 was always true

4860 part = parts[idx] 

4861 

4862 # If we hit 'weight' or 'bias', we're at a parameter - this is valid 

4863 if part in ("weight", "bias"): 

4864 return True 

4865 

4866 # Check if this part is a registered submodule 

4867 if hasattr(current_component, "submodules") and current_component.submodules: 

4868 if part in current_component.submodules: 

4869 current_component = current_component.submodules[part] 

4870 idx += 1 

4871 continue 

4872 else: 

4873 # This part is not a registered bridge component 

4874 # It's likely a nested HF component (like c_fc, c_proj, c_attn) 

4875 return False 

4876 else: 

4877 # No submodules to check, but not at a parameter yet 

4878 # Check if next is weight/bias 

4879 if idx + 1 < len(parts) and parts[idx + 1] in ("weight", "bias"): 

4880 return True 

4881 # Otherwise this is likely a nested HF component 

4882 return False 

4883 

4884 idx += 1 

4885 

4886 return True 

4887 

4888 def _normalize_bridge_key_to_hf(self, key: str) -> str: 

4889 """Normalize a key that uses bridge attribute names to use HF module names. 

4890 

4891 PyTorch's state_dict uses the Python attribute names (e.g., 'ln1') 

4892 but the conversion logic expects HF module names (e.g., 'ln_1'). This 

4893 function only replaces non-nested component names, leaving bridge 

4894 subcomponents (like 'in', 'out', 'q', 'k', 'v') unchanged since they're 

4895 handled by the component structure. 

4896 

4897 Args: 

4898 key: Key that may use bridge attribute names 

4899 

4900 Returns: 

4901 Key with attribute names replaced by module names where needed 

4902 """ 

4903 component_mapping = self.adapter.component_mapping 

4904 if not component_mapping: 4904 ↛ 4905line 4904 didn't jump to line 4905 because the condition on line 4904 was never true

4905 return key 

4906 

4907 # Build a mapping of only the direct module attribute names to HF names 

4908 # We only care about top-level and block-level component names, NOT subcomponents 

4909 attr_to_hf = {} 

4910 

4911 # Map top-level components 

4912 block_list_names = {"blocks", "L_blocks", "H_blocks", "encoder_blocks", "decoder_blocks"} 

4913 for tl_name, component in component_mapping.items(): 

4914 if component.name and tl_name not in block_list_names: 

4915 # Skip if TL name is already a segment of its HF path (avoids doubling). 

4916 if tl_name != component.name and tl_name not in component.name.split("."): 

4917 attr_to_hf[tl_name] = component.name 

4918 

4919 # Map block-level components (ln1, ln2, attn, mlp) per block list: an encoder and 

4920 # a decoder can give one name different HF modules (BART-family ln2 is the 

4921 # encoder's final_layer_norm but the decoder's encoder_attn_layer_norm). 

4922 block_attr_to_hf: dict[str, dict[str, str]] = {} 

4923 for bl_name in sorted(block_list_names): 

4924 blocks_component = component_mapping.get(bl_name) 

4925 if blocks_component and hasattr(blocks_component, "submodules"): 

4926 names = { 

4927 tl_subname: subcomponent.name 

4928 for tl_subname, subcomponent in blocks_component.submodules.items() 

4929 if subcomponent.name and tl_subname != subcomponent.name 

4930 } 

4931 attr_to_hf.update(names) 

4932 if blocks_component.name: 4932 ↛ 4923line 4932 didn't jump to line 4923 because the condition on line 4932 was always true

4933 block_attr_to_hf[blocks_component.name] = names 

4934 block_path = next((path for path in block_attr_to_hf if key.startswith(path + ".")), None) 

4935 if block_path is not None: 

4936 attr_to_hf = {**attr_to_hf, **block_attr_to_hf[block_path]} 

4937 

4938 # Replace only these specific attribute names in the key 

4939 # We need to be careful to only replace whole path components, not substrings 

4940 parts = key.split(".") 

4941 result_parts = [] 

4942 

4943 for part in parts: 

4944 if part in attr_to_hf: 

4945 result_parts.append(attr_to_hf[part]) 

4946 else: 

4947 result_parts.append(part) 

4948 

4949 return ".".join(result_parts) 

4950 

4951 def state_dict(self, destination=None, prefix="", keep_vars=False): 

4952 """Get state dict with TransformerLens format keys. 

4953 

4954 Converts HuggingFace format keys to TransformerLens format and filters out 

4955 _original_component references and nested HuggingFace components. 

4956 

4957 A direct no-argument call returns a clean state dict with bridge component 

4958 paths converted to TL format. Calls that supply ``destination`` or 

4959 ``prefix`` use standard ``nn.Module`` recursive semantics so a Bridge can 

4960 compose inside a parent module. 

4961 

4962 Args: 

4963 destination: Optional dict to store state dict in 

4964 prefix: Optional prefix to add to all keys 

4965 keep_vars: Whether to keep variables as Variables instead of tensors 

4966 

4967 Returns: 

4968 Direct calls return TransformerLens-format keys; recursive calls 

4969 return the supplied destination with standard module-tree keys. 

4970 """ 

4971 if destination is not None or prefix: 

4972 return super().state_dict( 

4973 destination=destination, 

4974 prefix=prefix, 

4975 keep_vars=keep_vars, 

4976 ) 

4977 

4978 raw_state_dict = self.original_model.state_dict(keep_vars=keep_vars) 

4979 

4980 # Clean _original_component references and convert to TL format 

4981 # Also filter out nested HuggingFace components that are wrapped by bridge components 

4982 tl_state_dict = {} 

4983 

4984 for key, value in raw_state_dict.items(): 

4985 # Skip _original_component keys 

4986 if key == "_original_component" or key.startswith("_original_component."): 4986 ↛ 4987line 4986 didn't jump to line 4987 because the condition on line 4986 was never true

4987 continue 

4988 

4989 # Remove all _original_component from the key 

4990 clean_key = key.replace("._original_component", "") 

4991 

4992 # Check if this is a valid bridge path (not a nested HF component) 

4993 if not self._is_valid_bridge_path(clean_key): 

4994 continue 

4995 

4996 # Normalize bridge component names to HF names for conversion 

4997 # (e.g., 'ln1' -> 'ln_1', 'mlp.in' -> 'mlp.c_fc') 

4998 hf_key = self._normalize_bridge_key_to_hf(clean_key) 

4999 

5000 # Convert to TL format - this uses the adapter's component_mapping 

5001 tl_key = self.adapter.convert_hf_key_to_tl_key(hf_key) 

5002 

5003 # Only add if we haven't seen this TL key yet (handles duplicates) 

5004 if tl_key not in tl_state_dict: 

5005 tl_state_dict[tl_key] = value 

5006 

5007 return tl_state_dict 

5008 

5009 def _tl_key_to_actual_keys(self) -> dict[str, list[str]]: 

5010 """Inverse of the renaming state_dict() applies: map each TL-format key 

5011 back to every raw parameter/buffer path that represents it. 

5012 

5013 Mirrors the filtering and key-conversion in state_dict() exactly, except 

5014 it keeps every raw key for a given TL key instead of only the first-seen 

5015 one. Bridge components frequently expose the same underlying parameter 

5016 through more than one attribute path (e.g. GPT-2's split q/k/v weights 

5017 are views into the wrapped module's combined c_attn weight, reachable 

5018 both via a block-level shortcut and via the nested _original_component 

5019 chain) - all of those aliases must be written for the round trip to 

5020 actually change what forward() reads, not just what state_dict() shows. 

5021 """ 

5022 mapping: dict[str, list[str]] = {} 

5023 for actual_key in self.original_model.state_dict(): 

5024 if actual_key == "_original_component" or actual_key.startswith("_original_component."): 5024 ↛ 5025line 5024 didn't jump to line 5025 because the condition on line 5024 was never true

5025 continue 

5026 clean_key = actual_key.replace("._original_component", "") 

5027 if not self._is_valid_bridge_path(clean_key): 

5028 continue 

5029 hf_key = self._normalize_bridge_key_to_hf(clean_key) 

5030 tl_key = self.adapter.convert_hf_key_to_tl_key(hf_key) 

5031 mapping.setdefault(tl_key, []).append(actual_key) 

5032 return mapping 

5033 

5034 def load_state_dict(self, state_dict, strict=True, assign=False): 

5035 """Load state dict into the model, handling both clean keys and original keys with _original_component references. 

5036 

5037 Accepts three key formats: TL-format keys as emitted by state_dict() 

5038 (e.g. "blocks.0.attn.q.weight"), raw native parameter paths (e.g. for 

5039 ``boot_native`` / tracr-style loading), and raw paths with 

5040 "_original_component" segments stripped. 

5041 

5042 Args: 

5043 state_dict: Dictionary containing a whole state of the module 

5044 strict: Whether to strictly enforce that the keys in state_dict match the keys returned by this module's state_dict() function 

5045 assign: Whether to assign items in the state dictionary to their corresponding keys in the module instead of copying them 

5046 

5047 Returns: 

5048 NamedTuple with missing_keys and unexpected_keys fields 

5049 """ 

5050 current_state_dict = self.original_model.state_dict(keep_vars=True) 

5051 clean_to_actual = {} 

5052 for actual_key in current_state_dict.keys(): 

5053 if actual_key != "_original_component": 5053 ↛ 5052line 5053 didn't jump to line 5052 because the condition on line 5053 was always true

5054 clean_to_actual[actual_key.replace("._original_component", "")] = actual_key 

5055 

5056 tl_to_actual = self._tl_key_to_actual_keys() 

5057 

5058 mapped_state_dict = {} 

5059 unexpected_keys = [] 

5060 for input_key, value in state_dict.items(): 

5061 if input_key in current_state_dict: 

5062 mapped_state_dict[input_key] = value 

5063 elif input_key in clean_to_actual: 

5064 mapped_state_dict[clean_to_actual[input_key]] = value 

5065 elif input_key in tl_to_actual: 

5066 for actual_key in tl_to_actual[input_key]: 

5067 mapped_state_dict[actual_key] = value 

5068 else: 

5069 unexpected_keys.append(input_key) 

5070 

5071 # A TL key's actual-key aliases share the same underlying storage (see 

5072 # _tl_key_to_actual_keys), so writing any one of them already updates 

5073 # what forward() reads for all of them. Treat the group as satisfied 

5074 # if any alias was written -- e.g. a caller supplying clean/raw keys 

5075 # (the branch above maps each clean key to exactly one actual key) 

5076 # shouldn't have the *other*, unwritten aliases reported as missing. 

5077 missing_keys = sorted( 

5078 actual_key 

5079 for actual_keys in tl_to_actual.values() 

5080 if not any(k in mapped_state_dict for k in actual_keys) 

5081 for actual_key in actual_keys 

5082 ) 

5083 

5084 if strict and (missing_keys or unexpected_keys): 

5085 error_msgs = [] 

5086 if unexpected_keys: 

5087 error_msgs.append( 

5088 "Unexpected key(s) in state_dict: " 

5089 + ", ".join(f'"{k}"' for k in sorted(unexpected_keys)) 

5090 ) 

5091 if missing_keys: 

5092 error_msgs.append( 

5093 "Missing key(s) in state_dict: " + ", ".join(f'"{k}"' for k in missing_keys) 

5094 ) 

5095 raise RuntimeError( 

5096 "Error(s) in loading state_dict for {}:\n\t{}".format( 

5097 type(self.original_model).__name__, "\n\t".join(error_msgs) 

5098 ) 

5099 ) 

5100 

5101 if not assign: 

5102 result = self.original_model.load_state_dict( 

5103 mapped_state_dict, strict=False, assign=False 

5104 ) 

5105 return type(result)(missing_keys=missing_keys, unexpected_keys=unexpected_keys) 

5106 

5107 # assign=True normally makes nn.Module.load_state_dict *replace* each 

5108 # target parameter/buffer with the incoming tensor rather than copying 

5109 # into existing storage. Any key whose current tensor shares storage 

5110 # with another key -- a split QKV/gate-up component's view into a 

5111 # combined weight, the combined weight itself (writing it directly 

5112 # would silently orphan the views), or a tied pair like embed/unembed 

5113 # -- would desync from whatever it shares storage with: the bridge 

5114 # might keep reading a stale value, or a live view not even part of 

5115 # this load would silently keep the pre-load data while 

5116 # original_model.state_dict() (what save_pretrained() exports) shows 

5117 # the new one. Route every key in a storage-sharing group through an 

5118 # explicit in-place .data.copy_() instead, regardless of the caller's 

5119 # assign=True, so those relationships survive. 

5120 shared_keys = _storage_group_keys(current_state_dict) 

5121 

5122 copy_items: dict[str, tuple[torch.Tensor, torch.Tensor]] = {} 

5123 passthrough_items = {} 

5124 errors = [] 

5125 for key, value in mapped_state_dict.items(): 

5126 target = current_state_dict.get(key) 

5127 if target is None or key not in shared_keys: 

5128 passthrough_items[key] = value 

5129 continue 

5130 problems = [] 

5131 if target.is_meta: 5131 ↛ 5135line 5131 didn't jump to line 5135 because the condition on line 5131 was never true

5132 # copy_() onto a meta tensor silently no-ops rather than 

5133 # raising, so a meta target would otherwise report a 

5134 # successful load while never actually materializing. 

5135 problems.append( 

5136 "the current parameter is a meta tensor; an in-place copy " 

5137 "can't materialize it, and this key shares storage with " 

5138 "another parameter so ordinary assign=True replacement " 

5139 "isn't safe here either" 

5140 ) 

5141 else: 

5142 if tuple(target.shape) != tuple(value.shape): 

5143 problems.append(f"shape {tuple(value.shape)} != expected {tuple(target.shape)}") 

5144 if target.dtype != value.dtype: 

5145 problems.append(f"dtype {value.dtype} != expected {target.dtype}") 

5146 if target.device != value.device: 

5147 problems.append(f"device {value.device} != expected {target.device}") 

5148 if problems: 

5149 errors.append(f'"{key}": ' + "; ".join(problems)) 

5150 else: 

5151 copy_items[key] = (target, value) 

5152 

5153 if errors: 

5154 raise RuntimeError( 

5155 "Cannot load the following key(s) with assign=True: each shares " 

5156 "storage with another parameter/buffer (e.g. a split QKV/" 

5157 "gate-up component's view into a combined weight, or a tied " 

5158 "pair like embed/unembed), so it can only be loaded via an " 

5159 "in-place copy, which requires an exact match.\n\t" + "\n\t".join(errors) 

5160 ) 

5161 

5162 for target, value in copy_items.values(): 

5163 with torch.no_grad(): 

5164 target.data.copy_(value) 

5165 

5166 result = self.original_model.load_state_dict(passthrough_items, strict=False, assign=True) 

5167 refresh_container_state_owners(self) 

5168 return type(result)(missing_keys=missing_keys, unexpected_keys=unexpected_keys) 

5169 

5170 def get_params(self): 

5171 """Access to model parameters in the format expected by SVDInterpreter. 

5172 

5173 For missing weights, returns zero tensors of appropriate shape instead of raising exceptions. 

5174 This ensures compatibility across different model architectures. 

5175 

5176 Returns: 

5177 dict: Dictionary of parameter tensors with TransformerLens naming convention 

5178 

5179 Raises: 

5180 ValueError: If configuration is inconsistent (e.g., cfg.n_layers != len(blocks)) 

5181 """ 

5182 return get_bridge_params(self) 

5183 

5184 # NOTE: list_supported_models and check_model_support are attached to this class 

5185 # dynamically by transformer_lens.model_bridge.sources.transformers module. 

5186 # These are HuggingFace-specific methods that belong in the transformers source module.