Coverage for transformer_lens/model_bridge/generalized_components/attention.py: 88%

507 statements  

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

1"""Attention bridge component. 

2 

3This module contains the bridge component for attention layers. 

4""" 

5import inspect 

6import logging 

7import warnings 

8from typing import Any, Dict, Optional, Tuple 

9 

10import einops 

11import torch 

12from transformers.pytorch_utils import Conv1D 

13 

14logger = logging.getLogger(__name__) 

15 

16from transformer_lens.conversion_utils.conversion_steps.attention_auto_conversion import ( 

17 AttentionAutoConversion, 

18) 

19from transformer_lens.conversion_utils.conversion_steps.base_tensor_conversion import ( 

20 BaseTensorConversion, 

21) 

22from transformer_lens.hook_points import HookPoint 

23from transformer_lens.model_bridge.generalized_components.base import ( 

24 GeneralizedComponent, 

25) 

26from transformer_lens.utilities.hf_utils import get_rotary_pct_from_config 

27from transformer_lens.utilities.quantization import require_readable_weight 

28 

29 

30class PerLayerGeometryError(ValueError): 

31 """A weight accessor refused a head split on per-layer attention geometry. 

32 

33 Dedicated type so callers with a raw-weight fallback (the centering 

34 benchmark) catch exactly this and nothing else — a generic ValueError 

35 catch would silently mask unrelated accessor regressions. 

36 """ 

37 

38 

39class AttentionBridge(GeneralizedComponent): 

40 """Bridge component for attention layers. 

41 

42 This component handles the conversion between Hugging Face attention layers 

43 and TransformerLens attention components. 

44 """ 

45 

46 hook_aliases = { 

47 "hook_q": "q.hook_out", 

48 "hook_k": "k.hook_out", 

49 "hook_v": "v.hook_out", 

50 "hook_z": "o.hook_in", 

51 } 

52 

53 # Override to False on variants without a pre-LN fork (e.g. MLA); skips 

54 # the split-qkv HookPoints and the BlockBridge pre-ln1 capture. 

55 supports_split_qkv_fork: bool = True 

56 # Reconstructed variants can opt in independently of Q/K/V input forks. 

57 supports_attn_result: bool = False 

58 # A [batch, 1, 1, kv] 4D mask is normally a complete caller mask (HF applies 

59 # it as given); set True where the wrapped HF module passes padding only and 

60 # leaves causality to the attention module (GPT-1). 

61 broadcast_mask_is_padding_only: bool = False 

62 property_aliases = { 

63 "W_Q": "q.weight", 

64 "W_K": "k.weight", 

65 "W_V": "v.weight", 

66 "W_O": "o.weight", 

67 "b_Q": "q.bias", 

68 "b_K": "k.bias", 

69 "b_V": "v.bias", 

70 "b_O": "o.bias", 

71 } 

72 

73 def __init__( 

74 self, 

75 name: Optional[str], 

76 config: Any, 

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

78 conversion_rule: Optional[BaseTensorConversion] = None, 

79 pattern_conversion_rule: Optional[BaseTensorConversion] = None, 

80 maintain_native_attention: bool = False, 

81 requires_position_embeddings: bool = False, 

82 requires_attention_mask: bool = False, 

83 attention_mask_4d: bool = False, 

84 requires_relative_position_bias: bool = False, 

85 is_cross_attention: bool = False, 

86 is_causal: bool = True, 

87 optional: bool = False, 

88 fused_qkv: bool = False, 

89 ): 

90 """Initialize the attention bridge. 

91 

92 Args: 

93 name: The name of this component, or None when projections live on the parent 

94 config: Model configuration (required for auto-conversion detection) 

95 submodules: Dictionary of submodules to register (e.g., q_proj, k_proj, etc.) 

96 conversion_rule: Optional conversion rule. If None, AttentionAutoConversion will be used 

97 pattern_conversion_rule: Optional conversion rule for attention patterns. If None, 

98 uses AttentionPatternConversion to ensure [n_heads, pos, pos] shape 

99 maintain_native_attention: If True, preserve the original HF attention implementation 

100 without wrapping. Use for models with custom attention 

101 (e.g., attention sinks, specialized RoPE). Defaults to False. 

102 requires_position_embeddings: If True, this attention requires position_embeddings argument 

103 (e.g., Gemma-3 with dual RoPE). Defaults to False. 

104 requires_attention_mask: If True, this attention requires attention_mask argument 

105 (e.g., GPTNeoX/Pythia). Defaults to False. 

106 attention_mask_4d: If True, generate 4D attention_mask [batch, 1, tgt_len, src_len] 

107 instead of 2D [batch, seq_len]. Required for OPT. Defaults to False. 

108 requires_relative_position_bias: T5/mT5-style relative attention; supplies a 

109 zero ``position_bias`` so HF's forward skips its ``cache_position[-1]`` fallback. 

110 is_cross_attention: Encoder-decoder cross-attention; supplies ``key_value_states``. 

111 is_causal: If True, apply a causal (lower-triangular) mask when reconstructing 

112 attention. Set False for bidirectional encoders (e.g. T5Gemma's encoder). 

113 """ 

114 if conversion_rule is None: 114 ↛ 116line 114 didn't jump to line 116 because the condition on line 114 was always true

115 conversion_rule = AttentionAutoConversion(config) 

116 super().__init__( 

117 name, 

118 config=config, 

119 submodules=submodules or {}, 

120 conversion_rule=conversion_rule, 

121 optional=optional, 

122 ) 

123 if fused_qkv: 

124 # A combined QKV projection has no q/k/v submodules for the class 

125 # aliases to resolve against; leaving them in place produces dead 

126 # aliases and resolution-audit noise (raven Wqkv, OpenELM qkv_proj). 

127 self.hook_aliases = { 

128 key: value 

129 for key, value in type(self).hook_aliases.items() 

130 if key not in {"hook_q", "hook_k", "hook_v"} 

131 } 

132 self.hook_attn_scores = HookPoint() 

133 self.hook_pattern = HookPoint() 

134 self.hook_hidden_states = HookPoint() 

135 # Per-head attention output, pre-sum across heads. 

136 # Shape [batch, pos, n_heads, d_model] when fired. Gated at fire time 

137 # by cfg.use_attn_result; the HookPoint exists unconditionally so 

138 # run_with_cache key lookups never miss. 

139 self.hook_result = HookPoint() 

140 # Pre-ln1 fork hooks ([B, S, H, D]) gated by use_split_qkv_input / 

141 # use_attn_in; fall back to post-ln1 if BlockBridge can't wire ln1. See #1317. 

142 if self.supports_split_qkv_fork: 

143 self.hook_attn_in = HookPoint() 

144 self.hook_q_input = HookPoint() 

145 self.hook_k_input = HookPoint() 

146 self.hook_v_input = HookPoint() 

147 self._captured_pre_ln_residual: Optional[torch.Tensor] = None 

148 self._ln1_module: Optional[torch.nn.Module] = None 

149 if ( 

150 hasattr(config, "positional_embedding_type") 

151 and config.positional_embedding_type == "rotary" 

152 ): 

153 self.hook_rot_k = HookPoint() 

154 self.hook_rot_q = HookPoint() 

