Coverage for transformer_lens/model_bridge/architecture_adapter.py: 80%

483 statements  

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

1"""Architecture adapter base class. 

2 

3This module contains the base class for architecture adapters that map between different model architectures. 

4""" 

5from dataclasses import dataclass, field 

6from typing import Any, Dict, Optional, cast 

7 

8import torch 

9 

10from transformer_lens.config import TransformerBridgeConfig 

11from transformer_lens.conversion_utils.conversion_steps.rearrange_tensor_conversion import ( 

12 RearrangeTensorConversion, 

13) 

14from transformer_lens.conversion_utils.param_processing_conversion import ( 

15 ParamProcessingConversion, 

16) 

17from transformer_lens.model_bridge.generalized_components.attention import ( 

18 AttentionBridge, 

19) 

20from transformer_lens.model_bridge.generalized_components.base import ( 

21 GeneralizedComponent, 

22) 

23from transformer_lens.model_bridge.generalized_components.gated_mlp import ( 

24 GatedMLPBridge, 

25) 

26from transformer_lens.model_bridge.generalized_components.linear import LinearBridge 

27from transformer_lens.model_bridge.generalized_components.mlp import MLPBridge 

28from transformer_lens.model_bridge.generalized_components.position_embeddings_attention import ( 

29 PositionEmbeddingsAttentionBridge, 

30) 

31from transformer_lens.model_bridge.types import ( 

32 ComponentMapping, 

33 RemoteComponent, 

34 RemoteModel, 

35 RemotePath, 

36 TransformerLensPath, 

37) 

38from transformer_lens.utilities.activation_functions import apply_softcap 

39from transformer_lens.utilities.attn_implementation import force_eager_attention 

40 

41 

42@dataclass(frozen=True) 

43class ResidualLayout: 

44 """Where each LayerNorm's output goes and what writes to each residual stream. 

45 

46 Covers pre-LN architectures the decoder-only ``blocks.{i}`` weight-processing walk 

47 cannot handle, such as encoder-decoders with cross-attention. Entries are 

48 state-dict prefixes of components with HF ``nn.Linear`` / ``nn.Embedding`` 

49 layout (``[out, in]`` weights, ``[n, d_model]`` tables). 

50 

51 Attributes: 

52 norm_readers: Each LayerNorm prefix mapped to the linears that read its output. 

53 residual_writers: Linears whose output is added to a residual stream. 

54 embedding_writers: Embedding tables whose rows are added to a residual stream. 

55 value_output_pairs: ``(value, output)`` linears of each attention. 

56 """ 

57 

58 norm_readers: Dict[str, list[str]] 

59 residual_writers: list[str] = field(default_factory=list) 

60 embedding_writers: list[str] = field(default_factory=list) 

61 value_output_pairs: list[tuple[str, str]] = field(default_factory=list) 

62 

63 

64class ArchitectureAdapter: 

65 """Base class for architecture adapters. 

66 

67 This class provides the interface for adapting between different model architectures. 

68 It handles both component mapping (for accessing model parts) and weight conversion 

69 (for initializing weights from one format to another). 

70 """ 

71 

72 default_cfg: dict[str, Any] = {} 

73 

74 # verify_models phase applicability. Architectures that cannot participate 

75 # in specific phases (e.g. SSMs don't have the transformer-shaped hooks/ 

76 # weights the benchmark phases assume) should override. An empty list 

77 # means "skip verify_models entirely; verification lives in integration 

78 # tests." 

79 applicable_phases: list[int] = [1, 2, 3, 4] 

80 

81 # Whether this architecture supports text generation via generate(). 

82 # Encoder-only models (e.g. BERT, HuBERT) should set this to False. 

83 supports_generation: bool = True 

84 

85 # Whether the wrapped forward speaks the HF KV-cache protocol. False for 

86 # recurrent/convolutional decoders (RWKV's bespoke `state`, HyenaDNA's 

87 # kwarg-less FFT forward): generation then recomputes the full prefix each 

88 # step, which is exact but O(n^2). 

89 supports_kv_cache: bool = True 

90 

91 # Whether batched generation is sound. False where the wrapped forward 

92 # ignores attention_mask (RWKV) or rejects it (HyenaDNA), so left-padding 

93 # would silently corrupt results rather than be masked out. 

94 supports_batched_generation: bool = True 

95 

96 # Name of a native non-autoregressive sampler on the wrapped model, exposed 

97 # via bridge.diffusion_generate() (e.g. Dream's "diffusion_generate", 

98 # LLaDA2's/Gidd's "generate"). None means the architecture has none. 

99 native_sampler: Optional[str] = None 

100 

101 def native_sampler_kwargs(self, max_new_tokens: int, prompt_len: int) -> Dict[str, Any]: 

102 """Map a token budget onto the native sampler's own parameter names 

103 (diffusion samplers each spell the budget differently).""" 

104 return {"max_new_tokens": max_new_tokens} 

105 

106 # Runtime gate for enable_compatibility_mode(): set False when the stored- 

107 # processed-weights forward is known to diverge (e.g. VaultGemma). 

108 supports_compatibility_mode: bool = True 

109 # Component paths (by suffix) whose isolated forward cannot run on the 

110 # component harness's synthesized probes — e.g. fused top-k routers whose 

111 # forward sorts/scatters. They stay hookable at runtime. 

112 component_test_skip_suffixes: tuple = () 

113 

114 # Whether run_with_cache should request attention tensors from Hugging Face. 

115 # Set False when an adapter reconstructs those tensors but the HF wrapper 

116 # rejects output_attentions=True. 

117 supports_hf_output_attentions: bool = True 

118 

119 # Whether Bridge's shifted next-token cross-entropy is meaningful. 

120 supports_causal_loss: bool = True 

121 

122 # Keyword the wrapped HF forward takes audio under. Read by the audio seq2seq 

123 # forward path (cfg.is_audio_seq2seq), e.g. Whisper's log-mel "input_features". 

124 audio_input_name: str = "input_values" 

125 

126 # HF-style 4D boolean attention masks keep positions marked True. Override 

127 # for architectures whose forward path uses True to block attention. 

128 bool_4d_mask_is_keep: bool = True 

129 

130 # Optional libraries this adapter needs at load time (e.g. the multimodal group's timm). 

131 # Checked at construction so a missing one raises a clear error, not a deep HF failure. 

132 required_libraries: list[str] = [] 

133 # Dependency group that ships required_libraries (named in the error); empty on the base. 

134 required_libraries_group: str = "" 

135 

136 def __init__(self, cfg: TransformerBridgeConfig) -> None: 

