Coverage for transformer_lens/model_bridge/generalized_components/block.py: 90%

268 statements  

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

1"""Block bridge component. 

2 

3This module contains the bridge component for transformer blocks. 

4""" 

5from __future__ import annotations 

6 

7import inspect 

8import re 

9import weakref 

10from typing import Any, Callable, Dict, Optional, cast 

11 

12import torch 

13 

14from transformer_lens.hook_points import HookPoint 

15from transformer_lens.model_bridge.exceptions import StopAtLayerException 

16from transformer_lens.model_bridge.generalized_components.base import ( 

17 GeneralizedComponent, 

18) 

19 

20# Layer-type variant submodule names. Tuple for deterministic iteration order. 

21# Extend here when adding new hybrid variant types. 

22VARIANT_SUBMODULE_NAMES: tuple[str, ...] = ("attn", "linear_attn", "mamba", "mixer", "ssm") 

23_VARIANT_SUBMODULE_SET: frozenset[str] = frozenset(VARIANT_SUBMODULE_NAMES) 

24 

25# Infrastructure modules excluded from submodule introspection. 

26_BLOCK_INTERNAL_MODULES: frozenset[str] = frozenset({"hook_in", "hook_out", "_original_component"}) 

27 

28# Norm-module prefixes excluded from layer_types() labels. 

29_NORM_PREFIXES: tuple[str, ...] = ("ln", "layer_norm", "norm", "rms") 

30 

31 

32class BlockBridge(GeneralizedComponent): 

33 """Bridge component for transformer blocks. 

34 

35 This component provides standardized input/output hooks and monkey-patches 

36 HuggingFace blocks to insert hooks at positions matching HookedTransformer. 

37 """ 

38 

39 is_list_item: bool = True 

40 hook_out_is_single_residual_stream: bool = True 

41 mlp_input_includes_attn: bool = True 

42 # hook_mlp_in is a direct HookPoint on this class (not aliased) so it can 

43 # fire on the MLP-branch entry (pre-ln2, or the MLP input on post-norm 

44 # blocks); see __init__. The normalized mlp input stays at block.mlp.hook_in. 

45 hook_aliases = { 

46 "hook_resid_pre": "hook_in", 

47 "hook_resid_mid": "ln2.hook_in", 

48 "hook_resid_post": "hook_out", 

49 "hook_attn_in": "attn.hook_attn_in", 

50 "hook_attn_out": "attn.hook_out", 

51 "hook_q_input": "attn.hook_q_input", 

52 "hook_k_input": "attn.hook_k_input", 

53 "hook_v_input": "attn.hook_v_input", 

54 "hook_mlp_out": "mlp.hook_out", 

55 } 

56 

57 def __init__( 

58 self, 

59 name: str, 

60 config: Optional[Any] = None, 

61 submodules: Optional[Dict[str, GeneralizedComponent]] = None, 

62 hook_alias_overrides: Optional[Dict[str, str]] = None, 

63 mlp_reads_resid_directly: bool = False, 

64 ): 

65 """Initialize the block bridge. 

66 

67 Args: 

68 name: The name of the component in the model 

69 config: Optional configuration (unused for BlockBridge) 

70 submodules: Dictionary of submodules to register 

71 hook_alias_overrides: Optional dictionary to override default hook aliases. 

72 For example, {"hook_attn_out": "ln1_post.hook_out"} will make hook_attn_out 

73 point to ln1_post.hook_out instead of the default attn.hook_out. 

74 mlp_reads_resid_directly: True when the MLP consumes the mid-residual with 

75 no pre-MLP norm. Moves the hook_mlp_in capture from ln2 to the MLP 

76 itself. Implied for post-norm-only blocks (ln2_post without ln2). 

77 """ 

78 has_ln2 = submodules is not None and "ln2" in submodules 

79 # OLMo 2 layout: ln2_post without ln2 means the MLP reads the mid-residual directly. 

80 post_norm_only_mlp = submodules is not None and "ln2_post" in submodules and not has_ln2 