155 self.hook_hidden_states.hook_conversion = conversion_rule 

156 if pattern_conversion_rule is not None: 156 ↛ 157line 156 didn't jump to line 157 because the condition on line 156 was never true

157 self.hook_pattern.hook_conversion = pattern_conversion_rule 

158 self._attn_scores = None 

159 self._pattern = None 

160 self._hf_forward_wrapped = False 

161 self.maintain_native_attention = maintain_native_attention 

162 self.requires_position_embeddings = requires_position_embeddings 

163 self.requires_attention_mask = requires_attention_mask 

164 self.attention_mask_4d = attention_mask_4d 

165 self.requires_relative_position_bias = requires_relative_position_bias 

166 self.is_cross_attention = is_cross_attention 

167 self.is_causal = is_causal 

168 self._layer_idx: Optional[int] = None 

169 

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

171 """Set original component and capture layer index for KV caching.""" 

172 super().set_original_component(original_component) 

173 layer_idx_raw = getattr(original_component, "layer_idx", None) 

174 if layer_idx_raw is not None: 

175 self._layer_idx = int(layer_idx_raw) 

176 

177 def _apply_ln1_per_head(self, x: torch.Tensor) -> torch.Tensor: 

178 """Apply ln1 to [B, S, H, D] with H folded into the batch. Identity if ln1 unwired. 

179 

180 Routes through the raw HF norm to avoid refiring ln1's internal hooks 

181 per-head — deliberate divergence from legacy's *Pre sub-hook firing. 

182 """ 

183 if self._ln1_module is None: 183 ↛ 184line 183 didn't jump to line 184 because the condition on line 183 was never true

184 return x 

185 b, s, h, d = x.shape 

186 return self._ln1_module(x.reshape(b * s * h, d)).reshape(b, s, h, d) 

187 

188 def _fork_and_norm_per_head( 

189 self, source: torch.Tensor, hook: HookPoint, n_heads: int 

190 ) -> torch.Tensor: 

191 """Repeat residual to [B, S, H, D], fire ``hook``, re-LN iff source is pre-LN.""" 

192 forked = einops.repeat(source, "b s d -> b s h d", h=n_heads).contiguous() 

193 forked = hook(forked) 

194 if self._captured_pre_ln_residual is not None: 

195 forked = self._apply_ln1_per_head(forked) 

196 return forked 

197 

198 def setup_hook_compatibility(self) -> None: 

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

200 

201 This sets up hook conversions that ensure Bridge hooks have the same shapes 

202 as HookedTransformer hooks. This includes reshaping Q/K/V/Z hooks from 

203 [batch, seq, d_model] to [batch, seq, n_heads, d_head] format. 

204 

205 This is called during Bridge.__init__ and should always be run. 

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

207 """ 

208 if self._hf_forward_wrapped: 

209 return 

210 if hasattr(self.config, "n_heads"): 210 ↛ 212line 210 didn't jump to line 212 because the condition on line 210 was always true

211 self._setup_qkv_hook_reshaping() 

212 self._hf_forward_wrapped = True 

213 

214 def get_random_inputs( 

215 self, 

216 batch_size: int = 2, 

217 seq_len: int = 8, 

218 device: Optional[torch.device] = None, 

219 dtype: Optional[torch.dtype] = None, 

220 ) -> Dict[str, Any]: 

221 """Get random inputs for testing this attention component. 

222 

223 Generates appropriate inputs based on the attention's requirements 

224 (position_embeddings, attention_mask, etc.). 

225 

226 Args: 

227 batch_size: Batch size for the test inputs 

228 seq_len: Sequence length for the test inputs 

229 device: Device to create tensors on (defaults to CPU) 

230 dtype: Dtype for generated tensors (defaults to float32) 

231 

232 Returns: 

233 Dictionary of keyword arguments to pass to forward() 

234 """ 

235 if device is None: 

236 device = torch.device("cpu") 

237 if dtype is None: 

238 dtype = torch.float32 

239 d_model = self.config.d_model if self.config and hasattr(self.config, "d_model") else 768 

240 inputs: Dict[str, Any] = { 

241 "hidden_states": torch.randn(batch_size, seq_len, d_model, device=device, dtype=dtype) 

242 } 

243 if self.requires_position_embeddings: 

244 if self.config: 244 ↛ 252line 244 didn't jump to line 252 because the condition on line 244 was always true

245 if hasattr(self.config, "d_head"): 245 ↛ 247line 245 didn't jump to line 247 because the condition on line 245 was always true

246 d_head = self.config.d_head 

247 elif hasattr(self.config, "head_dim"): 

248 d_head = self.config.head_dim 

249 else: 

250 d_head = 64 

251 else: 

252 d_head = 64 

253 rotary_pct = get_rotary_pct_from_config(self.config) 

254 rotary_ndims = int(rotary_pct * d_head) 

255 cos = torch.ones(1, seq_len, rotary_ndims, device=device, dtype=dtype) 

256 sin = torch.zeros(1, seq_len, rotary_ndims, device=device, dtype=dtype) 

257 inputs["position_embeddings"] = (cos, sin) 

258 # For models with internal rotary embeddings (e.g., GPT-J), the HF attention 

259 # forward expects position_ids to index into embed_positions. Models using 

260 # requires_position_embeddings get (cos, sin) tuples instead. 

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

262 self.config 

263 and hasattr(self.config, "positional_embedding_type") 

264 and self.config.positional_embedding_type == "rotary" 

265 and not self.requires_position_embeddings 

266 ): 

267 inputs["position_ids"] = ( 

268 torch.arange(seq_len, device=device).unsqueeze(0).expand(batch_size, -1) 

269 ) 

270 if self.requires_attention_mask: 270 ↛ 271line 270 didn't jump to line 271 because the condition on line 270 was never true

271 if self.attention_mask_4d: 

272 # Generate 4D attention mask [batch, 1, tgt_len, src_len] for models like OPT 

273 inputs["attention_mask"] = torch.ones( 

274 batch_size, 1, seq_len, seq_len, device=device 

275 ) 

276 else: 

277 # Generate 2D attention mask [batch, seq_len] for most models 

278 inputs["attention_mask"] = torch.ones(batch_size, seq_len, device=device) 

279 if self.requires_relative_position_bias: 279 ↛ 281line 279 didn't jump to line 281 because the condition on line 279 was never true

280 # Zero bias short-circuits HF's None-cache_position fallback in T5Attention. 

281 n_heads = self.config.n_heads if self.config and hasattr(self.config, "n_heads") else 1 

282 inputs["position_bias"] = torch.zeros( 

283 1, n_heads, seq_len, seq_len, device=device, dtype=dtype 

284 ) 

285 if self.is_cross_attention: 

286 inputs["key_value_states"] = torch.randn( 

287 batch_size, seq_len, d_model, device=device, dtype=dtype 

288 ) 

289 return inputs 

290 

291 def _setup_qkv_hook_reshaping(self) -> None: 

292 """Setup hook reshaping for Q/K/V/Z to match HookedTransformer shapes. 

293 

294 Reshapes hooks from [batch, seq, d_model] to [batch, seq, n_heads, d_head] format. 

295 For models with Grouped Query Attention (GQA), K and V use n_kv_heads instead of n_heads. 