137 """Initialize the architecture adapter. 

138 

139 Args: 

140 cfg: The configuration object. 

141 """ 

142 self._check_required_libraries() 

143 self.cfg = cfg 

144 self.component_mapping: ComponentMapping | None = None 

145 self.weight_processing_conversions: Dict[str, ParamProcessingConversion | str] | None = None 

146 self.uses_split_attention: bool = getattr(cfg, "uses_split_attention", False) 

147 self._fold_ln_requested: bool = True 

148 # State-dict keys of weights stored [in, out] (Conv1D), set before weight processing. 

149 self._in_out_weight_keys: set[str] = set() 

150 self._merge_default_config() 

151 

152 def _check_required_libraries(self) -> None: 

153 """Raise a clear error if an optional library this adapter needs is not installed.""" 

154 import importlib.util 

155 

156 missing = [lib for lib in self.required_libraries if importlib.util.find_spec(lib) is None] 

157 if missing: 

158 joined = ", ".join(missing) 

159 plural = "y" if len(missing) == 1 else "ies" 

160 group = self.required_libraries_group 

161 group_clause = f" from the '{group}' dependency group" if group else "" 

162 contrib = f" (contributors: `uv sync --group {group}`)" if group else "" 

163 raise ImportError( 

164 f"{type(self).__name__} needs the optional {joined} librar{plural}{group_clause}. " 

165 f"Install with `pip install {' '.join(missing)}`{contrib}." 

166 ) 

167 

168 def _merge_default_config(self) -> None: 

169 """Merge default_cfg into cfg for variables that don't exist in cfg.""" 

170 for key, value in self.default_cfg.items(): 

171 if not hasattr(self.cfg, key): 171 ↛ 170line 171 didn't jump to line 170 because the condition on line 171 was always true

172 setattr(self.cfg, key, value) 

173 

174 def _gated_mlp( 

175 self, 

176 name: str = "mlp", 

177 *, 

178 gate: str = "gate_proj", 

179 up: str = "up_proj", 

180 down: str = "down_proj", 

181 optional: bool = False, 

182 ) -> GatedMLPBridge: 

183 """GatedMLPBridge with the standard gate/in/out LinearBridge submodules 

184 (up->in, down->out).""" 

185 return GatedMLPBridge( 

186 name=name, 

187 config=self.cfg, 

188 submodules={ 

189 "gate": LinearBridge(name=gate), 

190 "in": LinearBridge(name=up), 

191 "out": LinearBridge(name=down), 

192 }, 

193 optional=optional, 

194 ) 

195 

196 @property 

197 def components(self) -> ComponentMapping: 

198 """component_mapping, asserted built — for subclasses that extend or edit 

199 a parent's mapping without per-file None narrowing.""" 

200 assert self.component_mapping is not None, "component_mapping has not been built" 

201 return self.component_mapping 

202 

203 def _ungated_mlp( 

204 self, 

205 name: str = "mlp", 

206 *, 

207 up: str = "up_proj", 

208 down: str = "down_proj", 

209 optional: bool = False, 

210 ) -> MLPBridge: 

211 """MLPBridge with the standard in/out LinearBridge submodules (up->in, down->out).""" 

212 return MLPBridge( 

213 name=name, 

214 config=self.cfg, 

215 submodules={ 

216 "in": LinearBridge(name=up), 

217 "out": LinearBridge(name=down), 

218 }, 

219 optional=optional, 

220 ) 

221 

222 # Attention class _qkvo_attention_bridge instantiates; families with bespoke 

223 # attention (BitNet, EXAONE-4) swap in a subclass. 

224 _attention_bridge_cls: type[AttentionBridge] = PositionEmbeddingsAttentionBridge 

225 

226 def _qkvo_attention_bridge( 

227 self, 

228 *, 

229 optional: bool = False, 

230 extra_submodules: Optional[Dict[str, GeneralizedComponent]] = None, 

231 requires_attention_mask: Optional[bool] = True, 

232 requires_position_embeddings: Optional[bool] = True, 

233 ) -> AttentionBridge: 

234 """``self_attn`` bridge from ``_attention_bridge_cls`` with the standard 

235 q/k/v/o LinearBridge submodules. A None flag is omitted from the 

236 constructor call so the bridge class's own default applies.""" 

237 submodules: Dict[str, GeneralizedComponent] = { 

238 "q": LinearBridge(name="q_proj"), 

239 "k": LinearBridge(name="k_proj"), 

240 "v": LinearBridge(name="v_proj"), 

241 "o": LinearBridge(name="o_proj"), 

242 } 

243 if extra_submodules: 

244 submodules.update(extra_submodules) 

245 flags: Dict[str, Any] = {} 

246 if requires_attention_mask is not None: 

247 flags["requires_attention_mask"] = requires_attention_mask 

248 if requires_position_embeddings is not None: 

249 flags["requires_position_embeddings"] = requires_position_embeddings 

250 return self._attention_bridge_cls( 

251 name="self_attn", 

252 config=self.cfg, 

253 optional=optional, 

254 submodules=submodules, 

255 **flags, 

256 ) 

257 

258 def _build_attention_bridge(self) -> AttentionBridge: 

259 """Attention bridge seam; subclasses swap the class or the construction.""" 

260 return self._qkvo_attention_bridge() 

261 

262 def _canonical_layer_types(self, cfg: Any) -> list[str]: 

263 """Per-layer mixer-type list, normalized to canonical TL names 

264 (mamba->linear_attention, attention->full_attention; others pass through).""" 

265 aliases = {"mamba": "linear_attention", "attention": "full_attention"} 

266 raw = getattr(cfg, "layers_block_type", None) or getattr(cfg, "layer_types", None) or [] 

267 return [aliases.get(t, t) for t in raw] 

268 

269 def _extract_vision_dims(self, cfg: Any) -> None: 

270 """Copy vision-tower dims onto cfg, handling both HF-standard naming 

271 (num_hidden_layers/num_attention_heads) and Qwen-style (depth/num_heads).""" 

272 vision_cfg = getattr(cfg, "vision_config", None) 

273 if vision_cfg is None: 

274 return 

275 self.cfg.vision_hidden_size = getattr(vision_cfg, "hidden_size", None) 

276 self.cfg.vision_num_layers = getattr( 

277 vision_cfg, "num_hidden_layers", getattr(vision_cfg, "depth", None) 

278 ) 

279 self.cfg.vision_num_heads = getattr( 

280 vision_cfg, "num_attention_heads", getattr(vision_cfg, "num_heads", None) 

281 ) 

282 