81 # ln1_post/ln2_post redirect attn_out/mlp_out to match HookedTransformer's 

82 # placement (hook fires after the post-norm, not before). 

83 auto_overrides = {} 

84 if submodules is not None: 

85 if "ln1_post" in submodules: 

86 auto_overrides["hook_attn_out"] = "ln1_post.hook_out" 

87 if "ln2_post" in submodules: 

88 auto_overrides["hook_mlp_out"] = "ln2_post.hook_out" 

89 if post_norm_only_mlp: 

90 auto_overrides["hook_resid_mid"] = "mlp.hook_in" 

91 merged_overrides = {**auto_overrides, **(hook_alias_overrides or {})} 

92 

93 # Guard against the bug where a sequential block (attn + mlp) with no MLP-side 

94 # norm silently points hook_resid_mid at the wrong tensor. Use 

95 # ParallelBlockBridge for parallel-residual architectures. 

96 # Skip the check on generic-container / attn-only uses (no mlp). 

97 has_attn_like = submodules is not None and any( 

98 k in submodules for k in _VARIANT_SUBMODULE_SET 

99 ) 

100 has_mlp = submodules is not None and "mlp" in submodules 

101 if ( 

102 has_attn_like 

103 and has_mlp 

104 and not has_ln2 

105 and not post_norm_only_mlp 

106 and type(self) is BlockBridge 

107 ): 

108 raise ValueError( 

109 f"BlockBridge at '{name}': neither 'ln2' nor 'ln2_post' declared. " 

110 f"Declare ln2 (pre-MLP norm) or ln2_post (post-MLP norm), or use " 

111 f"ParallelBlockBridge for a parallel-residual architecture." 

112 ) 

113 

114 super().__init__( 

115 name, 

116 config, 

117 submodules=submodules if submodules is not None else {}, 

118 hook_alias_overrides=merged_overrides if merged_overrides else None, 

119 ) 

120 

121 self._original_block_forward: Optional[Callable[..., Any]] = None 

122 self._capture_hooks_wired: bool = False 

123 self._capture_hook_handles: list[torch.utils.hooks.RemovableHandle] = [] 

124 # Fallback for _read_use_hook_mlp_in when block.config is None. 

125 self._use_hook_mlp_in: bool = False 

126 self.mlp_reads_resid_directly = mlp_reads_resid_directly or post_norm_only_mlp 

127 # Fires on the MLP-branch entry (pre-ln2, or the MLP input on post-norm 

128 # blocks) when use_hook_mlp_in is set. See #1317. 

129 self.hook_mlp_in = HookPoint() 

130 

131 def _wire_ln1_module(self) -> None: 

132 """Keep the raw ln1 execution reference outside the ownership tree.""" 

133 from transformer_lens.model_bridge.generalized_components.attention import ( 

134 AttentionBridge, 

135 ) 

136 

137 ln1 = self.submodules.get("ln1") if self.submodules else None 

138 attn = self.submodules.get("attn") if self.submodules else None 

139 if not isinstance(attn, AttentionBridge): 

140 return 

141 

142 ln1_module = None 

143 if ( 

144 ln1 is not None 

145 and getattr(attn, "supports_split_qkv_fork", False) 

146 and getattr(ln1, "original_component", None) is not None 

147 ): 

148 ln1_module = ln1.original_component 

149 

150 attn._modules.pop("_ln1_module", None) 

151 object.__setattr__(attn, "_ln1_module", ln1_module) 

152 

153 def _maybe_wire_capture_hooks(self) -> None: 

154 """Install the block's capture hooks (split-qkv fork, hook_mlp_in). 

155 

156 Registered on the bridge submodule, not ``original_component`` — the 

157 manual bridge forward never calls the raw module. Idempotent. 

158 """ 

159 self._wire_ln1_module() 

160 if self._capture_hooks_wired: 

161 return 

162 from transformer_lens.model_bridge.generalized_components.attention import ( 

163 AttentionBridge, 

164 ) 

165 

166 ln1 = self.submodules.get("ln1") if self.submodules else None 