296 

297 Sets up conversions for: 

298 - q.hook_out (aliased as hook_q) 

299 - k.hook_out (aliased as hook_k) - uses n_kv_heads if GQA 

300 - v.hook_out (aliased as hook_v) - uses n_kv_heads if GQA 

301 - o.hook_in (aliased as hook_z) 

302 """ 

303 

304 class ReshapeForAttentionHeads(BaseTensorConversion): 

305 """Reshape tensors to split attention heads for Q/K/V/Z compatibility.""" 

306 

307 # Marks the [batch, pos, head, d_head] layout so consumers (e.g. run_with_cache's 

308 # pos_slice) know the position axis is two from the end, not one. 

309 splits_attention_heads = True 

310 

311 def __init__(self, n_heads: int, d_head: int): 

312 super().__init__() 

313 self.n_heads = n_heads 

314 self.d_head = d_head 

315 

316 def handle_conversion(self, input_value, *full_context): 

317 """Convert from [batch, seq, d_model] to [batch, seq, n_heads, d_head].""" 

318 if len(input_value.shape) == 3: 318 ↛ 322line 318 didn't jump to line 322 because the condition on line 318 was always true

319 b, s, d = input_value.shape 

320 if d == self.n_heads * self.d_head: 

321 return input_value.view(b, s, self.n_heads, self.d_head) 

322 return input_value 

323 

324 def revert(self, input_value, *full_context): 

325 """Revert from [batch, seq, n_heads, d_head] to [batch, seq, d_model].""" 

326 if len(input_value.shape) == 4: 326 ↛ 331line 326 didn't jump to line 331 because the condition on line 326 was always true

327 b, s, n_h, d_h = input_value.shape 

328 if n_h == self.n_heads and d_h == self.d_head: 328 ↛ 331line 328 didn't jump to line 331 because the condition on line 328 was always true

329 # reshape (not view) — callers may pass non-contiguous tensors 

330 return input_value.reshape(b, s, n_h * d_h) 

331 return input_value 

332 

333 if self.config is None: 333 ↛ 334line 333 didn't jump to line 334 because the condition on line 333 was never true

334 raise RuntimeError(f"Config not set for {self.name}") 

335 

336 # Get n_heads (try n_heads first, then n_head) 

337 if hasattr(self.config, "n_heads"): 337 ↛ 339line 337 didn't jump to line 339 because the condition on line 337 was always true

338 n_heads = self.config.n_heads 

339 elif hasattr(self.config, "n_head"): 

340 n_heads = self.config.n_head 

341 else: 

342 # Can't setup reshaping without knowing number of heads 

343 return 

344 

345 # Get d_head (try d_head first, then compute from d_model or n_embd) 

346 if hasattr(self.config, "d_head"): 

347 d_head = self.config.d_head 

348 elif hasattr(self.config, "d_model"): 348 ↛ 349line 348 didn't jump to line 349 because the condition on line 348 was never true

349 d_head = self.config.d_model // n_heads 

350 elif hasattr(self.config, "n_embd"): 350 ↛ 351line 350 didn't jump to line 351 because the condition on line 350 was never true

351 d_head = self.config.n_embd // n_heads 

352 else: 

353 # Can't setup reshaping without knowing head dimension 

354 return 

355 n_kv_heads = n_heads 

356 if hasattr(self.config, "n_key_value_heads") and self.config.n_key_value_heads is not None: 

357 n_kv_heads = self.config.n_key_value_heads 

358 

359 # Per-layer d_head makes width division ambiguous (gemma4: 2048 = 8x256 

360 # = 4x512), so dividing by the majority scalar mis-factorizes silently. 

361 layer_d_head: Optional[int] = d_head 

362 per_layer_hd = getattr(self.config, "per_layer_head_dim", None) 

363 if per_layer_hd: 

364 entry: Any = None 

365 if self._layer_idx is not None and self._layer_idx < len(per_layer_hd): 

366 entry = per_layer_hd[self._layer_idx] 

367 if not (isinstance(entry, int) and entry > 0): 

368 entry = getattr(self.original_component, "head_dim", None) 

369 layer_d_head = entry if isinstance(entry, int) and entry > 0 else None 

370 

371 def conversion_dims( 

372 proj: Any, cfg_heads: int, width_attr: str = "out_features" 

373 ) -> Tuple[int, int]: 

374 """(n_heads, d_head) from the BOUND module width, not the cfg scalars. 

375 

376 OpenELM/laguna vary head counts per layer; cfg-only dims no-op there, 

377 flipping hook shapes mid-model. MLA excluded — its o-width is v_head_dim. 

378 """ 

379 if getattr(self, "_v_head_dim", None): 379 ↛ 380line 379 didn't jump to line 380 because the condition on line 379 was never true

380 return cfg_heads, d_head 

381 component = getattr(proj, "original_component", None) 

382 width = getattr(component, width_attr, None) 

383 if width and layer_d_head and width % layer_d_head == 0: 

384 return width // layer_d_head, layer_d_head 

385 return cfg_heads, layer_d_head or d_head 

386 

387 if hasattr(self, "q") and self.q is not None and hasattr(self.q, "hook_out"): 

388 q_reshape = ReshapeForAttentionHeads(*conversion_dims(self.q, n_heads)) 

389 self.q.hook_out.hook_conversion = q_reshape 

390 if hasattr(self, "k") and self.k is not None and hasattr(self.k, "hook_out"): 

391 k_reshape = ReshapeForAttentionHeads(*conversion_dims(self.k, n_kv_heads)) 

392 self.k.hook_out.hook_conversion = k_reshape 

393 # Subclasses that de-alias hook_k onto their own HookPoint (K-scaling 

394 # architectures) need the same conversion, whichever order runs first. 

395 if "hook_k" not in self.hook_aliases and isinstance( 

396 getattr(self, "hook_k", None), HookPoint 

397 ): 

398 self.hook_k.hook_conversion = k_reshape 

399 if hasattr(self, "v") and self.v is not None and hasattr(self.v, "hook_out"): 

400 v_reshape = ReshapeForAttentionHeads(*conversion_dims(self.v, n_kv_heads)) 

401 self.v.hook_out.hook_conversion = v_reshape 

402 if hasattr(self, "o") and self.o is not None and hasattr(self.o, "hook_in"): 402 ↛ 408line 402 didn't jump to line 408 because the condition on line 402 was always true

403 z_reshape = ReshapeForAttentionHeads( 

404 *conversion_dims(self.o, n_heads, width_attr="in_features") 

405 ) 

406 self.o.hook_in.hook_conversion = z_reshape 

407 

408 class TransposeRotaryHeads(BaseTensorConversion): 

409 """Transpose rotary hook tensors from HF format to HookedTransformer format.""" 

410 

411 def handle_conversion(self, input_value, *full_context): 

412 """Convert from [batch, n_heads, seq, d_head] to [batch, seq, n_heads, d_head].""" 

413 if len(input_value.shape) == 4: 413 ↛ 415line 413 didn't jump to line 415 because the condition on line 413 was always true

414 return input_value.transpose(1, 2) 

415 return input_value 

416 

417 def revert(self, input_value, *full_context): 

418 """Revert from [batch, seq, n_heads, d_head] to [batch, n_heads, seq, d_head].""" 

419 if len(input_value.shape) == 4: 419 ↛ 421line 419 didn't jump to line 421 because the condition on line 419 was always true

420 return input_value.transpose(1, 2) 

421 return input_value 

422 

423 if hasattr(self, "hook_rot_q"): 

424 self.hook_rot_q.hook_conversion = TransposeRotaryHeads() 

425 if hasattr(self, "hook_rot_k"): 

426 self.hook_rot_k.hook_conversion = TransposeRotaryHeads() 

427 

428 def _update_kv_cache( 

429 self, k: torch.Tensor, v: torch.Tensor, **kwargs: Any 

430 ) -> tuple[torch.Tensor, torch.Tensor]: 

431 """Update KV cache if provided, returning the (possibly extended) K and V. 