283 def _set_rms_rotary_defaults(self, *, final_rms: bool = True, gated: bool = True) -> None: 

284 """Set the Llama-family config flags: RMS norms, rotary positions, gated MLP 

285 (final_rms is per-architecture -- Mistral/Mixtral/OLMoE set False; gated=False 

286 for squared-ReLU/plain-MLP families like Gidd and NanoChat).""" 

287 self.cfg.normalization_type = "RMS" 

288 self.cfg.positional_embedding_type = "rotary" 

289 self.cfg.final_rms = final_rms 

290 self.cfg.gated_mlp = gated 

291 self.cfg.attn_only = False 

292 self.cfg.uses_rms_norm = True 

293 

294 def apply_output_logits_transform(self, logits: torch.Tensor) -> torch.Tensor: 

295 """Apply the architecture's declared post-unembedding transform. 

296 

297 Most causal decoders only apply the shared optional Gemma-style soft cap. 

298 Adapters with additional scaling override this method instead of relying 

299 on similarly named configuration fields used by unrelated architectures. 

300 """ 

301 return apply_softcap(logits, getattr(self.cfg, "output_logits_soft_cap", None)) 

302 

303 def validate_output_logits_transform(self) -> None: 

304 """Validate that the adapter can reproduce its post-unembedding path.""" 

305 

306 def _qkvo_weight_conversions( 

307 self, n_kv_heads: Optional[int] = None, include_biases: bool = False 

308 ) -> Dict[str, ParamProcessingConversion]: 

309 """Standard Q/K/V/O weight rearrangement conversions. 

310 

311 Most decoder-only models use the same rearrange patterns for attention 

312 weights. Override only when your model's layout differs. 

313 

314 Args: 

315 n_kv_heads: Number of KV heads for GQA. If None, falls back to n_heads. 

316 include_biases: Also emit Q/K/V bias reshapes. K/V use the kv-head 

317 count — a hand-rolled n_heads reshape breaks on GQA checkpoints. 

318 """ 

319 if n_kv_heads is None: 

320 n_kv_heads = getattr(self.cfg, "n_key_value_heads", None) or self.cfg.n_heads 

321 conversions = { 

322 "blocks.{i}.attn.q.weight": ParamProcessingConversion( 

323 tensor_conversion=RearrangeTensorConversion("(n h) m -> n m h", n=self.cfg.n_heads), 

324 ), 

325 "blocks.{i}.attn.k.weight": ParamProcessingConversion( 

326 tensor_conversion=RearrangeTensorConversion("(n h) m -> n m h", n=n_kv_heads), 

327 ), 

328 "blocks.{i}.attn.v.weight": ParamProcessingConversion( 

329 tensor_conversion=RearrangeTensorConversion("(n h) m -> n m h", n=n_kv_heads), 

330 ), 

331 "blocks.{i}.attn.o.weight": ParamProcessingConversion( 

332 tensor_conversion=RearrangeTensorConversion("m (n h) -> n h m", n=self.cfg.n_heads), 

333 ), 

334 } 

335 if include_biases: 

336 conversions.update( 

337 { 

338 "blocks.{i}.attn.q.bias": ParamProcessingConversion( 

339 tensor_conversion=RearrangeTensorConversion( 

340 "(h d_head) -> h d_head", h=self.cfg.n_heads 

341 ), 

342 ), 

343 "blocks.{i}.attn.k.bias": ParamProcessingConversion( 

344 tensor_conversion=RearrangeTensorConversion( 

345 "(h d_head) -> h d_head", h=n_kv_heads 

346 ), 

347 ), 

348 "blocks.{i}.attn.v.bias": ParamProcessingConversion( 

349 tensor_conversion=RearrangeTensorConversion( 

350 "(h d_head) -> h d_head", h=n_kv_heads 

351 ), 

352 ), 

353 } 

354 ) 

355 return conversions 

356 

357 def _reprefix_components(self, old: str, new: str) -> None: 

358 """Rewrite component names starting with ``old`` to start with ``new``. 

359 

360 For adapters that reuse a parent mapping under a different module 

361 nesting (e.g. a multimodal wrapper's ``model.language_model.``). 

362 """ 

363 assert self.component_mapping is not None 

364 for component in self.component_mapping.values(): 

365 if component.name and component.name.startswith(old): 

366 component.name = new + component.name[len(old) :] 

367 

368 def preprocess_weights(self, state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]: 

369 """Apply architecture-specific weight transformations before ProcessWeights. 

370 

371 This method allows architectures to apply custom transformations to weights 

372 before standard weight processing (fold_layer_norm, center_writing_weights, etc.). 

373 For example, Gemma models scale embeddings by sqrt(d_model). 

374 

375 Args: 

376 state_dict: The state dictionary, keyed in TransformerLens format. The caller 

377 passes ``bridge.state_dict()``, so keys have already been renamed by 

378 ``convert_hf_key_to_tl_key`` — match ``blocks.0.attn.q.weight``, not 

379 ``model.layers.0.self_attn.q_proj.weight``. An override that matches 

380 HuggingFace names silently matches nothing. 

381 

382 Returns: 

383 The modified state dictionary (default implementation returns unchanged) 

384 """ 

385 return state_dict 

386 

387 def residual_layout(self) -> Optional[ResidualLayout]: 

388 """Explicit norm/residual layout for weight processing, or None to use the 

389 decoder-only ``blocks.{i}`` walk. Override for architectures that walk misses.""" 

390 return None 

391 

392 def postprocess_weights(self, bridge: Any) -> None: 

393 """Apply architecture-specific updates after processed weights are installed. 

394 

395 Args: 

396 bridge: The TransformerBridge whose live source components received the weights. 

397 """ 

398 

399 def get_component_mapping(self) -> ComponentMapping: 

400 """Get the full component mapping. 

401 

402 Returns: 

403 The component mapping dictionary 

404 

405 Raises: 

406 ValueError: If the component mapping is not set 

407 """ 

408 if self.component_mapping is None: 408 ↛ 409line 408 didn't jump to line 409 because the condition on line 408 was never true

409 raise ValueError("component_mapping must be set before calling get_component_mapping") 

410 return self.component_mapping 

411 

412 def get_remote_component(self, model: RemoteModel, path: RemotePath) -> RemoteComponent: 