167 attn = self.submodules.get("attn") if self.submodules else None 

168 if ( 

169 ln1 is not None 

170 and isinstance(attn, AttentionBridge) 

171 and getattr(attn, "supports_split_qkv_fork", False) 

172 and getattr(ln1, "original_component", None) is not None 

173 ): 

174 attn_ref = cast(AttentionBridge, weakref.proxy(attn)) 

175 

176 def _capture_pre_ln1(_module: torch.nn.Module, args: tuple) -> None: 

177 if args and isinstance(args[0], torch.Tensor): 177 ↛ exitline 177 didn't return from function '_capture_pre_ln1' because the condition on line 177 was always true

178 attn_ref._captured_pre_ln_residual = args[0] 

179 

180 handle = ln1.register_forward_pre_hook(_capture_pre_ln1) 

181 self._capture_hook_handles.append(handle) 

182 

183 # hook_mlp_in must capture the MLP-branch entry point: ln2's input on 

184 # pre-norm blocks, the MLP's own input on post-norm blocks (where ln2 

185 # follows the MLP and its input is the raw MLP output). 

186 if self.mlp_reads_resid_directly: 

187 capture_target = self.submodules.get("mlp") if self.submodules else None 

188 else: 

189 capture_target = self.submodules.get("ln2") if self.submodules else None 

190 if ( 

191 capture_target is not None 

192 and getattr(capture_target, "original_component", None) is not None 

193 ): 

194 hook_mlp_in = self.hook_mlp_in 

195 block_ref = weakref.proxy(self) 

196 

197 def _capture_mlp_in(_module: torch.nn.Module, args: tuple) -> Any: 

198 if not block_ref._read_use_hook_mlp_in(): 

199 return None 

200 if args and isinstance(args[0], torch.Tensor): 200 ↛ 203line 200 didn't jump to line 203 because the condition on line 200 was always true

201 hooked = hook_mlp_in(args[0]) 

202 return (hooked,) + args[1:] 

203 return None 

204 

205 handle = capture_target.register_forward_pre_hook(_capture_mlp_in) 

206 self._capture_hook_handles.append(handle) 

207 

208 self._capture_hooks_wired = True 

209 

210 def _teardown_capture_hooks(self) -> None: 

211 """Remove the capture hooks installed by _maybe_wire_capture_hooks (and subclass extensions).""" 

212 for handle in self._capture_hook_handles: 

213 handle.remove() 

214 self._capture_hook_handles.clear() 

215 self._capture_hooks_wired = False 

216 

217 def _read_use_hook_mlp_in(self) -> bool: 

218 """Prefer ``block.config.use_hook_mlp_in``; fall back to the block-local flag.""" 

219 cfg = self.config 

220 if cfg is not None and hasattr(cfg, "use_hook_mlp_in"): 

221 return bool(cfg.use_hook_mlp_in) 

222 return self._use_hook_mlp_in 

223 

224 def _clear_attention_capture(self) -> None: 

225 """Release the transient residual captured for attention input forks.""" 

226 from transformer_lens.model_bridge.generalized_components.attention import ( 

227 AttentionBridge, 

228 ) 

229 

230 attn = self.submodules.get("attn") if self.submodules else None 

231 if isinstance(attn, AttentionBridge): 

232 attn._captured_pre_ln_residual = None 

233 

234 def forward(self, *args: Any, **kwargs: Any) -> Any: 

235 """Forward pass through the block bridge. 

236 

237 Args: 

238 *args: Input arguments 

239 **kwargs: Input keyword arguments 

240 

241 Returns: 

242 The output from the original component 

243 

244 Raises: 

245 StopAtLayerException: If stop_at_layer is set and this block should stop execution 

246 """ 

247 if self.original_component is None: 247 ↛ 248line 247 didn't jump to line 248 because the condition on line 247 was never true

248 raise RuntimeError( 

249 f"Original component not set for {self.name}. Call set_original_component() first." 

250 ) 

251 

252 self._maybe_wire_capture_hooks() 

253 self._clear_attention_capture() 