432 

433 Call this after K/V projections and any positional embeddings (e.g. RoPE) 

434 have been applied, but before computing attention scores. If no cache is 

435 present in kwargs, K and V are returned unchanged. 

436 """ 

437 past_key_values = kwargs.get("past_key_values", None) 

438 if past_key_values is None: 

439 # GPT-NeoX/GPT-J/Bloom/Falcon/MPT/CodeGen/GPTBigCode still name the 

440 # cache `layer_past`; missing it leaves the cache empty, so every 

441 # decode step attends to itself alone and generation ignores the prompt. 

442 past_key_values = kwargs.get("layer_past", None) 

443 if past_key_values is None: 

444 return k, v 

445 layer_idx = getattr(self, "_layer_idx", None) 

446 if layer_idx is None: 

447 logger.warning( 

448 "%s: past_key_values provided but _layer_idx is None " 

449 "(HF component missing layer_idx attribute). KV cache update " 

450 "skipped — cached generation will ignore earlier tokens.", 

451 self.name, 

452 ) 

453 return k, v 

454 # Some architectures (e.g. HRM-Text's recurrent stacks) pass a cycle_offset 

455 # so each stack invocation writes to a unique cache slot. Non-participating 

456 # models simply leave it unset. 

457 cycle_offset = kwargs.get("cycle_offset", 0) 

458 k, v = past_key_values.update(k, v, layer_idx + cycle_offset) 

459 return k, v 

460 

461 def _reshape_qkv_to_heads( 

462 self, 

463 q: torch.Tensor, 

464 k: torch.Tensor, 

465 v: torch.Tensor, 

466 num_heads: int, 

467 num_kv_heads: int | None = None, 

468 ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, int, int, int]: 

469 """Reshape Q/K/V from [batch, seq, hidden] or [batch, seq, heads, head_dim] 

470 to [batch, heads, seq, head_dim]. Returns (q, k, v, batch_size, seq_len, head_dim). 

471 

472 Args: 

473 num_kv_heads: If provided and differs from num_heads (GQA), K/V use 

474 this head count for the 3D reshape path. 

475 """ 

476 if num_kv_heads is None: 

477 num_kv_heads = num_heads 

478 if q.ndim == 3: 

479 batch_size, seq_len, q_hidden = q.shape 

480 head_dim: int = q_hidden // num_heads 

481 q = q.view(batch_size, seq_len, num_heads, head_dim).transpose(1, 2) 

482 k = k.view(batch_size, seq_len, num_kv_heads, head_dim).transpose(1, 2) 

483 v = v.view(batch_size, seq_len, num_kv_heads, head_dim).transpose(1, 2) 

484 elif q.ndim == 4: 484 ↛ 491line 484 didn't jump to line 491 because the condition on line 484 was always true

485 batch_size, seq_len = q.shape[0], q.shape[1] 

486 head_dim = q.shape[-1] 

487 q = q.transpose(1, 2) 

488 k = k.transpose(1, 2) 

489 v = v.transpose(1, 2) 

490 else: 

491 raise ValueError(f"Unexpected Q tensor shape: {q.shape}. Expected 3D or 4D.") 

492 return q, k, v, batch_size, seq_len, head_dim 

493 

494 def _apply_attn_dropout(self, attn_weights: torch.Tensor) -> torch.Tensor: 

495 """Apply attention dropout from the original HF component if present.""" 

496 if self.original_component is not None: 496 ↛ 502line 496 didn't jump to line 502 because the condition on line 496 was always true

497 dropout_fn = getattr(self.original_component, "attn_dropout", None) 

498 if dropout_fn is None: 

499 dropout_fn = getattr(self.original_component, "attention_dropout", None) 

500 if dropout_fn is not None and callable(dropout_fn): 

501 attn_weights = dropout_fn(attn_weights) 

502 return attn_weights 

503 

504 def _apply_output_projection(self, attn_output: torch.Tensor) -> torch.Tensor: 

505 """Apply the output projection (self.o) if present.""" 

506 if hasattr(self, "o") and self.o is not None: 

507 attn_output = self.o(attn_output) 

508 return attn_output 

509 

510 def _softmax_dropout_pattern( 

511 self, 

512 attn_scores: torch.Tensor, 

513 target_dtype: torch.dtype | None = None, 

514 upcast_to_fp32: bool = False, 

515 ) -> torch.Tensor: 

516 """Apply softmax, dropout, and hook_pattern to attention scores. 

517 

518 Args: 

519 attn_scores: Raw attention scores [batch, heads, q_seq, kv_seq]. 

520 target_dtype: If set, cast weights to this dtype after softmax. 

521 upcast_to_fp32: If True, compute softmax in float32 for numerical 

522 stability, then cast to target_dtype. 

523 """ 

524 if upcast_to_fp32: 

525 attn_weights = self._masked_softmax(attn_scores, dtype=torch.float32) 

526 if target_dtype is not None: 526 ↛ 532line 526 didn't jump to line 532 because the condition on line 526 was always true

527 attn_weights = attn_weights.to(target_dtype) 

528 else: 

529 attn_weights = self._masked_softmax(attn_scores) 

530 if target_dtype is not None: 

531 attn_weights = attn_weights.to(target_dtype) 

532 attn_weights = self._scrub_compatibility_pattern_nans(attn_weights) 

533 attn_weights = self._apply_attn_dropout(attn_weights) 

534 attn_weights = self.hook_pattern(attn_weights) 

535 return attn_weights 

536 

537 def _masked_softmax( 

538 self, attn_scores: torch.Tensor, dtype: torch.dtype | None = None 

539 ) -> torch.Tensor: 

540 """Softmax over keys that zeroes fully masked rows in compatibility mode. 

541 

542 Compatibility mode masks with -inf, so a query with no visible key (e.g. 

543 the leading pads of a left-padded row) softmaxes to NaN. Zeroing that NaN 

544 afterwards only fixes the forward: softmax's backward still multiplies by 

545 the NaN output and leaks it into Q/K and the residual stream. 

546 """ 

547 if not self.compatibility_mode: 

548 return torch.nn.functional.softmax(attn_scores, dim=-1, dtype=dtype) 

549 fully_masked = torch.isneginf(attn_scores).all(dim=-1, keepdim=True) 

550 pattern = torch.nn.functional.softmax( 

551 attn_scores.masked_fill(fully_masked, 0.0), dim=-1, dtype=dtype 

552 ) 

553 return pattern.masked_fill(fully_masked, 0.0) 

554 

555 def _scrub_compatibility_pattern_nans(self, pattern: torch.Tensor) -> torch.Tensor: 

556 """Match HookedTransformer's NaN scrub of the attention pattern.""" 