413 """Get a component from a remote model by its path. 

414 

415 This method should be overridden by subclasses to provide the logic for 

416 accessing components in a specific model architecture. 

417 

418 Args: 

419 model: The remote model 

420 path: The path to the component in the remote model's format 

421 

422 Returns: 

423 The component (e.g., a PyTorch module) 

424 

425 Raises: 

426 AttributeError: If a component in the path doesn't exist 

427 IndexError: If an invalid index is accessed 

428 ValueError: If the path is empty or invalid 

429 

430 Examples: 

431 Get an embedding component: 

432 

433 >>> # adapter.get_remote_component(model, "model.embed_tokens") 

434 >>> # <Embedding> 

435 

436 Get a transformer block: 

437 

438 >>> # adapter.get_remote_component(model, "model.layers.0") 

439 >>> # <TransformerBlock> # type: ignore[index] 

440 

441 Get a layer norm component: 

442 

443 >>> # adapter.get_remote_component(model, "model.layers.0.ln1") 

444 >>> # <LayerNorm> 

445 """ 

446 current = model 

447 parent_stack: list[RemoteComponent] = [] # Track parent components for .. navigation 

448 

449 # Handle ../ pattern by replacing with a marker before splitting 

450 # This is needed because "../output.dense".split(".") gives ['', '', '/output', 'dense'] 

451 path_with_markers = path.replace("../", "##PARENT##.") 

452 

453 for part in path_with_markers.split("."): 

454 # If current is a GeneralizedComponent bridge, unwrap to get the original HF component 

455 if ( 

456 isinstance(current, GeneralizedComponent) 

457 and hasattr(current, "original_component") 

458 and current.original_component is not None 

459 ): 

460 current = current.original_component 

461 

462 if part == "##PARENT##": 462 ↛ 464line 462 didn't jump to line 464 because the condition on line 462 was never true

463 # Navigate to parent component (from ../ syntax) 

464 if not parent_stack: 

465 raise ValueError(f"Cannot navigate above root in path: {path}") 

466 current = parent_stack.pop() 

467 elif part == "..": 467 ↛ 469line 467 didn't jump to line 469 because the condition on line 467 was never true

468 # Navigate to parent component (from plain .. syntax) 

469 if not parent_stack: 

470 raise ValueError(f"Cannot navigate above root in path: {path}") 

471 current = parent_stack.pop() 

472 elif part.isdigit(): 

473 parent_stack.append(current) 

474 current = current[int(part)] # type: ignore[index] 

475 else: 

476 parent_stack.append(current) 

477 current = getattr(current, part) 

478 return current 

479 

480 def get_component_from_list_module( 

481 self, list_module: RemoteComponent, bridge_component: GeneralizedComponent, parts: list[str] 

482 ) -> RemoteComponent: 

483 """Get a component from a list module using the bridge component and the transformer lens path. 

484 Args: 

485 list_module: The remote list module to get the component from 

486 bridge_component: The bridge component 

487 parts: The parts of the transformer lens path to navigate 

488 Returns: 

489 The requested component from the list module described by the path 

490 """ 

491 item_index = parts[1] 

492 if not item_index.isdigit(): 

493 raise ValueError(f"Expected item index, got {item_index}") 

494 if not hasattr(list_module, "__getitem__"): 494 ↛ 495line 494 didn't jump to line 495 because the condition on line 494 was never true

495 raise TypeError(f"Component {bridge_component.name} is not indexable") 

496 indexable_container = cast(Any, list_module) 

497 item = indexable_container[int(item_index)] 

498 if len(parts) == 2: 

499 return item 

500 else: 

501 subcomponent_name = parts[2] 

502 if subcomponent_name in bridge_component.submodules: 502 ↛ 532line 502 didn't jump to line 532 because the condition on line 502 was always true

503 subcomponent_bridge = bridge_component.submodules[subcomponent_name] 

504 if len(parts) > 3: 

505 current_bridge = subcomponent_bridge 

506 if subcomponent_bridge.name is None: 506 ↛ 507line 506 didn't jump to line 507 because the condition on line 506 was never true

507 current = item 

508 else: 

509 current = self.get_remote_component(item, subcomponent_bridge.name) 

510 for i in range(3, len(parts)): 

511 deeper_component_name = parts[i] 

512 if deeper_component_name.isdigit() and current_bridge.is_list_item: 512 ↛ 513line 512 didn't jump to line 513 because the condition on line 512 was never true

513 return self.get_component_from_list_module( 

514 current, current_bridge, parts[i - 1 :] 

515 ) 

516 if deeper_component_name in current_bridge.submodules: 516 ↛ 523line 516 didn't jump to line 523 because the condition on line 516 was always true

517 current_bridge = current_bridge.submodules[deeper_component_name] 

518 if current_bridge.name is None: 518 ↛ 519line 518 didn't jump to line 519 because the condition on line 518 was never true

519 pass 

520 else: 

521 current = self.get_remote_component(current, current_bridge.name) 

522 else: 

523 raise ValueError( 

524 f"Component {deeper_component_name} not found in {'.'.join(parts[:i])} components" 

525 ) 

526 return current 

527 elif subcomponent_bridge.name is None: 527 ↛ 528line 527 didn't jump to line 528 because the condition on line 527 was never true

528 return item 

529 else: 

530 return self.get_remote_component(item, subcomponent_bridge.name) 

531 else: 

532 raise ValueError( 

533 f"Component {subcomponent_name} not found in {parts[0]} components" 

534 ) 

535 

536 def get_generalized_component(self, path: TransformerLensPath) -> GeneralizedComponent: 

537 """Get the generalized component (bridge component) for a given TransformerLens path. 

538 

539 Args: 

540 path: The TransformerLens path to get the component for 

541 

542 Returns: 

543 The generalized component that handles this path 

544 

545 Raises: 

546 ValueError: If component_mapping is not set or if the component is not found 

547 

548 Examples: 

549 Get the embedding bridge component: 

550 

551 >>> # adapter.get_generalized_component("embed") 

552 >>> # <EmbeddingBridge> 

553 

554 Get the attention bridge component: 

555 

556 >>> # adapter.get_generalized_component("blocks.0.attn") 

557 >>> # <AttentionBridge> 

558 """ 

559 if self.component_mapping is None: 

560 raise ValueError( 

561 "component_mapping must be set before calling get_generalized_component" 

562 ) 

563 component_path, _ = self._preprocess_parameter_path(path) 

564 parts = component_path.split(".") 

565 if not parts: 565 ↛ 566line 565 didn't jump to line 566 because the condition on line 565 was never true

566 raise ValueError("Empty path") 

567 if parts[0] not in self.component_mapping: 

568 raise ValueError(f"Component {parts[0]} not found in component mapping") 

569 bridge_component = self.component_mapping[parts[0]] 

570 if len(parts) == 1: 

571 return bridge_component 

572 current_component = bridge_component 

573 for i in range(1, len(parts)): 