254 args, kwargs = self._maybe_inject_start_residual(args, kwargs) 

255 self._check_stop_at_layer(*args, **kwargs) 

256 args, kwargs = self._hook_input_hidden_states(args, kwargs) 

257 

258 # Filter kwargs to only include parameters accepted by the original component 

259 # This prevents errors when passing encoder-specific params to decoder-only models 

260 filtered_kwargs = self._filter_kwargs_for_forward(kwargs, len(args)) 

261 

262 try: 

263 output = self.original_component(*args, **filtered_kwargs) 

264 finally: 

265 self._clear_attention_capture() 

266 force_tuple_for_bare_tensor = self._is_standalone_hidden_state_call(args, filtered_kwargs) 

267 return self._apply_output_hook( 

268 output, force_tuple_for_bare_tensor=force_tuple_for_bare_tensor 

269 ) 

270 

271 def _apply_output_hook( 

272 self, 

273 output: Any, 

274 wrap_single_element: bool = True, 

275 force_tuple_for_bare_tensor: bool = False, 

276 ) -> Any: 

277 """Hook the primary tensor in the output and return the result. 

278 

279 Args: 

280 output: Raw output from the original component (tensor, tuple or list). 

281 wrap_single_element: If True, single-element tuples stay as tuples after 

282 hooking (default, required by most HF models). If False, single-element 

283 tuples are unwrapped to a bare tensor (Bloom convention). 

284 force_tuple_for_bare_tensor: If True, bare tensor outputs are wrapped into 

285 a one-element tuple after hooking. This keeps standalone BlockBridge 

286 calls compatible with HF block APIs that expose tuple-like block outputs, 

287 while preserving tensor outputs during newer HF parent-model execution. 

288 """ 

289 if isinstance(output, tuple) and len(output) > 0: 

290 first = output[0] 

291 if isinstance(first, torch.Tensor): 291 ↛ 296line 291 didn't jump to line 296 because the condition on line 291 was always true

292 first = self.hook_out(first) 

293 if len(output) == 1: 

294 return (first,) if wrap_single_element else first 

295 output = (first,) + output[1:] 

296 return output 

297 # OpenAI GPT's block returns a list, and its parent model indexes it. 

298 if isinstance(output, list) and len(output) > 0 and isinstance(output[0], torch.Tensor): 

299 return [self.hook_out(output[0]), *output[1:]] 

300 if isinstance(output, torch.Tensor): 

301 output = self.hook_out(output) 

302 if force_tuple_for_bare_tensor and wrap_single_element: 

303 return (output,) 

304 return output 

305 return output 

306 

307 @staticmethod 

308 def _is_standalone_hidden_state_call(args: tuple, kwargs: dict) -> bool: 

309 """Return True for direct block(hidden_states) style calls. 

310 

311 Transformers versions differ on whether parent model loops expect block 

312 outputs as tuples or tensors. We preserve the original tensor return during 

313 full-model execution, but expose tuple-like output for standalone component 

314 calls so `output[0]` does not accidentally drop the batch dimension. 

315 """ 

316 if len(args) == 1 and isinstance(args[0], torch.Tensor) and not kwargs: 

317 return True 

318 return ( 

319 len(args) == 0 

320 and set(kwargs.keys()) == {"hidden_states"} 

321 and isinstance(kwargs["hidden_states"], torch.Tensor) 

322 ) 

323 

324 def _extract_layer_idx(self) -> Optional[int]: 

325 """Parse this block's layer index from its name (TL/GPT-2/LLaMA patterns).""" 

326 if self.name is None: 326 ↛ 327line 326 didn't jump to line 327 because the condition on line 326 was never true

327 return None 

328 match = re.search(r"(?:^|\.)(?:blocks|h|layers)\.(\d+)", self.name) 

329 return int(match.group(1)) if match else None 

330 

331 def _check_stop_at_layer(self, *args: Any, **kwargs: Any) -> None: 

332 """Check if execution should stop before this block. Raises StopAtLayerException. 

333 

334 The _stop_at_layer_idx attribute is set by the bridge's forward method. 

335 Supports TL/GPT-2/LLaMA naming patterns for layer index extraction. 

336 """ 