557 if self.compatibility_mode: 

558 pattern = torch.where(torch.isnan(pattern), torch.zeros_like(pattern), pattern) 

559 return pattern 

560 

561 def _normalize_compatibility_mask_sentinel(self, attention_mask: torch.Tensor) -> torch.Tensor: 

562 """Normalize additive mask sentinels before dtype conversion or addition.""" 

563 if self.compatibility_mode and attention_mask.is_floating_point(): 

564 attention_mask = attention_mask.masked_fill( 

565 attention_mask <= torch.finfo(attention_mask.dtype).min, -torch.inf 

566 ) 

567 return attention_mask 

568 

569 def _reshape_attn_output( 

570 self, 

571 attn_output: torch.Tensor, 

572 batch_size: int, 

573 seq_len: int, 

574 num_heads: int, 

575 head_dim: int, 

576 ) -> torch.Tensor: 

577 """Reshape attention output from [batch, heads, seq, dim] to [batch, seq, hidden].""" 

578 attn_output = attn_output.transpose(1, 2).contiguous() 

579 attn_output = attn_output.view(batch_size, seq_len, num_heads * head_dim) 

580 return attn_output 

581 

582 def _apply_reconstruct_attention_mask( 

583 self, 

584 attn_scores: torch.Tensor, 

585 attention_mask: torch.Tensor | None, 

586 seq_len: int, 

587 q_seq_len: int | None = None, 

588 ) -> torch.Tensor: 

589 """Apply causal and optional attention masking to reconstructed scores. 

590 

591 4D masks are treated as authoritative, matching HF, which applies a 4D 

592 mask as given. Lower-rank masks carry no causal structure, so the local 

593 causal mask is applied before adding them. On subclasses that set 

594 ``broadcast_mask_is_padding_only``, a 4D mask broadcast over the query 

595 rows ([batch, 1, 1, kv_seq_len]) is padding only and gets the local 

596 causal mask too. 

597 

598 Args: 

599 attn_scores: Attention scores [batch, heads, q_seq_len, kv_seq_len]. 

600 attention_mask: Optional mask from the caller. 

601 seq_len: The KV sequence length (total positions including cache). 

602 q_seq_len: The query sequence length. When using KV cache this is 

603 shorter than seq_len. Defaults to seq_len when not provided. 

604 """ 

605 if q_seq_len is None: 

606 q_seq_len = seq_len 

607 min_dtype = torch.finfo(attn_scores.dtype).min 

608 mask_value = -torch.inf if self.compatibility_mode else min_dtype 

609 use_direct_hf_mask = ( 

610 attention_mask is not None 

611 and attention_mask.ndim >= 4 

612 and not (self.broadcast_mask_is_padding_only and attention_mask.shape[-2] == 1) 

613 ) 

614 # Bidirectional attention (encoders) and cross-attention have no causal 

615 # structure, so only synthesize the triangular mask for causal self-attention. 

616 apply_causal = self.is_causal and not self.is_cross_attention 

617 if not use_direct_hf_mask and apply_causal: 

618 # Rectangular causal mask: query i attends to KV 0..(offset+i) 

619 # where offset = kv_seq_len - q_seq_len (cached positions). 

620 causal_mask = torch.ones( 

621 q_seq_len, seq_len, device=attn_scores.device, dtype=torch.bool 

622 ) 

623 causal_mask = torch.tril(causal_mask, diagonal=seq_len - q_seq_len) 

624 attn_scores = attn_scores.masked_fill(~causal_mask, mask_value) 

625 

626 if attention_mask is not None: 

627 if attention_mask.shape[-1] != seq_len: 627 ↛ 628line 627 didn't jump to line 628 because the condition on line 627 was never true

628 attention_mask = attention_mask[..., :seq_len] 

629 if attention_mask.ndim >= 3 and attention_mask.shape[-2] != q_seq_len: 

630 # Extra query rows mean a full-sequence mask on a cached decode step, 

631 # where the live queries are the LAST rows; taking the first hands 

632 # every step position 0 (Baichuan-13B fuses ALiBi slopes in here). 

633 attention_mask = attention_mask[..., -q_seq_len:, :] 

634 

635 if attention_mask.dtype == torch.bool: 

636 attention_mask = torch.where( 

637 attention_mask, 

638 torch.zeros((), dtype=attn_scores.dtype, device=attn_scores.device), 

639 torch.full((), mask_value, dtype=attn_scores.dtype, device=attn_scores.device), 

640 ) 

641 else: 

642 attention_mask = self._normalize_compatibility_mask_sentinel(attention_mask) 

643 attention_mask = attention_mask.to(dtype=attn_scores.dtype) 

644 attn_scores = attn_scores + attention_mask 

645 

646 return attn_scores 

647 

648 def _get_n_heads(self, use_kv: bool = False) -> int: 

649 """Resolve the number of attention heads from config. 

650 

651 Args: 

652 use_kv: If True, return n_key_value_heads (for GQA) when available. 

653 """ 

654 assert self.config is not None, "config required to resolve n_heads" 

655 if use_kv: 

656 if hasattr(self.config, "n_key_value_heads") and self.config.n_key_value_heads: 

657 return self.config.n_key_value_heads 

658 if hasattr(self.config, "n_heads"): 

659 return self.config.n_heads 

660 return self.config.n_head 

661 

662 def _weight_layout_in_out(self, proj: Any) -> Optional[bool]: 

663 """Whether ``proj``'s wrapped module stores its weight as [in, out]. 

664 

665 Conv1D (GPT-2 style) stores [in_features, out_features]; nn.Linear stores 

666 [out_features, in_features]. Returns None when the wrapped module is 

667 neither, so callers can fall back to a shape heuristic. 

668 """ 

669 component = getattr(proj, "original_component", None) 

670 if isinstance(component, Conv1D): 

671 return True 

672 if isinstance(component, torch.nn.Linear): 

673 return False 

674 return None 

675 

676 def _reshape_weight_to_3d( 

677 self, 

678 weight: torch.Tensor, 

679 n_heads: int, 

680 pattern: str = "qkv", 

681 in_out_layout: Optional[bool] = None, 

682 ) -> torch.Tensor: 

683 """Reshape a 2D weight to 3D by splitting heads. 

684 

685 Args: 

686 weight: 2D weight tensor 

687 n_heads: Number of heads to split into 

688 pattern: "qkv" for [n_heads, d_model, d_head], "o" for [n_heads, d_head, d_model] 

689 in_out_layout: True if the weight is stored [in, out] (Conv1D), False 

690 for [out, in] (nn.Linear). None falls back to a shape heuristic, 

691 which cannot distinguish the two when the weight is square. 

692 """ 

693 if pattern == "o": 

694 if in_out_layout is None: 

695 # Heuristic: assumes [in, out] whenever the head split fits dim 0. 

696 in_out_layout = weight.shape[0] == n_heads * ( 

697 weight.shape[1] // n_heads 

698 if weight.shape[1] % n_heads == 0 

699 else weight.shape[0] // n_heads 

700 ) 