574 part = parts[i] 

575 if part.isdigit(): 

576 continue 

577 if hasattr(current_component, "submodules") and part in current_component.submodules: 

578 current_component = current_component.submodules[part] 

579 elif ( 579 ↛ 584line 579 didn't jump to line 584 because the condition on line 579 was never true

580 hasattr(current_component, "__class__") 

581 and "AttentionBridge" in current_component.__class__.__name__ 

582 and (part in ["q", "k", "v", "o"]) 

583 ): 

584 if "JointQKV" in current_component.__class__.__name__: 

585 continue 

586 elif ( 

587 hasattr(current_component, "submodules") 

588 and part in current_component.submodules 

589 ): 

590 current_component = current_component.submodules[part] 

591 continue 

592 elif ( 592 ↛ 597line 592 didn't jump to line 597 because the condition on line 592 was never true

593 hasattr(current_component, "__class__") 

594 and "MLPBridge" in current_component.__class__.__name__ 

595 and (part in ["in", "out", "gate"]) 

596 ): 

597 if ( 

598 hasattr(current_component, "submodules") 

599 and part in current_component.submodules 

600 ): 

601 current_component = current_component.submodules[part] 

602 continue 

603 else: 

604 continue 

605 else: 

606 raise ValueError(f"Component {part} not found in {'.'.join(parts[:i])} components") 

607 return current_component 

608 

609 def get_component(self, model: RemoteModel, path: TransformerLensPath) -> RemoteComponent: 

610 """Get a component from the model using the component_mapping. 

611 

612 Args: 

613 model: The model to extract components from 

614 path: The path of the component to get, as defined in component_mapping 

615 

616 Returns: 

617 The requested component from the model 

618 

619 Raises: 

620 ValueError: If component_mapping is not set or if the component is not found 

621 AttributeError: If a component in the path doesn't exist 

622 IndexError: If an invalid index is accessed 

623 

624 Examples: 

625 Get an embedding component: 

626 

627 >>> # adapter.get_component(model, "embed") 

628 >>> # <Embedding> 

629 

630 Get a transformer block: 

631 

632 >>> # adapter.get_component(model, "blocks.0") 

633 >>> # <TransformerBlock> 

634 

635 Get a layer norm component: 

636 

637 >>> # adapter.get_component(model, "blocks.0.ln1") 

638 >>> # <LayerNorm> 

639 """ 

640 if self.component_mapping is None: 640 ↛ 641line 640 didn't jump to line 641 because the condition on line 640 was never true

641 raise ValueError("component_mapping must be set before calling get_component") 

642 parts = path.split(".") 

643 if not parts: 643 ↛ 644line 643 didn't jump to line 644 because the condition on line 643 was never true

644 raise ValueError("Empty path") 

645 if self.component_mapping is None or parts[0] not in self.component_mapping: 

646 raise ValueError(f"Component {parts[0]} not found in component mapping") 

647 bridge_component = self.component_mapping[parts[0]] 

648 if len(parts) == 1: 

649 if bridge_component.name is None: 649 ↛ 650line 649 didn't jump to line 650 because the condition on line 649 was never true

650 return model 

651 return self.get_remote_component(model, bridge_component.name) 

652 if bridge_component.is_list_item and len(parts) >= 2: 652 ↛ 657line 652 didn't jump to line 657 because the condition on line 652 was always true

653 if bridge_component.name is None: 653 ↛ 654line 653 didn't jump to line 654 because the condition on line 653 was never true

654 raise ValueError(f"List component {parts[0]} must have a name") 

655 list_module = self.get_remote_component(model, bridge_component.name) 

656 return self.get_component_from_list_module(list_module, bridge_component, parts) 

657 remote_path = bridge_component.name 

658 if remote_path is None: 

659 raise ValueError(f"Component {parts[0]} must have a name for nested paths") 

660 if len(parts) > 1: 

661 remote_path = f"{remote_path}.{'.'.join(parts[1:])}" 

662 return self.get_remote_component(model, remote_path) 

663 

664 def translate_transformer_lens_path( 

665 self, path: TransformerLensPath, last_component_only: bool = False 

666 ) -> RemotePath: 

667 """Translate a TransformerLens path to a remote model path. 

668 

669 Args: 

670 path: The TransformerLens path to translate 

671 last_component_only: If True, return only the last component of the path 

672 

673 Returns: 

674 The corresponding remote model path 

675 

676 Raises: 

677 ValueError: If the path is not found in the component mapping 

678 """ 

679 if self.component_mapping is None: 679 ↛ 680line 679 didn't jump to line 680 because the condition on line 679 was never true

680 raise ValueError( 

681 "component_mapping must be set before calling translate_transformer_lens_path" 

682 ) 

683 path, param_suffix = self._preprocess_parameter_path(path) 

684 parts = path.split(".") 

685 if not parts: 685 ↛ 686line 685 didn't jump to line 686 because the condition on line 685 was never true

686 raise ValueError("Empty path") 

687 if parts[0] not in self.component_mapping: 

688 raise ValueError(f"Component {parts[0]} not found in component mapping") 

689 bridge_component = self.component_mapping[parts[0]] 

690 if len(parts) == 1: 

691 remote_path = bridge_component.name 

692 if remote_path is None: 692 ↛ 693line 692 didn't jump to line 693 because the condition on line 692 was never true

693 raise ValueError(f"Component {parts[0]} must have a name for path translation") 

694 if param_suffix: 

695 remote_path = remote_path + param_suffix 

696 if last_component_only: 

697 return remote_path.split(".")[-1] 

698 return remote_path 

699 if bridge_component.is_list_item and len(parts) >= 2: 699 ↛ 755line 699 didn't jump to line 755 because the condition on line 699 was always true

700 item_index = parts[1] 

701 if not item_index.isdigit(): 

702 raise ValueError(f"Expected item index, got {item_index}") 

703 items_path = bridge_component.name 

704 if items_path is None: 704 ↛ 705line 704 didn't jump to line 705 because the condition on line 704 was never true

705 raise ValueError(f"List component {parts[0]} must have a name for path translation") 

706 if len(parts) == 2: 

707 remote_path = f"{items_path}.{item_index}" 

708 if param_suffix: 708 ↛ 709line 708 didn't jump to line 709 because the condition on line 708 was never true

709 remote_path = remote_path + param_suffix 

710 if last_component_only: 

711 return remote_path.split(".")[-1] 

712 return remote_path 

713 else: 

714 subcomponent_name = parts[2] 

715 if subcomponent_name in bridge_component.submodules: 

716 subcomponent_bridge = bridge_component.submodules[subcomponent_name] 