337 if getattr(self, "_stop_at_layer_idx", None) is None: 

338 return 

339 layer_idx = self._extract_layer_idx() 

340 if layer_idx is not None and layer_idx == self._stop_at_layer_idx: 

341 if len(args) > 0 and isinstance(args[0], torch.Tensor): 341 ↛ 343line 341 didn't jump to line 343 because the condition on line 341 was always true

342 input_tensor = args[0] 

343 elif "hidden_states" in kwargs and isinstance(kwargs["hidden_states"], torch.Tensor): 

344 input_tensor = kwargs["hidden_states"] 

345 else: 

346 raise ValueError(f"Cannot find input tensor to stop at layer {layer_idx}") 

347 input_tensor = self.hook_in(input_tensor) 

348 raise StopAtLayerException(input_tensor) 

349 

350 def _maybe_inject_start_residual(self, args: tuple, kwargs: dict) -> tuple[tuple, dict]: 

351 """If this is the start_at_layer block, swap in the caller's residual. 

352 

353 Mirror of ``_check_stop_at_layer``: the bridge's forward stashes the 

354 residual-stream input on the block via ``_start_residual`` and sets 

355 ``_start_at_layer_idx``. This block replaces its incoming hidden states 

356 with that residual; ``_hook_input_hidden_states`` then fires ``hook_in`` 

357 on it, so ``hook_resid_pre`` reflects the injected value. 

358 """ 

359 if getattr(self, "_start_at_layer_idx", None) is None: 

360 return args, kwargs 

361 if self._extract_layer_idx() != self._start_at_layer_idx: 

362 return args, kwargs 

363 residual = getattr(self, "_start_residual", None) 

364 if residual is None: 364 ↛ 365line 364 didn't jump to line 365 because the condition on line 364 was never true

365 return args, kwargs 

366 if len(args) > 0 and isinstance(args[0], torch.Tensor): 366 ↛ 368line 366 didn't jump to line 368 because the condition on line 366 was always true

367 args = (residual,) + args[1:] 

368 elif "hidden_states" in kwargs: 

369 kwargs = {**kwargs, "hidden_states": residual} 

370 return args, kwargs 

371 

372 def _hook_input_hidden_states(self, args: tuple, kwargs: dict) -> tuple[tuple, dict]: 

373 """Apply hook_in to the hidden_states input, whether in args or kwargs.""" 

374 if len(args) > 0 and isinstance(args[0], torch.Tensor): 374 ↛ 377line 374 didn't jump to line 377 because the condition on line 374 was always true

375 hooked_input = self.hook_in(args[0]) 

376 args = (hooked_input,) + args[1:] 

377 elif "hidden_states" in kwargs and isinstance(kwargs["hidden_states"], torch.Tensor): 

378 kwargs["hidden_states"] = self.hook_in(kwargs["hidden_states"]) 

379 return args, kwargs 

380 

381 def _filter_kwargs_for_forward( 

382 self, kwargs: Dict[str, Any], num_positional_args: int = 0 

383 ) -> Dict[str, Any]: 

384 """Filter kwargs to only include parameters accepted by original_component.forward(). 

385 

386 This prevents TypeErrors when the bridge passes parameters (like encoder_attention_mask) 

387 that aren't accepted by decoder-only models. It also removes any kwargs that would 

388 conflict with positional arguments already being passed. 

389 

390 Args: 

391 kwargs: The full set of keyword arguments 

392 num_positional_args: Number of positional arguments being passed (to avoid conflicts) 

393 

394 Returns: 

395 Filtered kwargs containing only accepted parameters 

396 """ 

397 if self.original_component is None: 397 ↛ 398line 397 didn't jump to line 398 because the condition on line 397 was never true

398 return kwargs 

399 

400 try: 

401 # Get the signature of the original component's forward method 

402 sig = inspect.signature(self.original_component.forward) 

403 param_list = list(sig.parameters.keys()) 