701 mat = weight if in_out_layout else weight.T 

702 self._check_head_split_width(mat, n_heads) 

703 return einops.rearrange( 

704 mat, "(n_heads d_head) d_model -> n_heads d_head d_model", n_heads=n_heads 

705 ) 

706 # QKV pattern 

707 if in_out_layout is None: 

708 in_out_layout = weight.shape[0] % n_heads != 0 

709 mat = weight.T if in_out_layout else weight 

710 self._check_head_split_width(mat, n_heads) 

711 return einops.rearrange( 

712 mat, "(n_heads d_head) d_model -> n_heads d_model d_head", n_heads=n_heads 

713 ) 

714 

715 def _check_head_split_width(self, mat: torch.Tensor, n_heads: int) -> None: 

716 """Refuse a head split whose width disagrees with the model's geometry. 

717 

718 einops only needs divisibility, so per-layer geometry (gemma4 KV-shared 

719 layers) would factorize into wrong-shaped heads silently. MLA's 

720 bind-time ``_v_head_dim`` is a legitimate second width (o_proj). 

721 """ 

722 d_head = getattr(self.config, "d_head", None) 

723 if not d_head: 

724 return 

725 allowed_dims = {d_head} 

726 v_head_dim = getattr(self, "_v_head_dim", None) 

727 if v_head_dim: 

728 allowed_dims.add(v_head_dim) 

729 if mat.shape[0] % n_heads == 0 and mat.shape[0] // n_heads in allowed_dims: 

730 return 

731 raise PerLayerGeometryError( 

732 f"Cannot split {tuple(mat.shape)} weight on '{self.name}' into " 

733 f"{n_heads} heads of d_head in {sorted(allowed_dims)}: this " 

734 "layer's attention geometry differs from the config-level scalars " 

735 "(per-layer num_key_value_heads/head_dim, e.g. gemma4 KV-shared " 

736 "or K==V layers). Read the wrapped module's weight directly for " 

737 "this layer instead." 

738 ) 

739 

740 def _project_per_head_qkv( 

741 self, 

742 linear_bridge: "GeneralizedComponent", 

743 input_4d: torch.Tensor, 

744 n_heads: int, 

745 d_head: int, 

746 ) -> torch.Tensor: 

747 """Per-head Q/K/V projection over a 4D residual fork. 

748 

749 Plain nn.Linear applied to [batch, pos, H, d_model] broadcasts the 

750 same weight across heads' copies — which for the split-qkv fork means 

751 head h's copy sees every head's W rows, not just head h's. This routes 

752 head h's copy through head h's W slice only via a per-head einsum. 

753 

754 Fires `linear_bridge.hook_out` on the flat 3D tensor so the hook sees 

755 the same shape as the default path and downstream code receives a 

756 consistent 4D `[B, S, H, d_head]` regardless of whether the user's 

757 hook modified the tensor (which would otherwise trigger the 

758 `hook_conversion.revert` 4D→3D flatten). 

759 """ 

760 component = linear_bridge.original_component 

761 assert component is not None, "LinearBridge.original_component not set" 

762 weight = require_readable_weight( 

763 component.weight, 

764 operation="project per head (use_split_qkv_input / use_attn_in)", 

765 owner=component, 

766 ) 

767 bias = component.bias 

768 w3d = einops.rearrange( 

769 weight, 

770 "(n_heads d_head) d_model -> n_heads d_model d_head", 

771 n_heads=n_heads, 

772 d_head=d_head, 

773 ) 

774 out = torch.einsum("bshd,hde->bshe", input_4d, w3d) 

775 if bias is not None: 

776 b2d = einops.rearrange(bias, "(n_heads d_head) -> n_heads d_head", n_heads=n_heads) 

777 assert isinstance(b2d, torch.Tensor) 

778 out = out + b2d 

779 # Flatten to 3D for hook_out (matches default-path shape); the 

780 # hook_conversion reshapes to 4D for the user's fwd_hook, then reverts 

781 # to 3D if the hook returned a modified tensor. Return 4D always. 

782 b, s = out.shape[0], out.shape[1] 

783 out_flat = out.reshape(b, s, n_heads * d_head) 

784 out_flat = linear_bridge.hook_out(out_flat) 

785 return out_flat.reshape(b, s, n_heads, d_head) 

786 

787 def _compute_per_head_result( 

788 self, 

789 z_4d: torch.Tensor, 

790 n_heads: int, 

791 d_head: int, 

792 ) -> torch.Tensor: 

793 """Per-head attention output pre-sum across heads. 

794 

795 Computes (z[..., h, :] @ W_O_per_head[h]) for each head h, fires 

796 hook_result on the resulting [batch, pos, n_heads, d_model], then sums 

797 across heads and adds b_O. Distributive over weight folding 

798 (`sum_h z_h @ W_O_h + b_O == z_flat @ W_O.T + b_O`), so compat-mode and 

799 raw-weight paths produce identical logits. 

800 """ 

801 o = self.o.original_component 

802 weight = o.weight 

803 bias = getattr(o, "bias", None) 

804 # HF Conv1D (GPT-2, GPT-J, CodeGen) stores weight as [in, out]; nn.Linear 

805 # stores [out, in]. When W_O is square (d_model == n_heads*d_head, which 

806 # is the common case), shape alone is ambiguous — dispatch on module 

807 # type instead. 

808 weight_is_in_out = type(o).__name__ == "Conv1D" 

809 if weight_is_in_out: 

810 w_per_head = einops.rearrange( 

811 weight, 

812 "(n_heads d_head) d_model -> n_heads d_head d_model", 

813 n_heads=n_heads, 

814 d_head=d_head, 

815 ) 

816 else: 

817 w_per_head = einops.rearrange( 

818 weight, 

819 "d_model (n_heads d_head) -> n_heads d_head d_model", 

820 n_heads=n_heads, 

821 d_head=d_head, 

822 ) 

823 per_head = torch.einsum("bshd,hdm->bshm", z_4d, w_per_head) 

824 scale = getattr(self, "_result_contribution_scale", 1.0) 

825 if scale == 1.0: 

826 # Keep callable hook replacements on the original unscaled path. 

827 per_head = self.hook_result(per_head) 

828 else: 

829 per_head = self._hook_scaled_output(per_head, self.hook_result, scale) 

830 summed = per_head.sum(dim=-2) 

831 if bias is not None: 

832 summed = summed + bias 

833 return summed 

834 

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

836 """Simplified forward pass - minimal wrapping around original component. 

837 

838 This does minimal wrapping: hook_in → delegate to HF → hook_out. 

839 This ensures we match HuggingFace's exact output without complex intermediate processing. 

840 

841 Args: 

842 *args: Input arguments to pass to the original component 

843 **kwargs: Input keyword arguments to pass to the original component 

844 

845 Returns: 

846 The output from the original component, with only input/output hooks applied 

847 """ 

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

849 raise RuntimeError( 

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

851 ) 

852 if "query_input" in kwargs: 

853 hooked = self.hook_in(kwargs["query_input"]) 

854 kwargs["query_input"] = hooked 

855 elif "hidden_states" in kwargs: 