717 if len(parts) > 3: 

718 current_bridge = subcomponent_bridge 

719 remote_path_parts = [items_path, item_index] 

720 if subcomponent_bridge.name is not None: 

721 remote_path_parts.append(subcomponent_bridge.name) 

722 for i in range(3, len(parts)): 

723 deeper_component_name = parts[i] 

724 if deeper_component_name in current_bridge.submodules: 724 ↛ 730line 724 didn't jump to line 730 because the condition on line 724 was always true

725 current_bridge = current_bridge.submodules[deeper_component_name] 

726 deeper_name = current_bridge.name 

727 if deeper_name is not None: 727 ↛ 722line 727 didn't jump to line 722 because the condition on line 727 was always true

728 remote_path_parts.append(deeper_name) 

729 else: 

730 raise ValueError( 

731 f"Component {deeper_component_name} not found in {'.'.join(parts[:i])} components" 

732 ) 

733 remote_path = ".".join(remote_path_parts) 

734 if param_suffix: 

735 remote_path = remote_path + param_suffix 

736 if last_component_only: 

737 return remote_path.split(".")[-1] 

738 return remote_path 

739 else: 

740 subcomponent_name_str = subcomponent_bridge.name 

741 if subcomponent_name_str is None: 

742 raise ValueError( 

743 f"Synthetic component {subcomponent_name} has no remote path" 

744 ) 

745 remote_path = f"{items_path}.{item_index}.{subcomponent_name_str}" 

746 if param_suffix: 

747 remote_path = remote_path + param_suffix 

748 if last_component_only: 

749 return remote_path.split(".")[-1] 

750 return remote_path 

751 else: 

752 raise ValueError( 

753 f"Component {subcomponent_name} not found in {parts[0]} components" 

754 ) 

755 remote_path = bridge_component.name 

756 if remote_path is None: 

757 raise ValueError(f"Component {parts[0]} must have a name for path translation") 

758 if len(parts) > 1: 

759 remote_path = f"{remote_path}.{'.'.join(parts[1:])}" 

760 if param_suffix: 

761 remote_path = remote_path + param_suffix 

762 if last_component_only: 

763 return remote_path.split(".")[-1] 

764 return remote_path 

765 

766 def _preprocess_parameter_path(self, path: str) -> tuple[str, str]: 

767 """Preprocess TransformerLens path to map parameter names to component names. 

768 

769 Args: 

770 path: The original TransformerLens path 

771 

772 Returns: 

773 Tuple of (preprocessed_path, parameter_suffix) 

774 """ 

775 param_suffix = "" 

776 if path.endswith( 

777 ( 

778 ".W_Q", 

779 ".W_K", 

780 ".W_V", 

781 ".W_O", 

782 ".W_in", 

783 ".W_out", 

784 ".W_gate", 

785 ".W_E", 

786 ".W_U", 

787 ".W_pos", 

788 ".w", 

789 "._W_K", 

790 "._W_V", 

791 ) 

792 ): 

793 param_suffix = ".weight" 

794 elif path.endswith( 

795 ( 

796 ".b_Q", 

797 ".b_K", # type: ignore[assignment] 

798 ".b_V", 

799 ".b_O", 

800 ".b_in", 

801 ".b_out", 

802 ".b_gate", 

803 ".b_E", 

804 ".b_U", 

805 ".b_pos", 

806 ".b", 

807 "._b_K", 

808 "._b_V", 

809 ) 

810 ): 

811 param_suffix = ".bias" 

812 if any( 

813 ( 

814 path.endswith(suffix) 

815 for suffix in [ 

816 ".W_Q", 

817 ".W_K", 

818 ".W_V", 

819 ".b_Q", 

820 ".b_K", 

821 ".b_V", 

822 "._W_K", 

823 "._W_V", 

824 "._b_K", 

825 "._b_V", 

826 ] 

827 ) 

828 ): 

829 attn_path_parts = path.split(".") 

830 if len(attn_path_parts) >= 3 and attn_path_parts[-2] == "attn": 830 ↛ 857line 830 didn't jump to line 857 because the condition on line 830 was always true

831 attn_component_path = ".".join(attn_path_parts[:-1]) 

832 try: 

833 if self.component_mapping: 833 ↛ 857line 833 didn't jump to line 857 because the condition on line 833 was always true

834 current_mapping = self.component_mapping 

835 for part in attn_component_path.split("."): 

836 if ( 

837 hasattr(current_mapping, "submodules") 

838 and part in current_mapping.submodules 

839 ): 

840 current_mapping = current_mapping.submodules[part] 

841 elif hasattr(current_mapping, "__getitem__"): 

842 current_mapping = current_mapping[part] # type: ignore[assignment] 

843 if hasattr(current_mapping, "submodules"): 843 ↛ 857line 843 didn't jump to line 857 because the condition on line 843 was always true

844 attn_components = list(current_mapping.submodules.keys()) 

845 path = path.replace(".W_Q", ".q") 

846 path = path.replace(".W_K", ".k") 

847 path = path.replace(".W_V", ".v") 

848 path = path.replace(".b_Q", ".q") 

849 path = path.replace(".b_K", ".k") 

850 path = path.replace(".b_V", ".v") 

851 path = path.replace("._W_K", ".k") 

852 path = path.replace("._W_V", ".v") 

853 path = path.replace("._b_K", ".k") 

854 path = path.replace("._b_V", ".v") 

855 except Exception: 

856 pass 

857 if any( 857 ↛ 860line 857 didn't jump to line 860 because the condition on line 857 was never true

858 (path.endswith(suffix) for suffix in [".W_Q", ".W_K", ".W_V", ".b_Q", ".b_K", ".b_V"]) 

859 ): 

860 path = path.replace(".W_Q", ".q") 

861 path = path.replace(".W_K", ".k") 

862 path = path.replace(".W_V", ".v") 

863 path = path.replace(".b_Q", ".q") 

864 path = path.replace(".b_K", ".k") 

865 path = path.replace(".b_V", ".v") 

866 path = path.replace(".W_O", ".o") 

867 path = path.replace(".b_O", ".o") 

868 if any( 

869 ( 

870 path.endswith(suffix) 

871 for suffix in [".W_in", ".W_out", ".b_in", ".b_out", ".ln.w", ".ln.b"] 

872 ) 

873 ): 

874 mlp_path_parts = path.split(".") 

875 if len(mlp_path_parts) >= 3 and mlp_path_parts[-2] == "mlp": 875 ↛ 910line 875 didn't jump to line 910 because the condition on line 875 was always true