404 valid_params = set(param_list) 

405 

406 # Check if the signature accepts **kwargs (VAR_KEYWORD) 

407 accepts_var_keyword = any( 

408 p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values() 

409 ) 

410 

411 # If it accepts **kwargs, pass everything through 

412 if accepts_var_keyword: 

413 return kwargs 

414 

415 # Skip params already provided positionally 

416 positional_param_names = set(param_list[:num_positional_args]) 

417 

418 # Filter kwargs: include only if in signature AND not already provided positionally 

419 filtered = { 

420 k: v 

421 for k, v in kwargs.items() 

422 if k in valid_params and k not in positional_param_names 

423 } 

424 return filtered 

425 

426 except (ValueError, TypeError): 

427 # If we can't inspect the signature, pass through all kwargs 

428 # (better to potentially fail than to silently drop important params) 

429 return kwargs 

430 

431 

432class MLABlockBridge(BlockBridge): 

433 """Block wrapping Multi-Head Latent Attention (DeepSeek V2/V3/R1). 

434 

435 MLA has no standalone q/k/v projections — Q flows through compressed 

436 q_a_proj→q_a_layernorm→q_b_proj, and K/V share a joint kv_a_proj_with_mqa 

437 entry point. There is no single HookPoint that represents "input that 

438 becomes Q/K/V", so the block-level ``hook_q_input``/``hook_k_input``/ 

439 ``hook_v_input``/``hook_attn_in`` aliases do not apply. Type-level 

440 distinction means a reader of the adapter sees ``MLABlockBridge`` and 

441 knows those hooks are absent. 

442 """ 

443 

444 def __init__( 

445 self, 

446 name: str, 

447 config: Optional[Any] = None, 

448 submodules: Optional[Dict[str, GeneralizedComponent]] = None, 

449 hook_alias_overrides: Optional[Dict[str, str]] = None, 

450 ): 

451 super().__init__( 

452 name, 

453 config=config, 

454 submodules=submodules, 

455 hook_alias_overrides=hook_alias_overrides, 

456 ) 

457 if self.hook_aliases is BlockBridge.hook_aliases: 457 ↛ 459line 457 didn't jump to line 459 because the condition on line 457 was always true

458 self.hook_aliases = dict(self.hook_aliases) 

459 for alias in ("hook_q_input", "hook_k_input", "hook_v_input", "hook_attn_in"): 

460 self.hook_aliases.pop(alias, None) 

461 

462 

463class ParallelBlockBridge(BlockBridge): 

464 """Block where attn and MLP both read the pre-attention residual. 

465 

466 For GPT-J, NeoX, Pythia, Phi, Cohere, CodeGen, and some Falcon variants, 

467 output = resid_pre + attn_out + mlp_out — no distinct post-attention 

468 residual exists. Matches legacy HookedTransformer which omits hook_resid_mid 

469 when ``cfg.parallel_attn_mlp=True``. Type-level distinction means a reader 

470 of the adapter sees ``ParallelBlockBridge`` and knows the hook is absent. 

471 """ 

472 

473 mlp_input_includes_attn: bool = False 

474 

475 def __init__( 

476 self, 

477 name: str, 

478 config: Optional[Any] = None, 

479 submodules: Optional[Dict[str, GeneralizedComponent]] = None, 

480 hook_alias_overrides: Optional[Dict[str, str]] = None, 

481 ): 

482 super().__init__( 

483 name, 

484 config=config, 

485 submodules=submodules, 

486 hook_alias_overrides=hook_alias_overrides, 

487 ) 

488 # Ensure instance-level copy before mutating; base may have left the 

489 # class-level dict shared when no overrides were passed. 

490 if self.hook_aliases is BlockBridge.hook_aliases: 490 ↛ 492line 490 didn't jump to line 492 because the condition on line 490 was always true

491 self.hook_aliases = dict(self.hook_aliases) 

492 self.hook_aliases.pop("hook_resid_mid", None) 

493 

494 

495class ScaledResidualBlockBridge(BlockBridge): 