856 hooked = self.hook_in(kwargs["hidden_states"]) 

857 kwargs["hidden_states"] = hooked 

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

859 hooked = self.hook_in(args[0]) 

860 args = (hooked,) + args[1:] 

861 # Modules exposing the pattern seam (NativeAttention) run the pattern 

862 # through hook_pattern INSIDE the computation, so hook edits re-weight 

863 # the output; post-hoc firing below cannot (see _fire_post_hoc_hook). 

864 pattern_hooked_inside = bool(getattr(self.original_component, "accepts_pattern_fn", False)) 

865 if pattern_hooked_inside: 

866 kwargs["pattern_fn"] = self.hook_pattern 

867 # Relative-position-bias modules (T5 family) return position_bias, not 

868 # attention weights, in output[1]: force the real weights into the 

869 # output and capture Q/K to rebuild the pre-softmax scores. 

870 reroute_position_bias = self.requires_relative_position_bias 

871 caller_output_attentions = bool(kwargs.get("output_attentions", False)) 

872 qk_capture: Dict[str, torch.Tensor] = {} 

873 capture_handles: list = [] 

874 if reroute_position_bias: 

875 kwargs["output_attentions"] = True 

876 capture_handles = self._capture_qk_outputs(qk_capture) 

877 # try/finally so the captured tensor (and its autograd graph) is 

878 # released even if original_component raises. 

879 try: 

880 output = self.original_component(*args, **kwargs) 

881 finally: 

882 self._captured_pre_ln_residual = None 

883 for handle in capture_handles: 

884 handle.remove() 

885 if isinstance(output, tuple) and len(output) >= 2: 

886 # output[0] is attention output 

887 # output[1] may be attention weights (pattern) or position_bias (T5) 

888 # Additional elements may include position_bias, attention weights, etc. 

889 attn_output = self.hook_out(output[0]) 

890 if reroute_position_bias: 

891 output = (attn_output,) + self._fire_position_bias_module_hooks( 

892 output[1:], qk_capture, caller_output_attentions 

893 ) 

894 else: 

895 second_element = output[1] 

896 # Fire hook_pattern if the second element is attention weights (4D tensor) 

897 if isinstance(second_element, torch.Tensor) and second_element.dim() == 4: 

898 # This looks like attention weights [batch, heads, seq, seq] 

899 if not pattern_hooked_inside: 

900 second_element = self._fire_post_hoc_hook( 

901 self.hook_pattern, second_element, "hook_pattern" 

902 ) 

903 # Also store for potential hook_attn_scores (before softmax) 

904 # Note: Most HF implementations return post-softmax weights 

905 self._fire_post_hoc_hook( 

906 self.hook_attn_scores, second_element, "hook_attn_scores" 

907 ) 

908 output = (attn_output, second_element) + output[2:] 

909 elif isinstance(output, tuple) and len(output) == 1: 909 ↛ 910line 909 didn't jump to line 910 because the condition on line 909 was never true

910 output = (self.hook_out(output[0]),) 

911 else: 

912 output = self.hook_out(output) 

913 return output 

914 

915 def _capture_qk_outputs(self, store: Dict[str, torch.Tensor]) -> list: 

916 """Capture the Q/K projection outputs during the wrapped module's forward. 

917 

918 The relative-position-bias path rebuilds pre-softmax scores from these 

919 (the wrapped module exposes neither the scores nor a seam to hook them). 

920 Returns the handles; the caller removes them after the forward. 

921 """ 

922 handles = [] 

923 for key in ("q", "k"): 

924 proj = self._modules.get(key) 

925 if proj is None: 925 ↛ 928line 925 didn't jump to line 928 because the condition on line 925 was always true

926 continue 

927 

928 def make_capture(name: str): 

929 def capture(module: Any, inputs: Any, out: Any) -> None: 

930 if isinstance(out, torch.Tensor): 930 ↛ exitline 930 didn't return from function 'capture' because the condition on line 930 was always true

931 store[name] = out 

932 

933 return capture 

934 

935 handles.append(proj.register_forward_hook(make_capture(key))) 

936 return handles 

937 

938 def _fire_position_bias_module_hooks( 

939 self, 

940 rest: Tuple[Any, ...], 

941 qk_capture: Dict[str, torch.Tensor], 

942 caller_output_attentions: bool, 

943 ) -> Tuple[Any, ...]: 

944 """Fire pattern/scores hooks for a module whose output[1] is position_bias. 

945 

946 ``rest`` is the wrapped module's output after the attention output: 

947 (position_bias, attn_weights?) with the weights present because forward 

948 forced ``output_attentions``. The forced element is stripped again 

949 unless the caller asked for it, so upstream tuple indexing (the HF 

950 stack reads fixed positions) stays intact. The bias itself gets no 

951 hooks: it is a broadcast [1, heads, q, k] additive term, not a pattern. 

952 """ 

953 position_bias = rest[0] 

954 weights = rest[1] if len(rest) >= 2 else None 

955 if not (isinstance(weights, torch.Tensor) and weights.dim() == 4): 955 ↛ 956line 955 didn't jump to line 956 because the condition on line 955 was never true

956 return rest 

957 scores = self._reconstruct_bias_scores(qk_capture, position_bias, weights) 

958 if scores is not None: 

959 self._fire_post_hoc_hook(self.hook_attn_scores, scores, "hook_attn_scores") 

960 weights = self._fire_post_hoc_hook(self.hook_pattern, weights, "hook_pattern") 

961 if caller_output_attentions or not self._output_attentions_is_optional(): 

962 return (position_bias, weights) + rest[2:] 

963 return (position_bias,) + rest[2:] 

964 

965 def _output_attentions_is_optional(self) -> bool: 

966 """Whether the wrapped module only returns weights when asked to. 

967 

968 Transformers >= 5.15 T5 attention always returns three values, which callers unpack. 

969 """ 

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

971 return True 

972 try: 

973 params = inspect.signature(self.original_component.forward).parameters 

974 except (TypeError, ValueError): 

975 return True 

976 return "output_attentions" in params 

977 

978 def _reconstruct_bias_scores( 

979 self, 

980 qk_capture: Dict[str, torch.Tensor], 

981 position_bias: Any, 

982 attn_weights: torch.Tensor, 

983 ) -> Optional[torch.Tensor]: 

984 """Rebuild pre-softmax scores as q @ k^T + position_bias. 

985 

986 T5-family attention applies no 1/sqrt(d) scaling, and the returned bias 

987 already folds in the attention mask, so this reproduces the exact tensor 

988 HF softmaxed. Returns None when Q or K was not captured this forward 

989 (e.g. cross-attention K served from an encoder-decoder cache) or the 

990 captured shapes disagree with the weights (e.g. cached decode steps). 

991 """ 

992 q = qk_capture.get("q") 

993 k = qk_capture.get("k") 

994 if q is None or k is None or q.dim() != 3 or k.dim() != 3: 

995 return None 

996 batch, n_heads, q_len, k_len = attn_weights.shape 

997 if ( 

998 q.shape[0] != batch 

999 or q.shape[1] != q_len 

1000 or k.shape[0] != batch 

1001 or k.shape[1] != k_len 

1002 or q.shape[2] != k.shape[2] 

1003 or q.shape[2] % n_heads != 0 

1004 ): 