876 mlp_component_path = ".".join(mlp_path_parts[:-1]) 

877 try: 

878 if self.component_mapping: 878 ↛ 910line 878 didn't jump to line 910 because the condition on line 878 was always true

879 current_mapping = self.component_mapping 

880 for part in mlp_component_path.split("."): 

881 if ( 

882 hasattr(current_mapping, "submodules") 

883 and part in current_mapping.submodules 

884 ): 

885 current_mapping = current_mapping.submodules[part] 

886 elif hasattr(current_mapping, "__getitem__"): 

887 current_mapping = current_mapping[part] # type: ignore[assignment] 

888 if hasattr(current_mapping, "submodules"): 888 ↛ 910line 888 didn't jump to line 910 because the condition on line 888 was always true

889 mlp_components = list(current_mapping.submodules.keys()) 

890 if "input" in mlp_components and "out" in mlp_components: 890 ↛ 891line 890 didn't jump to line 891 because the condition on line 890 was never true

891 path = path.replace(".W_in", ".input") 

892 path = path.replace(".b_in", ".input") 

893 path = path.replace(".W_out", ".out") 

894 path = path.replace(".b_out", ".out") 

895 elif "in" in mlp_components and "out" in mlp_components: 895 ↛ 900line 895 didn't jump to line 900 because the condition on line 895 was always true

896 path = path.replace(".W_in", ".in") 

897 path = path.replace(".b_in", ".in") 

898 path = path.replace(".W_out", ".out") 

899 path = path.replace(".b_out", ".out") 

900 elif "fc_in" in mlp_components and "fc_out" in mlp_components: 

901 path = path.replace(".W_in", ".fc_in") 

902 path = path.replace(".b_in", ".fc_in") 

903 path = path.replace(".W_out", ".fc_out") 

904 path = path.replace(".b_out", ".fc_out") 

905 if "ln" in mlp_components: 905 ↛ 906line 905 didn't jump to line 906 because the condition on line 905 was never true

906 path = path.replace(".ln.w", ".ln") 

907 path = path.replace(".ln.b", ".ln") 

908 except Exception: 

909 pass 

910 if any((path.endswith(suffix) for suffix in [".W_in", ".W_out", ".b_in", ".b_out"])): 910 ↛ 911line 910 didn't jump to line 911 because the condition on line 910 was never true

911 path = path.replace(".W_in", ".in") 

912 path = path.replace(".b_in", ".in") 

913 path = path.replace(".W_out", ".out") 

914 path = path.replace(".b_out", ".out") 

915 path = path.replace(".W_gate", ".gate") 

916 path = path.replace(".b_gate", ".gate") 

917 if not (path.endswith(".weight") or path.endswith(".bias")): 917 ↛ 926line 917 didn't jump to line 926 because the condition on line 917 was always true

918 path = path.replace(".W_E", "") 

919 path = path.replace(".b_E", "") 

920 path = path.replace(".W_U", "") 

921 path = path.replace(".b_U", "") 

922 path = path.replace(".W_pos", "") 

923 path = path.replace(".b_pos", "") 

924 path = path.replace(".w", "") 

925 path = path.replace(".b", "") 

926 return (path, param_suffix) 

927 

928 def convert_hf_key_to_tl_key(self, hf_key: str) -> str: 

929 """Convert a HuggingFace-style key to TransformerLens format key using component mapping. 

930 

931 The component mapping keys ARE the TL format names (e.g., "embed", "pos_embed", "blocks"). 

932 The component.name is the HF path (e.g., "transformer.wte"). 

933 

934 Args: 

935 hf_key: The HuggingFace-style key (e.g., "transformer.wte.weight") 

936 

937 Returns: 

938 The TransformerLens format key (e.g., "embed.weight") 

939 """ 

940 if self.component_mapping is None: 940 ↛ 941line 940 didn't jump to line 941 because the condition on line 940 was never true

941 return hf_key 

942 for tl_name, component in self.component_mapping.items(): 

943 if tl_name in ("blocks", "L_blocks", "H_blocks"): 

944 continue 

945 hf_path = component.name 

946 if hf_path is not None and hf_key.startswith(hf_path + "."): 

947 param = hf_key[len(hf_path) + 1 :] 

948 return f"{tl_name}.{param}" 

949 for bl_tl_name in ("blocks", "L_blocks", "H_blocks"): 

950 blocks_component = self.component_mapping.get(bl_tl_name) 

951 if blocks_component: 

952 hf_blocks_prefix = blocks_component.name 

953 if hf_blocks_prefix is not None and hf_key.startswith(hf_blocks_prefix + "."): 

954 rest = hf_key[len(hf_blocks_prefix) + 1 :] 

955 parts = rest.split(".", 1) 

956 if len(parts) >= 2 and parts[0].isdigit(): 956 ↛ 949line 956 didn't jump to line 949 because the condition on line 956 was always true

957 layer_idx = parts[0] 

958 subkey = parts[1] 

959 if hasattr(blocks_component, "submodules"): 959 ↛ 949line 959 didn't jump to line 949 because the condition on line 959 was always true

960 for tl_subname, subcomponent in blocks_component.submodules.items(): 960 ↛ 949line 960 didn't jump to line 949 because the loop on line 960 didn't complete

961 hf_subpath = subcomponent.name 

962 if hasattr(subcomponent, "submodules"): 962 ↛ 978line 962 didn't jump to line 978 because the condition on line 962 was always true

963 for ( 

964 tl_nested_name, 

965 nested_comp, 

966 ) in subcomponent.submodules.items(): 

967 if hf_subpath is not None: 

968 hf_nested_path: Optional[ 

969 str 

970 ] = f"{hf_subpath}.{nested_comp.name}" 

971 else: 

972 hf_nested_path = nested_comp.name 

973 if hf_nested_path is not None and subkey.startswith( 

974 hf_nested_path + "." 

975 ): 

976 param = subkey[len(hf_nested_path) + 1 :] 

977 return f"{bl_tl_name}.{layer_idx}.{tl_subname}.{tl_nested_name}.{param}" 

978 if hf_subpath is not None and subkey.startswith(hf_subpath + "."): 

979 param = subkey[len(hf_subpath) + 1 :] 

980 return f"{bl_tl_name}.{layer_idx}.{tl_subname}.{param}" 

981 if hf_subpath is None and subkey.startswith(tl_subname + "."): 

982 param = subkey[len(tl_subname) + 1 :] 

983 return f"{bl_tl_name}.{layer_idx}.{tl_subname}.{param}" 

984 return hf_key 

985 

986 def prepare_loading(self, model_name: str, model_kwargs: dict) -> None: 