496 """Block whose sublayer outputs are scaled before the residual add. 

497 

498 Granite-family HF blocks compute ``residual + sublayer_out * residual_multiplier`` 

499 inline, so no submodule output equals the tensor added to the residual stream 

500 and the legacy aliases cannot be fixed by re-pointing. ``hook_attn_out`` / 

501 ``hook_mlp_out`` become real HookPoints on the block firing on the scaled 

502 contribution: 

503 

504 - no hooks attached: the forward is untouched (bit-exact); 

505 - read-only hooks: they observe ``module_out * scale``, forward stays bit-exact; 

506 - a hook that changes the tensor (returned new or mutated in place): the module 

507 output is rewritten to ``hooked / scale`` so HF's multiply reconstructs the 

508 written value as the contribution (~1-ulp rounding; exact for zero-ablation); 

509 - any backward hooks: the rewrite always happens so the autograd graph routes 

510 through the HookPoint. 

511 """ 

512 

513 def __init__( 

514 self, 

515 name: str, 

516 config: Optional[Any] = None, 

517 submodules: Optional[Dict[str, GeneralizedComponent]] = None, 

518 hook_alias_overrides: Optional[Dict[str, str]] = None, 

519 mlp_reads_resid_directly: bool = False, 

520 residual_contribution_scale: float = 1.0, 

521 scaled_attn_submodule: str = "attn", 

522 scaled_mlp_submodule: Optional[str] = "mlp", 

523 ): 

524 """scaled_mlp_submodule=None when no single submodule feeds the MLP-side 

525 add (GraniteMoeHybrid sums moe + shared_mlp inline) — hook_mlp_out then 

526 stays absent rather than firing with a partial tensor.""" 

527 super().__init__( 

528 name, 

529 config=config, 

530 submodules=submodules, 

531 hook_alias_overrides=hook_alias_overrides, 

532 mlp_reads_resid_directly=mlp_reads_resid_directly, 

533 ) 

534 scale = float(residual_contribution_scale) 

535 if scale == 0.0: 

536 raise ValueError( 

537 f"ScaledResidualBlockBridge at '{name}': residual_contribution_scale " 

538 f"must be nonzero (the write path divides by it)." 

539 ) 

540 self.residual_contribution_scale = scale 

541 self.scaled_attn_submodule = scaled_attn_submodule 

542 self.scaled_mlp_submodule = scaled_mlp_submodule 

543 attn = self.submodules.get(scaled_attn_submodule) if self.submodules else None 

544 if attn is not None: 544 ↛ 546line 544 didn't jump to line 546 because the condition on line 544 was always true

545 attn._result_contribution_scale = scale 

546 if self.hook_aliases is BlockBridge.hook_aliases: 546 ↛ 548line 546 didn't jump to line 548 because the condition on line 546 was always true

547 self.hook_aliases = dict(self.hook_aliases) 

548 for alias in ("hook_attn_out", "hook_mlp_out"): 

549 self.hook_aliases.pop(alias, None) 

550 self.hook_attn_out = HookPoint() 

551 if scaled_mlp_submodule is not None: 

552 self.hook_mlp_out = HookPoint() 

553 

554 def set_original_component(self, original_component: torch.nn.Module) -> None: 

555 """Prune contribution HookPoints the bound layer cannot fire. 

556 

557 Heterogeneous blocks (GraniteMoeHybrid mamba layers) lack the attn 

558 submodule; a HookPoint that exists but never fires is a silent-no-op 

559 intervention trap, so the name must be absent instead. 

560 """ 

561 super().set_original_component(original_component) 

562 targets = [(self.scaled_attn_submodule, "hook_attn_out")] 

563 if self.scaled_mlp_submodule is not None: 

564 targets.append((self.scaled_mlp_submodule, "hook_mlp_out")) 

565 for sub_name, hook_name in targets: 

566 sub = self.submodules.get(sub_name) if self.submodules else None 

567 remote = getattr(sub, "name", None) 

568 first = remote.split(".", 1)[0] if isinstance(remote, str) else None 