1005 return None 

1006 q4 = q.view(batch, q_len, n_heads, -1).transpose(1, 2) 

1007 k4 = k.view(batch, k_len, n_heads, -1).transpose(1, 2) 

1008 scores = torch.matmul(q4, k4.transpose(3, 2)) 

1009 if isinstance(position_bias, torch.Tensor): 1009 ↛ 1011line 1009 didn't jump to line 1011 because the condition on line 1009 was always true

1010 scores = scores + position_bias 

1011 return scores 

1012 

1013 def _fire_post_hoc_hook( 

1014 self, hook: HookPoint, tensor: torch.Tensor, hook_label: str 

1015 ) -> torch.Tensor: 

1016 """Fire a hook on a tensor the wrapped HF module already consumed. 

1017 

1018 An edit returned from such a hook cannot flow back into the attention 

1019 output, so it earns a warning instead of silently doing nothing. 

1020 Read-only hooks (e.g. caching) return the tensor unchanged and stay 

1021 silent. 

1022 """ 

1023 result = hook(tensor) 

1024 if isinstance(result, torch.Tensor) and result is not tensor: 

1025 try: 

1026 unchanged = result.shape == tensor.shape and torch.equal(result, tensor) 

1027 except RuntimeError: 

1028 unchanged = False 

1029 if not unchanged: 

1030 warnings.warn( 

1031 f"A hook on {self.name or type(self).__name__}.{hook_label} returned a " 

1032 "modified tensor, but this attention delegates its computation to the " 

1033 "wrapped HF module, which has already consumed the original values. The " 

1034 "edit is discarded and does not affect the model's output.", 

1035 UserWarning, 

1036 stacklevel=2, 

1037 ) 

1038 return result 

1039 

1040 @property 

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

1042 """Get W_Q in 3D format [n_heads, d_model, d_head]. 

1043 

1044 Gated query projections retain their live query-and-gate parameter; 

1045 this analysis view selects the query rows interleaved within each head. 

1046 """ 

1047 weight = require_readable_weight( 

1048 self.q.weight, operation=f"read W_Q from {self.name}", owner=self.q 

1049 ) 

1050 if weight.ndim == 2 and self.config is not None: 1050 ↛ 1071line 1050 didn't jump to line 1071 because the condition on line 1050 was always true

1051 n_heads = self._get_n_heads() 

1052 in_out_layout = self._weight_layout_in_out(self.q) 

1053 if getattr(self.config, "gated_q_proj", False): 

1054 d_head = int(self.config.d_head) 

1055 gated_width = n_heads * d_head * 2 

1056 if in_out_layout is True: 1056 ↛ 1057line 1056 didn't jump to line 1057 because the condition on line 1056 was never true

1057 output_first_weight = weight.T 

1058 elif in_out_layout is False or weight.shape[0] == gated_width: 1058 ↛ 1060line 1058 didn't jump to line 1060 because the condition on line 1058 was always true

1059 output_first_weight = weight 

1060 elif weight.shape[1] == gated_width: 

1061 output_first_weight = weight.T 

1062 else: 

1063 output_first_weight = None 

1064 

1065 if output_first_weight is not None and output_first_weight.shape[0] == gated_width: 1065 ↛ 1070line 1065 didn't jump to line 1070 because the condition on line 1065 was always true

1066 # Preserve the live query-gate projection; W_Q is an analysis-only query view. 

1067 per_head_weight = output_first_weight.reshape(n_heads, d_head * 2, -1) 

1068 return per_head_weight[:, :d_head, :].transpose(-1, -2) 

1069 

1070 return self._reshape_weight_to_3d(weight, n_heads, in_out_layout=in_out_layout) 

1071 return weight 

1072 

1073 @property 

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

1075 """Get W_K in 3D format [n_heads, d_model, d_head] (uses n_kv_heads for GQA).""" 

1076 weight = require_readable_weight( 

1077 self.k.weight, operation=f"read W_K from {self.name}", owner=self.k 

1078 ) 

1079 if weight.ndim == 2 and self.config is not None: 1079 ↛ 1085line 1079 didn't jump to line 1085 because the condition on line 1079 was always true

1080 return self._reshape_weight_to_3d( 

1081 weight, 

1082 self._get_n_heads(use_kv=True), 

1083 in_out_layout=self._weight_layout_in_out(self.k), 

1084 ) 

1085 return weight 

1086 

1087 @property 

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

1089 """Get W_V in 3D format [n_heads, d_model, d_head] (uses n_kv_heads for GQA).""" 

1090 weight = require_readable_weight( 

1091 self.v.weight, operation=f"read W_V from {self.name}", owner=self.v 

1092 ) 

1093 if weight.ndim == 2 and self.config is not None: 1093 ↛ 1099line 1093 didn't jump to line 1099 because the condition on line 1093 was always true

1094 return self._reshape_weight_to_3d( 

1095 weight, 

1096 self._get_n_heads(use_kv=True), 

1097 in_out_layout=self._weight_layout_in_out(self.v), 

1098 ) 

1099 return weight 

1100 

1101 @property 

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

1103 """Get W_O in 3D format [n_heads, d_head, d_model].""" 

1104 weight = require_readable_weight( 

1105 self.o.weight, operation=f"read W_O from {self.name}", owner=self.o 

1106 ) 

1107 if weight.ndim == 2 and self.config is not None: 1107 ↛ 1114line 1107 didn't jump to line 1114 because the condition on line 1107 was always true

1108 return self._reshape_weight_to_3d( 

1109 weight, 

1110 self._get_n_heads(), 

1111 pattern="o", 

1112 in_out_layout=self._weight_layout_in_out(self.o), 

1113 ) 

1114 return weight 

1115 

1116 def _reshape_bias( 

1117 self, bias: Optional[torch.Tensor], use_kv: bool = False 

1118 ) -> Optional[torch.Tensor]: 

1119 """Reshape 1D bias to [n_heads, d_head].""" 

1120 if bias is not None and bias.ndim == 1 and self.config is not None: 

1121 n_heads = self._get_n_heads(use_kv=use_kv) 

1122 return einops.rearrange(bias, "(n_heads d_head) -> n_heads d_head", n_heads=n_heads) 

1123 return bias 

1124 

1125 @property 

1126 def b_Q(self) -> Optional[torch.Tensor]: 

1127 """Get b_Q in 2D format [n_heads, d_head].""" 

1128 return self._reshape_bias(self.q.bias) 

1129 

1130 @property 

1131 def b_K(self) -> Optional[torch.Tensor]: 

1132 """Get b_K in 2D format [n_heads, d_head] (uses n_kv_heads for GQA).""" 

1133 return self._reshape_bias(self.k.bias, use_kv=True) 

1134 

1135 @property 

1136 def b_V(self) -> Optional[torch.Tensor]: 

1137 """Get b_V in 2D format [n_heads, d_head] (uses n_kv_heads for GQA).""" 

1138 return self._reshape_bias(self.v.bias, use_kv=True) 

1139 

1140 @property 

1141 def b_O(self) -> Optional[torch.Tensor]: 

1142 """Get b_O bias from linear bridge.""" 

1143 return self.o.bias