987 """Called before HuggingFace model loading to apply architecture-specific patches. 

988 

989 Override this to patch HF model classes before from_pretrained() is called. 

990 For example, patching custom model code that is incompatible with transformers v5 

991 meta device initialization. Overrides that also want the base eager-forcing 

992 must call super().prepare_loading(...). 

993 

994 The base implementation forces eager attention on the loading config when 

995 cfg.attn_implementation == "eager": composite configs (vision towers) don't 

996 reliably inherit the from_pretrained attn_implementation kwarg. 

997 

998 Args: 

999 model_name: The HuggingFace model name/path 

1000 model_kwargs: The kwargs dict that will be passed to from_pretrained() 

1001 """ 

1002 if getattr(self.cfg, "attn_implementation", None) == "eager": 

1003 config = model_kwargs.get("config") 

1004 if config is not None and hasattr(config, "_attn_implementation"): 1004 ↛ exitline 1004 didn't return from function 'prepare_loading' because the condition on line 1004 was always true

1005 config._attn_implementation = "eager" 

1006 

1007 def prepare_model(self, hf_model: Any) -> None: 

1008 """Called after HuggingFace model loading but before bridge creation. 

1009 

1010 Override this to fix up the loaded model (e.g., create synthetic modules, 

1011 re-initialize deferred computations, apply post-load patches). Overrides 

1012 that also want the base eager-forcing must call super().prepare_model(...). 

1013 

1014 The base implementation mirrors prepare_loading's eager-forcing onto the 

1015 loaded model's config when cfg.attn_implementation == "eager". 

1016 

1017 Args: 

1018 hf_model: The loaded HuggingFace model instance 

1019 """ 

1020 if getattr(self.cfg, "attn_implementation", None) == "eager": 

1021 force_eager_attention(hf_model) 

1022 

1023 def create_stateful_cache( 

1024 self, 

1025 hf_model: Any, 

1026 batch_size: int, 

1027 device: Any, 

1028 dtype: torch.dtype, 

1029 ) -> Any: 

1030 """Build the HF cache object for a stateful (SSM) generation loop. 

1031 

1032 Called by ``TransformerBridge.generate()`` once before the token loop 

1033 when ``cfg.is_stateful`` is True. The returned object is threaded 

1034 through each forward call as ``cache_params=...`` and is expected to 

1035 mutate itself in-place. 

1036 

1037 Subclasses for SSM architectures (Mamba, Mamba-2, etc.) must override 

1038 this. The base raises to catch adapters that set ``is_stateful=True`` 

1039 without providing a cache implementation. 

1040 

1041 Args: 

1042 hf_model: The wrapped HF model (source of ``.config``). 

1043 batch_size: Number of sequences generated in parallel. 

1044 device: Device for cache tensors. 

1045 dtype: Cache tensor dtype (usually the model's param dtype). 

1046 """ 

1047 raise NotImplementedError( 

1048 f"{type(self).__name__}.create_stateful_cache is not implemented. " 

1049 "If this adapter represents a stateful model (cfg.is_stateful=True), " 

1050 "it must override create_stateful_cache to return the appropriate " 

1051 "HF cache object." 

1052 ) 

1053 

1054 # setup_component_testing knobs; adapters override these one-line class 

1055 # attributes instead of re-declaring the standard wiring method. 

1056 _testing_lm_attr: str = "model" 

1057 _testing_eager: Optional[str] = "layers" 

1058 _testing_hybrid: bool = False 

1059 _testing_rotary_attr: str = "rotary_emb" 

1060 _testing_wire_rotary: bool = True 

1061 

1062 def setup_component_testing(self, hf_model: Any, bridge_model: Any = None) -> None: 

1063 """Wire model-specific references for component testing (eager-forcing + rotary 

1064 per the ``_testing_*`` attributes); override and call super() for extra needs.""" 

1065 self._wire_rotary_for_testing( 

1066 hf_model, 

1067 bridge_model, 

1068 lm_attr=self._testing_lm_attr, 

1069 hybrid=self._testing_hybrid, 

1070 eager=self._testing_eager, 

1071 rotary_attr=self._testing_rotary_attr, 

1072 wire_rotary=self._testing_wire_rotary, 

1073 ) 

1074 

1075 def _wire_rotary_for_testing( 

1076 self, 

1077 hf_model: Any, 

1078 bridge_model: Any = None, 

1079 *, 

1080 lm_attr: str = "model", 

1081 hybrid: bool = False, 

1082 eager: Optional[str] = "layers", 

1083 rotary_attr: str = "rotary_emb", 

1084 wire_rotary: bool = True, 

1085 ) -> None: 

1086 """Force eager attention and set the model's shared rotary_emb on each attention 

1087 bridge and the template (``wire_rotary=False`` for delegated attention, which has 

1088 no set_rotary_emb; ``hybrid`` tolerates attention-less blocks).""" 

1089 lm = hf_model 

1090 for segment in lm_attr.split("."): 

1091 lm = getattr(lm, segment, None) 

1092 if lm is None: 

1093 break 

1094 

1095 if eager is not None: 

1096 # eager == "layers" additionally stamps per-layer self_attn configs. 

1097 force_eager_attention(hf_model, per_layer=(eager == "layers")) 

1098 

1099 if not wire_rotary or lm is None or not hasattr(lm, rotary_attr): 

1100 return 

1101 rotary_emb = getattr(lm, rotary_attr) 

1102 

1103 # No attn submodule in the blocks template (fully delegated attention, 

1104 # e.g. Zamba2's shared blocks): wiring is inapplicable, not an error. 

1105 blocks_template = (self.component_mapping or {}).get("blocks") 

1106 if blocks_template is not None and "attn" not in getattr(blocks_template, "submodules", {}): 

1107 return 

1108 

1109 if bridge_model is not None and hasattr(bridge_model, "blocks"): 

1110 for block in bridge_model.blocks: 

1111 has_attn = ("attn" in block._modules) if hybrid else hasattr(block, "attn") 

1112 if has_attn and hasattr(block.attn, "set_rotary_emb"): 

1113 block.attn.set_rotary_emb(rotary_emb) 

1114 

1115 try: 

1116 template = self.get_generalized_component("blocks.0.attn") 

1117 except (ValueError, AttributeError, KeyError): 

1118 if not hybrid: 1118 ↛ 1119line 1118 didn't jump to line 1119 because the condition on line 1118 was never true

1119 raise 

1120 template = None 

1121 if template is not None and hasattr(template, "set_rotary_emb"): 

1122 template.set_rotary_emb(rotary_emb)