569 missing = sub is None or ( 

570 first is not None and getattr(original_component, first, None) is None 

571 ) 

572 if missing: 

573 if hasattr(self, hook_name): 573 ↛ 577line 573 didn't jump to line 577 because the condition on line 573 was always true

574 delattr(self, hook_name) 

575 # __setattr__ auto-registered the HookPoint; get_hooks() serves 

576 # from this registry, so the module deletion alone is not enough. 

577 self._hook_registry.pop(hook_name, None) 

578 

579 def _maybe_wire_capture_hooks(self) -> None: 

580 """Extend the base wiring with the scaled-contribution forward hooks. 

581 

582 Shares the base flag and handle list so _teardown_capture_hooks also 

583 removes these hooks and re-wiring stays idempotent. 

584 """ 

585 if self._capture_hooks_wired: 

586 return 

587 super()._maybe_wire_capture_hooks() 

588 targets = [(self.scaled_attn_submodule, "hook_attn_out")] 

589 if self.scaled_mlp_submodule is not None: 

590 targets.append((self.scaled_mlp_submodule, "hook_mlp_out")) 

591 for sub_name, hook_name in targets: 

592 hook_point = getattr(self, hook_name, None) 

593 sub = self.submodules.get(sub_name) if self.submodules else None 

594 if ( 

595 hook_point is None 

596 or sub is None 

597 or getattr(sub, "original_component", None) is None 

598 ): 

599 continue 

600 handle = sub.register_forward_hook(self._make_scaled_contribution_hook(hook_point)) 

601 self._capture_hook_handles.append(handle) 

602 

603 def _make_scaled_contribution_hook( 

604 self, hook_point: HookPoint 

605 ) -> Callable[[torch.nn.Module, tuple, Any], Any]: 

606 """Build a forward hook exposing ``output * scale`` through hook_point.""" 

607 scale = self.residual_contribution_scale 

608 

609 def _hook(_module: torch.nn.Module, _args: tuple, output: Any) -> Any: 

610 if not hook_point.has_hooks(dir="both"): 

611 return None 

612 is_tuple = isinstance(output, tuple) 

613 out = output[0] if is_tuple else output 

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

615 return None 

616 new = self._hook_scaled_output(out, hook_point, scale) 

617 if new is out: 

618 return None 

619 return ((new,) + output[1:]) if is_tuple else new 

620 

621 return _hook 

622 

623 

624class DelegatedAttentionBlockBridge(BlockBridge): 

625 """Block whose attention is delegated wholesale to HF (no split-qkv fork). 

626 

627 For architectures with heterogeneous per-layer attention structure — e.g. 

628 Gemma 4, where KV-shared layers have no ``k_proj``/``v_proj`` at all and 

629 K==V layers have no ``v_proj`` — there is no uniform HookPoint that 

630 represents "input that becomes Q/K/V", so the block-level ``hook_q_input``/ 

631 ``hook_k_input``/``hook_v_input``/``hook_attn_in`` aliases do not apply. 

632 Type-level distinction means a reader of the adapter sees 

633 ``DelegatedAttentionBlockBridge`` and knows those hooks are absent. 

634 """ 

635 

636 # Tell the component benchmark this block's attention is delegated wholesale 

637 # to HF and cannot be tested in isolation (requires model-specific kwargs). 

638 maintain_native_attention: bool = True 

639 

640 def __init__( 

641 self, 

642 name: str, 

643 config: Optional[Any] = None, 

644 submodules: Optional[Dict[str, GeneralizedComponent]] = None, 

645 hook_alias_overrides: Optional[Dict[str, str]] = None, 

646 ): 

647 super().__init__( 

648 name, 

649 config=config, 

650 submodules=submodules, 

651 hook_alias_overrides=hook_alias_overrides, 

652 ) 

653 if self.hook_aliases is BlockBridge.hook_aliases: 

654 self.hook_aliases = dict(self.hook_aliases) 

655 for alias in ("hook_q_input", "hook_k_input", "hook_v_input", "hook_attn_in"): 

656 self.hook_aliases.pop(alias, None)