Coverage for transformer_lens/model_bridge/bridge_core.py: 86%

936 statements  

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

1"""Framework-agnostic bridge surface shared by TransformerBridge and RemoteBridge.""" 

2from __future__ import annotations 

3 

4import inspect 

5import re 

6import warnings 

7from contextlib import contextmanager 

8from functools import lru_cache, partial 

9from typing import ( 

10 Any, 

11 Callable, 

12 Dict, 

13 FrozenSet, 

14 Iterable, 

15 Iterator, 

16 List, 

17 Literal, 

18 Mapping, 

19 Optional, 

20 Tuple, 

21 Union, 

22 cast, 

23 overload, 

24) 

25 

26import torch 

27from torch.nn import functional as F 

28 

29from transformer_lens.ActivationCache import ActivationCache 

30from transformer_lens.hook_points import HookPoint, LensHandle 

31from transformer_lens.model_bridge.architecture_adapter import ArchitectureAdapter 

32from transformer_lens.model_bridge.driver_protocol import to_torch 

33from transformer_lens.model_bridge.exceptions import StopAtLayerException 

34from transformer_lens.model_bridge.generalized_components.base import alias_generation 

35from transformer_lens.utilities.aliases import resolve_alias 

36from transformer_lens.utilities.lm_utils import lm_cross_entropy_loss 

37from transformer_lens.utilities.slice import Slice, SliceInput 

38 

39# Aliased: the caching methods take a ``remove_batch_dim`` flag that would shadow it. 

40from transformer_lens.utilities.tensors import remove_batch_dim as drop_batch_dim 

41 

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

43 

44# Block-list container attributes a bridge may expose. 

45_BLOCK_LIST_ATTRS = ("blocks", "encoder_blocks", "decoder_blocks", "L_blocks", "H_blocks") 

46# Encoder blocks name self-attention ``attn``; decoder blocks name it ``self_attn`` 

47# (``cross_attn`` is a separate submodule, deliberately excluded from stacking). 

48_SELF_ATTENTION_NAMES = {"attn": ("attn", "self_attn")} 

49 

50 

51def _validate_execution_kwargs(kwargs: Mapping[str, Any], caller: str) -> None: 

52 """Reject helper-only arguments before they can disappear into a driver's kwargs.""" 

53 for name in kwargs: 

54 if name in ("fwd_hook", "bwd_hook"): 

55 correct = f"{name}s" 

56 hint = f"use run_with_hooks({correct}=...) or hooks({correct}=...)." 

57 elif name in ("fwd_hooks", "bwd_hooks"): 

58 hint = f"use run_with_hooks({name}=...) or hooks({name}=...)." 

59 elif name in ("names_filter", "incl_bwd", "pos_slice", "return_cache_object"): 

60 hint = f"use run_with_cache({name}=...) to scope caching." 

61 elif name in ("reset_hooks_end", "clear_contexts", "remove_batch_dim"): 

62 hint = f"use run_with_hooks({name}=...) or run_with_cache({name}=...)." 

63 else: 

64 continue 

65 raise TypeError(f"{caller}() got an unexpected keyword argument {name!r}; {hint}") 

66 

67 

68def _input_batch_size(*inputs: Any) -> Optional[int]: 

69 """The batch size of the first input that states it (a string, list of strings or tensor). 

70 

71 A 1-D tensor is one sequence. Returns None when no input says, so the caller can fall 

72 back to inferring it from what was cached. 

73 """ 

74 for value in inputs: 

75 if isinstance(value, str): 

76 return 1 

77 if isinstance(value, list) and value and all(isinstance(v, str) for v in value): 

78 return len(value) 

79 if isinstance(value, torch.Tensor) and value.ndim > 0: 

80 return 1 if value.ndim == 1 else int(value.shape[0]) 

81 return None 

82 

83 

84def build_alias_to_canonical_map(hook_dict: Any, prefix: str = "") -> dict: 

85 """Map alias hook names to their canonical names (where ``.name`` differs from the key).""" 

86 aliases: dict = {} 

87 for key, value in hook_dict.items(): 

88 full_key = f"{prefix}.{key}" if prefix else key 

89 if isinstance(value, dict): 89 ↛ 90line 89 didn't jump to line 90 because the condition on line 89 was never true

90 aliases.update(build_alias_to_canonical_map(value, full_key)) 

91 elif hasattr(value, "name"): 91 ↛ 87line 91 didn't jump to line 87 because the condition on line 91 was always true

92 if key != value.name: 

93 aliases[full_key] = value.name 

94 return aliases 

95 

96 

97class BridgeCore: 

98 """Framework-agnostic bridge surface: hooks, cache, run_with_*, driver wiring. 

99 

100 Holds state shared by every bridge (adapter, cfg, tokenizer, driver, hook 

101 registries). Subclasses add framework-specific state — ``TransformerBridge`` 

102 walks the wrapped ``nn.Module``; ``RemoteBridge`` builds components from 

103 adapter metadata. 

104 """ 

105 

106 hook_aliases: Dict[str, Union[str, List[str]]] = { 

107 # Prefer embed_ln.hook_out for post-LN models (Bloom, BERT) 

108 "hook_embed": ["embed_ln.hook_out", "embed.hook_out"], 

109 "hook_pos_embed": ["pos_embed.hook_out", "rotary_emb.hook_out"], 

110 "hook_unembed": "unembed.hook_out", 

111 } 

112 

113 def __init__( 

114 self, 

115 adapter: ArchitectureAdapter, 

116 tokenizer: Any, 

117 driver: Any, 

118 ) -> None: 

119 """Subclasses call this AFTER ``nn.Module.__init__`` (if applicable), 

120 then do framework-specific setup.""" 

121 self.adapter = adapter 

122 self.cfg = adapter.cfg 

123 self._tokenizer = None 

124 if tokenizer is not None: 

125 self.tokenizer = tokenizer # Use the property setter 

126 if self.cfg.d_vocab_out == -1: 

127 self.cfg.d_vocab_out = self.cfg.d_vocab 

128 self.compatibility_mode = False 

129 self._weights_processed = False 

130 self._hook_cache = None 

131 self._hook_registry: Dict[str, HookPoint] = {} 

132 self._hook_registry_initialized = False 

133 self._hook_alias_registry: Dict[str, Union[str, List[str]]] = {} 

134 self._block_alias_cache: Optional[Tuple[Tuple[int, int], Dict[str, str]]] = None 

135 self._property_alias_registry: Dict[str, str] = {} 

136 self.context_level = 0 

137 self._driver = driver 

138 if not hasattr(adapter, "component_mapping") or adapter.component_mapping is None: 138 ↛ 139line 138 didn't jump to line 139 because the condition on line 138 was never true

139 raise ValueError("Adapter must have a component_mapping attribute") 

140 

141 # ---- tokenizer property ---- 

142 

143 @property 

144 def tokenizer(self) -> Any: 

145 """The tokenizer used for encoding/decoding text.""" 

146 return self._tokenizer 

147 

148 @tokenizer.setter 

149 def tokenizer(self, value: Any) -> None: 

150 """Set tokenizer and re-run wiring (d_vocab, BOS/EOS detection, padding). 

151 

152 On initial assignment (during __init__), the boot path has already called 

153 configure_tokenizer, so we skip calling it again. However, we still infer 

154 d_vocab if it wasn't set from the model config (d_vocab == -1). 

155 

156 On reassignment, we re-run configure_tokenizer and update d_vocab to keep 

157 cfg in sync with the new tokenizer. 

158 """ 

159 is_reassignment = getattr(self, "_tokenizer", None) is not None 

160 cfg = getattr(self, "cfg", None) 

161 if value is not None and cfg is not None: 

162 if is_reassignment: 

163 from transformer_lens.model_bridge.sources._bridge_builder import ( 

164 configure_tokenizer, 

165 ) 

166 

167 value = configure_tokenizer(value, cfg) 

168 

169 # Infer d_vocab: on initial assignment only if not set (-1), 

170 # on reassignment always update to match new tokenizer. 

171 # Use getattr for cfg attributes since tests may use SimpleNamespace. 

172 d_vocab = getattr(cfg, "d_vocab", None) 

173 if d_vocab == -1 or is_reassignment: 

174 if hasattr(value, "get_vocab"): 174 ↛ 177line 174 didn't jump to line 177 because the condition on line 174 was always true

175 vocab = value.get_vocab() 

176 cfg.d_vocab = max(vocab.values()) + 1 

177 elif hasattr(value, "vocab"): 

178 cfg.d_vocab = max(value.vocab.values()) + 1 

179 else: 

180 cfg.d_vocab = getattr(value, "vocab_size", 50257) 

181 d_vocab_out = getattr(cfg, "d_vocab_out", None) 

182 if d_vocab_out == -1 or is_reassignment: 

183 cfg.d_vocab_out = getattr(cfg, "d_vocab", d_vocab_out) 

184 self._tokenizer = value 

185 

186 # ---- hook registry ---- 

187 

188 def _initialize_hook_registry(self) -> None: 

189 """Initialize the hook registry by scanning existing components.""" 

190 if self._hook_registry_initialized: 190 ↛ 191line 190 didn't jump to line 191 because the condition on line 190 was never true

191 return 

192 self._scan_existing_hooks(self, "") 

193 self._hook_registry_initialized = True 

194 

195 def _scan_existing_hooks(self, module: Any, prefix: str = "") -> None: 

196 """Walk components for HookPoint instances. Framework-specific.""" 

197 raise NotImplementedError( 

198 f"{type(self).__name__} must implement _scan_existing_hooks " 

199 "(walks the component tree to find HookPoint instances)." 

200 ) 

201 

202 def clear_hook_registry(self) -> None: 

203 """Clear the hook registry and force re-initialization.""" 

204 self._hook_registry.clear() 

205 self._hook_registry_initialized = False 

206 

207 @property 

208 def hook_dict(self) -> dict[str, HookPoint]: 

209 """All HookPoint objects, including aliases — TransformerLens-compatible.""" 

210 hooks = self._hook_registry.copy() 

211 self._add_aliases_to_hooks(hooks) 

212 return hooks 

213 

214 @property 

215 def mod_dict(self) -> Dict[str, Any]: 

216 """Module/hook name -> object, HookedRootModule-compatible. 

217 

218 Union of the named-module tree and the aliased hook view, so both 

219 canonical (``blocks.0.mlp.hook_out``) and HT-style 

220 (``blocks.0.hook_mlp_out``) names resolve to the same HookPoint. 

221 """ 

222 # BridgeCore is a mixin; concrete bridges (TransformerBridge/RemoteBridge) 

223 # are nn.Modules, so named_modules() is always present at runtime. 

224 mods: Dict[str, Any] = { 

225 name: module 

226 for name, module in cast(torch.nn.Module, self).named_modules() 

227 if name != "" 

228 } 

229 mods.update(self.hook_dict) 

230 return mods 

231 

232 # ---- alias registry ---- 

233 

234 def _register_aliases(self) -> None: 

235 """Register bridge-level aliases (hook_embed, hook_pos_embed, etc.) by 

236 resolving each alias target path and installing the target HookPoint 

237 as a direct attribute under the alias name.""" 

238 if self.hook_aliases: 238 ↛ exitline 238 didn't return from function '_register_aliases' because the condition on line 238 was always true

239 self._hook_alias_registry.update(self.hook_aliases) 

240 for alias_name, target_path in self.hook_aliases.items(): 

241 try: 

242 if isinstance(target_path, list): 

243 for single_target in target_path: 

244 try: 

245 target_obj = self 

246 for part in single_target.split("."): 

247 target_obj = getattr(target_obj, part) 

248 object.__setattr__(self, alias_name, target_obj) 

249 break 

250 except AttributeError: 

251 continue 

252 else: 

253 target_obj = self 

254 for part in target_path.split("."): 

255 target_obj = getattr(target_obj, part) 

256 object.__setattr__(self, alias_name, target_obj) 

257 except AttributeError: 

258 pass 

259 

260 def _collect_component_aliases( 

261 self, component_mapping: Any, prefix: str = "", _ancestors: FrozenSet[int] = frozenset() 

262 ) -> dict: 

263 """Recursively collect aliases from the architecture's component templates. 

264 

265 ``_ancestors`` is path-scoped, not globally-visited: a cycle is cut 

266 (else RecursionError at boot) while a diamond-shared component still 

267 contributes aliases under both names. 

268 """ 

269 aliases: dict = {} 

270 if id(component_mapping) in _ancestors: 

271 return aliases 

272 _ancestors = _ancestors | {id(component_mapping)} 

273 if isinstance(component_mapping, dict): 

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

275 sub_prefix = f"{prefix}.{name}" if prefix else name 

276 aliases.update(self._collect_component_aliases(component, sub_prefix, _ancestors)) 

277 else: 

278 if hasattr(component_mapping, "hook_aliases") and component_mapping.hook_aliases: 

279 for alias_name, target in component_mapping.hook_aliases.items(): 

280 full_alias = f"{prefix}.{alias_name}" if prefix else alias_name 

281 if isinstance(target, list): 

282 # Fallback chain: candidates in declared priority order. 

283 full_target: Any = tuple(f"{prefix}.{t}" if prefix else t for t in target) 

284 else: 

285 full_target = f"{prefix}.{target}" if prefix else target 

286 aliases[full_alias] = full_target 

287 if hasattr(component_mapping, "submodules") and component_mapping.submodules: 

288 for sub_name, sub_component in component_mapping.submodules.items(): 

289 sub_prefix = f"{prefix}.{sub_name}" if prefix else sub_name 

290 aliases.update( 

291 self._collect_component_aliases(sub_component, sub_prefix, _ancestors) 

292 ) 

293 return aliases 

294 

295 @staticmethod 

296 @lru_cache(maxsize=128) 

297 def _compute_hook_aliases_cached( 

298 hook_names_tuple: Tuple[str, ...], 

299 component_aliases_tuple: Tuple[Tuple[str, Union[str, Tuple[str, ...]]], ...], 

300 ) -> Tuple[Tuple[str, str], ...]: 

301 """Cached computation of hook aliases.""" 

302 aliases: dict = {} 

303 # For list-valued (fallback-chain) targets, remember which candidate 

304 # resolved each alias so an earlier (higher-priority) candidate wins. 

305 alias_priority: dict = {} 

306 component_aliases = dict(component_aliases_tuple) 

307 for hook_name in hook_names_tuple: 

308 for alias_pattern, target_patterns in component_aliases.items(): 

309 candidates = ( 

310 target_patterns if isinstance(target_patterns, tuple) else (target_patterns,) 

311 ) 

312 for priority, target_pattern in enumerate(candidates): 

313 if "blocks." in target_pattern and "blocks." in hook_name: 

314 block_match = _BLOCK_PATTERN.search(hook_name) 

315 if not block_match: 315 ↛ 316line 315 didn't jump to line 316 because the condition on line 315 was never true

316 continue 

317 block_num = block_match.group(1) 

318 dynamic_alias_pattern = alias_pattern.replace( 

319 "blocks.", f"blocks.{block_num}." 

320 ) 

321 dynamic_target_pattern = target_pattern.replace( 

322 "blocks.", f"blocks.{block_num}." 

323 ) 

324 if hook_name.endswith(dynamic_target_pattern): 

325 target_len = len(dynamic_target_pattern) 

326 alias_name = hook_name[:-target_len] + dynamic_alias_pattern 

327 if alias_priority.get(alias_name, len(candidates)) > priority: 

328 aliases[alias_name] = hook_name 

329 alias_priority[alias_name] = priority 

330 elif hook_name.endswith(target_pattern): 

331 target_len = len(target_pattern) 

332 alias_name = hook_name[:-target_len] + alias_pattern 

333 if alias_priority.get(alias_name, len(candidates)) > priority: 333 ↛ 312line 333 didn't jump to line 312 because the condition on line 333 was always true

334 aliases[alias_name] = hook_name 

335 alias_priority[alias_name] = priority 

336 return tuple(aliases.items()) 

337 

338 def _collect_hook_aliases_from_registry(self) -> dict: 

339 """Collect aliases based on existing hooks in the registry.""" 

340 if hasattr(self.adapter, "component_mapping"): 

341 component_aliases = self._collect_component_aliases(self.adapter.component_mapping) 

342 hook_names_tuple = tuple(sorted(self._hook_registry.keys())) 

343 component_aliases_tuple = tuple(sorted(component_aliases.items())) 

344 aliases_tuple = self._compute_hook_aliases_cached( 

345 hook_names_tuple, component_aliases_tuple 

346 ) 

347 aliases = dict(aliases_tuple) 

348 aliases.update(self._collect_block_instance_aliases()) 

349 return aliases 

350 return {} 

351 

352 def _collect_block_instance_aliases(self) -> Dict[str, str]: 

353 """Collect per-block-instance aliases, overriding template-derived ones. 

354 

355 Templates cannot see per-layer rebinds (OlmoHybrid, MoE dense/sparse). 

356 Memoized on (registry size, alias generation): size alone misses a 

357 dense<->sparse rebind, which changes targets without changing size. 

358 """ 

359 cache_key = (len(self._hook_registry), alias_generation()) 

360 cached = self._block_alias_cache 

361 if cached is not None and cached[0] == cache_key: 

362 return cached[1] 

363 aliases: Dict[str, str] = {} 

364 unresolved: List[str] = [] 

365 for bl_name in _BLOCK_LIST_ATTRS: 

366 block_list = getattr(self, bl_name, None) 

367 if block_list is None: 

368 continue 

369 for i, block in enumerate(block_list): 

370 # A block with no registered hooks means the registry hasn't 

371 # scanned it yet — unresolved aliases there are timing, not drops. 

372 block_prefix = f"{bl_name}.{i}." 

373 if f"{block_prefix}hook_in" not in self._hook_registry: 

374 continue 

375 # Walk the block and its submodule tree: components rebind 

376 # aliases per layer at bind time either at block level 

377 # (OlmoHybrid) or one level down (MoEBridge's dense/sparse 

378 # dispatch). id()-seen guards against shared/cyclic submodule 

379 # references, which would otherwise hang boot. 

380 # (prefix, component, ids-on-this-path): path-scoped rather than 

381 # globally-visited so a cycle is cut while a component shared 

382 # under two names still contributes aliases at both. 

383 stack: List[Tuple[str, Any, FrozenSet[int]]] = [("", block, frozenset())] 

384 while stack: 

385 sub_prefix, component, ancestors = stack.pop() 

386 if id(component) in ancestors: 

387 continue 

388 ancestors = ancestors | {id(component)} 

389 component_aliases = getattr(component, "hook_aliases", None) 

390 if component_aliases: 

391 for alias_name, target in component_aliases.items(): 

392 targets = target if isinstance(target, list) else [target] 

393 for single_target in targets: 

394 full_target = f"{block_prefix}{sub_prefix}{single_target}" 

395 if full_target in self._hook_registry: 

396 aliases[f"{block_prefix}{sub_prefix}{alias_name}"] = full_target 

397 break 

398 else: 

399 unresolved.append(f"{block_prefix}{sub_prefix}{alias_name}") 

400 for nested_name, nested in ( 

401 getattr(component, "submodules", None) or {} 

402 ).items(): 

403 stack.append((f"{sub_prefix}{nested_name}.", nested, ancestors)) 

404 if unresolved: 

405 # Surface drops instead of silently swallowing, mirroring 

406 # GeneralizedComponent._register_aliases. 

407 warnings.warn( 

408 f"{len(unresolved)} block hook alias(es) did not resolve to a " 

409 f"registered hook (e.g. '{unresolved[0]}'). Any such alias falls " 

410 "back to the architecture template's mapping, which for a " 

411 "per-layer rebind is the wrong tensor for this layer.", 

412 stacklevel=2, 

413 ) 

414 self._block_alias_cache = (cache_key, aliases) 

415 return aliases 

416 

417 def _add_aliases_to_hooks(self, hooks: Dict[str, HookPoint]) -> None: 

418 """Add aliases to hooks in place. Registry-first so RemoteBridge works.""" 

419 component_aliases = self._collect_hook_aliases_from_registry() 

420 all_aliases = {**self.hook_aliases, **component_aliases} 

421 if not all_aliases: 421 ↛ 422line 421 didn't jump to line 422 because the condition on line 421 was never true

422 return 

423 for alias_name, target in all_aliases.items(): 

424 targets = target if isinstance(target, list) else [target] 

425 for t in targets: 

426 hp = self._hook_registry.get(t) 

427 if hp is not None: 

428 hooks[alias_name] = hp 

429 break 

430 # Fall back to attribute walk for TransformerBridge nested paths 

431 # not directly keyed in the registry. 

432 try: 

433 target_hook = resolve_alias(self, alias_name, {alias_name: t}) 

434 if target_hook is not None: 434 ↛ 425line 434 didn't jump to line 425 because the condition on line 434 was always true

435 hooks[alias_name] = target_hook 

436 break 

437 except AttributeError: 

438 continue 

439 

440 # ---- captures from driver ---- 

441 

442 def _replay_captures(self, captured: Mapping[str, Any]) -> None: 

443 """Fire driver-delivered captures through the registry. Unknown names dropped silently.""" 

444 for hook_name, activation in captured.items(): 

445 hp = self._hook_registry.get(hook_name) 

446 if hp is None: 

447 continue 

448 hp(to_torch(activation)) 

449 

450 # ---- driver dispatch (subclasses concrete-override) ---- 

451 

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

453 """Subclasses implement how the driver gets called.""" 

454 raise NotImplementedError(f"{type(self).__name__} must implement forward()") 

455 

456 def to_tokens(self, *args: Any, **kwargs: Any) -> Any: 

457 """Subclasses implement against their tokenizer surface.""" 

458 raise NotImplementedError(f"{type(self).__name__} must implement to_tokens()") 

459 

460 def close(self) -> None: 

461 """Release driver-managed resources. Idempotent — safe to call multiple times.""" 

462 self._driver.close() 

463 

464 def _input_device(self) -> Any: 

465 """Driver's expected device for inputs; None for remote / meta / dispatched drivers.""" 

466 if not self._driver.supports("parameters"): 

467 return None 

468 params = getattr(self._driver, "parameters", None) 

469 if not callable(params): 469 ↛ 470line 469 didn't jump to line 470 because the condition on line 469 was never true

470 return None 

471 try: 

472 device = next(params()).device 

473 except (StopIteration, NotImplementedError, RuntimeError): 

474 return None 

475 # Meta device → inputs would silently become meta tensors with no data. 

476 if device.type == "meta": 

477 return None 

478 return device 

479 

480 def loss_fn( 

481 self, 

482 logits: torch.Tensor, 

483 tokens: torch.Tensor, 

484 attention_mask: Optional[torch.Tensor] = None, 

485 per_token: bool = False, 

486 ) -> torch.Tensor: 

487 """Cross-entropy loss matching HookedTransformer's formula (log_softmax + gather).""" 

488 if tokens.device != logits.device: 488 ↛ 489line 488 didn't jump to line 489 because the condition on line 488 was never true

489 tokens = tokens.to(logits.device) 

490 if attention_mask is not None: 

491 if attention_mask.device != logits.device: 491 ↛ 492line 491 didn't jump to line 492 because the condition on line 491 was never true

492 attention_mask = attention_mask.to(logits.device) 

493 attention_mask = self._prepare_loss_attention_mask(attention_mask, tokens) 

494 return lm_cross_entropy_loss(logits, tokens, attention_mask, per_token) 

495 

496 def _causal_labels_loss( 

497 self, 

498 logits: torch.Tensor, 

499 labels: torch.Tensor, 

500 attention_mask: Optional[torch.Tensor] = None, 

501 per_token: bool = False, 

502 ) -> torch.Tensor: 

503 """Compute shifted causal loss against explicit labels, ignoring ``-100``.""" 

504 if labels.device != logits.device: 504 ↛ 505line 504 didn't jump to line 505 because the condition on line 504 was never true

505 labels = labels.to(logits.device) 

506 if labels.shape != logits.shape[:-1]: 506 ↛ 507line 506 didn't jump to line 507 because the condition on line 506 was never true

507 raise ValueError( 

508 "causal labels must match the logits batch and position dimensions, " 

509 f"got labels {tuple(labels.shape)} and logits {tuple(logits.shape)}" 

510 ) 

511 

512 losses = F.cross_entropy( 

513 logits[:, :-1].flatten(0, 1), 

514 labels[:, 1:].flatten(), 

515 reduction="none", 

516 ignore_index=-100, 

517 ).view_as(labels[:, 1:]) 

518 valid_targets = labels[:, 1:] != -100 

519 if attention_mask is not None: 

520 if attention_mask.device != logits.device: 520 ↛ 521line 520 didn't jump to line 521 because the condition on line 520 was never true

521 attention_mask = attention_mask.to(logits.device) 

522 token_mask = self._prepare_loss_attention_mask(attention_mask, labels) 

523 valid_targets &= token_mask[:, :-1] & token_mask[:, 1:] 

524 losses = losses.masked_fill(~valid_targets, 0.0) 

525 return losses if per_token else losses.sum() / valid_targets.sum() 

526 

527 def _prepare_loss_attention_mask( 

528 self, attention_mask: torch.Tensor, tokens: torch.Tensor 

529 ) -> torch.Tensor: 

530 """Reduce a forward mask using the adapter's 4D boolean polarity.""" 

531 batch, pos = tokens.shape 

532 if attention_mask.ndim not in (2, 4): 532 ↛ 533line 532 didn't jump to line 533 because the condition on line 532 was never true

533 raise ValueError( 

534 "attention_mask must be 2D [batch, key_pos] or 4D " 

535 f"[batch, *, query_pos, key_pos], got shape {tuple(attention_mask.shape)}" 

536 ) 

537 if attention_mask.shape[0] != batch: 537 ↛ 538line 537 didn't jump to line 538 because the condition on line 537 was never true

538 raise ValueError( 

539 "attention_mask batch dimension must match tokens, " 

540 f"got {attention_mask.shape[0]} and {batch}" 

541 ) 

542 

543 if attention_mask.ndim == 2: 

544 if attention_mask.shape[1] < pos: 544 ↛ 545line 544 didn't jump to line 545 because the condition on line 544 was never true

545 raise ValueError( 

546 "attention_mask must cover every scored token, " 

547 f"got length {attention_mask.shape[1]} for {pos} tokens" 

548 ) 

549 return attention_mask[:, -pos:].bool() 

550 

551 query_pos, key_pos = attention_mask.shape[-2:] 

552 if key_pos < pos: 552 ↛ 553line 552 didn't jump to line 553 because the condition on line 552 was never true

553 raise ValueError( 

554 "attention_mask must cover every scored token, " 

555 f"got key length {key_pos} for {pos} tokens" 

556 ) 

557 

558 if attention_mask.dtype is torch.bool: 

559 blocked = ~attention_mask if self.adapter.bool_4d_mask_is_keep else attention_mask 

560 else: 

561 blocked = attention_mask < -1.0 

562 if query_pos == 1: 

563 # Broadcast key-only masks use one query row for the full sequence. 

564 keep = ~blocked[..., 0, -pos:] 

565 else: 

566 if query_pos < pos: 566 ↛ 567line 566 didn't jump to line 567 because the condition on line 566 was never true

567 raise ValueError( 

568 "attention_mask must contain a query row for every scored token, " 

569 f"got {query_pos} rows for {pos} tokens" 

570 ) 

571 # The aligned diagonal excludes causal masking while retaining padding. 

572 diagonal = torch.diagonal( 

573 blocked, 

574 offset=key_pos - query_pos, 

575 dim1=-2, 

576 dim2=-1, 

577 ) 

578 if diagonal.shape[-1] < pos: 578 ↛ 579line 578 didn't jump to line 579 because the condition on line 578 was never true

579 raise ValueError( 

580 "attention_mask diagonal must cover every scored token, " 

581 f"got length {diagonal.shape[-1]} for {pos} tokens" 

582 ) 

583 keep = ~diagonal[..., -pos:] 

584 

585 # A token is padding only when every broadcast/head mask blocks its key. 

586 return keep.reshape(batch, -1, pos).any(dim=1) 

587 

588 def _finalize_return( 

589 self, 

590 return_type: Optional[str], 

591 logits: Optional[torch.Tensor], 

592 input_ids: Optional[torch.Tensor], 

593 *, 

594 attention_mask: Optional[torch.Tensor] = None, 

595 labels: Optional[torch.Tensor] = None, 

596 is_audio_model: bool = False, 

597 is_visual_model: bool = False, 

598 inputs_embeds_was_used: bool = False, 

599 loss_per_token: bool = False, 

600 ) -> Any: 

601 """Post-process driver output into the user's requested return_type.""" 

602 if return_type == "logits": 

603 return logits 

604 if return_type is None: 

605 return None 

606 self._check_loss_supported(return_type) 

607 if return_type == "loss": 

608 if is_audio_model: 608 ↛ 609line 608 didn't jump to line 609 because the condition on line 608 was never true

609 raise ValueError( 

610 "Audio models do not support return_type='loss'. " 

611 "CTC loss requires aligned frame-level labels." 

612 ) 

613 if is_visual_model: 613 ↛ 614line 613 didn't jump to line 614 because the condition on line 613 was never true

614 raise ValueError( 

615 "Vision classification models do not support return_type='loss' " 

616 "via this path (no next-token LM target exists for image " 

617 "classification). Compute cross-entropy against `labels` " 

618 "yourself from the returned logits, or use hf_generate()-style " 

619 "direct access to self.original_model for HF's own loss." 

620 ) 

621 if inputs_embeds_was_used and labels is None: 621 ↛ 622line 621 didn't jump to line 622 because the condition on line 621 was never true

622 raise ValueError( 

623 "Cannot compute loss with inputs_embeds — token IDs required for labels." 

624 ) 

625 assert isinstance(logits, torch.Tensor), f"Expected logits tensor, got {type(logits)}" 

626 if labels is not None: 

627 return self._causal_labels_loss( 

628 logits, 

629 labels, 

630 attention_mask=attention_mask, 

631 per_token=loss_per_token, 

632 ) 

633 assert input_ids is not None, "input_ids required for return_type='loss'" 

634 return self.loss_fn( 

635 logits, 

636 input_ids, 

637 attention_mask=attention_mask, 

638 per_token=loss_per_token, 

639 ) 

640 if return_type == "both": 

641 if is_audio_model: 641 ↛ 642line 641 didn't jump to line 642 because the condition on line 641 was never true

642 raise ValueError( 

643 "Audio models do not support return_type='both'. " 

644 "CTC loss requires aligned frame-level labels." 

645 ) 

646 if is_visual_model: 646 ↛ 647line 646 didn't jump to line 647 because the condition on line 646 was never true

647 raise ValueError( 

648 "Vision classification models do not support return_type='both' " 

649 "via this path (no next-token LM target exists for image " 

650 "classification). Compute cross-entropy against `labels` " 

651 "yourself from the returned logits." 

652 ) 

653 if inputs_embeds_was_used and labels is None: 653 ↛ 654line 653 didn't jump to line 654 because the condition on line 653 was never true

654 raise ValueError( 

655 "Cannot compute loss with inputs_embeds — token IDs required for labels." 

656 ) 

657 assert isinstance(logits, torch.Tensor), f"Expected logits tensor, got {type(logits)}" 

658 if labels is not None: 

659 loss = self._causal_labels_loss( 

660 logits, 

661 labels, 

662 attention_mask=attention_mask, 

663 per_token=loss_per_token, 

664 ) 

665 else: 

666 assert input_ids is not None, "input_ids required for return_type='both'" 

667 loss = self.loss_fn( 

668 logits, 

669 input_ids, 

670 attention_mask=attention_mask, 

671 per_token=loss_per_token, 

672 ) 

673 return (logits, loss) 

674 if return_type == "predictions": 

675 assert self.tokenizer is not None, "Tokenizer required for return_type='predictions'" 

676 assert isinstance(logits, torch.Tensor), f"Expected logits tensor, got {type(logits)}" 

677 if logits.shape[-1] == 2: 677 ↛ 687line 677 didn't jump to line 687 because the condition on line 677 was always true

678 # Next Sentence Prediction — 2-class output 

679 logprobs = logits.log_softmax(dim=-1) 

680 predictions = [ 

681 "The sentences are sequential", 

682 "The sentences are NOT sequential", 

683 ] 

684 return predictions[int(logprobs.argmax(dim=-1).item())] 

685 else: 

686 # Masked Language Modeling — decode [MASK] tokens 

687 assert input_ids is not None, "input_ids required for MLM predictions" 

688 logprobs = logits[input_ids == self.tokenizer.mask_token_id].log_softmax(dim=-1) 

689 preds = self.tokenizer.decode(logprobs.argmax(dim=-1)) 

690 if " " in preds: 

691 parts = preds.split(" ") 

692 return [f"Prediction {i}: {p}" for i, p in enumerate(parts)] 

693 return preds 

694 raise ValueError(f"Invalid return_type: {return_type}") 

695 

696 def _check_loss_supported(self, return_type: Optional[str]) -> None: 

697 """Loss needs full-sequence logits; final-position-only drivers would NaN.""" 

698 if return_type in ("loss", "both") and not getattr( 

699 self._driver, "provides_sequence_logits", True 

700 ): 

701 raise NotImplementedError( 

702 f"return_type={return_type!r} is unsupported on this driver: it " 

703 "provides next-token logits for the final position only, so loss " 

704 "over earlier positions is undefined. Use return_type='logits' " 

705 "and read logits[..., -1, :]." 

706 ) 

707 

708 # ---- hook lookup / mutation ---- 

709 

710 @staticmethod 

711 def _is_embedding_stage_hook(name: str) -> bool: 

712 """Hooks belonging to the pre-block token/positional embedding stage. 

713 

714 Excluded from ``start_at_layer`` output: the caller's residual already 

715 carries the embedding, so the embedding stage is logically skipped even 

716 though HF still computes (and discards) it. ``unembed``/``hook_unembed`` 

717 are the output stage and deliberately not matched. 

718 """ 

719 return name in ("hook_embed", "hook_pos_embed", "hook_tokens") or name.startswith( 

720 ("embed.", "pos_embed.") 

721 ) 

722 

723 def _check_hook_fireable(self, *names: str) -> None: 

724 """Fail loud when the driver declares it can't fire a requested hook — 

725 attaching anyway would yield a silently-unhooked forward / empty cache.""" 

726 non_fireable: frozenset = getattr(self._driver, "non_fireable_hook_points", frozenset()) 

727 for name in names: 

728 if name in non_fireable: 

729 raise NotImplementedError( 

730 f"this backend cannot fire {name!r}; use boot_transformers() " 

731 "for full hook coverage." 

732 ) 

733 

734 def _resolve_hook_point( 

735 self, name: str, aliases: Dict[str, str], hook_dict: Dict[str, HookPoint] 

736 ) -> Tuple[str, HookPoint]: 

737 """Resolve an (aliased) string hook name to its HookPoint, enforcing 

738 fireability. A name that resolves to nothing raises — a typo'd name must 

739 not run unhooked.""" 

740 canonical = aliases.get(name, name) 

741 self._check_hook_fireable(name, canonical) 

742 hook_point = hook_dict.get(canonical) 

743 if hook_point is None: 

744 raise KeyError(f"Hook name {name!r} does not exist on this model.") 

745 return canonical, hook_point 

746 

747 def get_hook_point(self, hook_name: str) -> Optional[HookPoint]: 

748 """Get a hook point by name from the bridge's hook system.""" 

749 if hook_name in self._hook_registry: 749 ↛ 751line 749 didn't jump to line 751 because the condition on line 749 was always true

750 return self._hook_registry[hook_name] 

751 try: 

752 parts = hook_name.split(".") 

753 current: Any = self 

754 for part in parts: 

755 current = getattr(current, part) 

756 if isinstance(current, HookPoint): 

757 return current 

758 except AttributeError: 

759 pass 

760 return None 

761 

762 def check_hooks_to_add( 

763 self, 

764 hook_point: HookPoint, 

765 hook_point_name: str, 

766 hook: Callable, 

767 dir: Literal["fwd", "bwd"] = "fwd", 

768 is_permanent: bool = False, 

769 prepend: bool = False, 

770 ) -> None: 

771 """Validate a hook before it is added; override to add checks. 

772 

773 Raises for a gated-off hook point — a targeted attach there would 

774 silently never fire. Every explicit-name attach path routes through 

775 here; filter sweeps pre-skip gated matches (with a warning) before 

776 reaching it, since a filter was not necessarily targeting them. 

777 

778 Gating keys on the POINT's own canonical name, not the requested 

779 spelling: on adapters with ``hook_alias_overrides`` a gated HT name 

780 (e.g. ``blocks.0.hook_mlp_in`` on BERT) resolves to an always-firing 

781 point, and refusing it would reject a hook that works. 

782 Driver-fireability is enforced separately in ``_check_hook_fireable``. 

783 """ 

784 reason = self._gated_hook_reason(hook_point.name or hook_point_name) 

785 if reason is not None: 

786 raise ValueError( 

787 f"Cannot add hook {hook_point_name} because {reason} is False. " 

788 f"Call set_{reason}(True) first." 

789 ) 

790 

791 def _add_fn_to_hook_point( 

792 self, 

793 hook_point: HookPoint, 

794 name: str, 

795 hook_fn: Callable, 

796 dir: Literal["fwd", "bwd"], 

797 is_permanent: bool, 

798 level: Optional[int] = None, 

799 prepend: bool = False, 

800 ) -> None: 

801 """Run the extension-point check, then attach the hook function.""" 

802 self.check_hooks_to_add( 

803 hook_point, name, hook_fn, dir=dir, is_permanent=is_permanent, prepend=prepend 

804 ) 

805 hook_point.add_hook( 

806 hook_fn, dir=dir, is_permanent=is_permanent, level=level, prepend=prepend 

807 ) 

808 

809 def _gated_hook_reason(self, hook_point_name: str) -> Optional[str]: 

810 """Return the disabled setter name if hook_point_name is gated off, else None.""" 

811 if hook_point_name.endswith("attn.hook_result") and not self.cfg.use_attn_result: 

812 return "use_attn_result" 

813 if ( 

814 hook_point_name.endswith(("hook_q_input", "hook_k_input", "hook_v_input")) 

815 and not self.cfg.use_split_qkv_input 

816 ): 

817 return "use_split_qkv_input" 

818 if hook_point_name.endswith("mlp_in") and not self.cfg.use_hook_mlp_in: 

819 return "use_hook_mlp_in" 

820 if hook_point_name.endswith("attn_in") and not self.cfg.use_attn_in: 

821 return "use_attn_in" 

822 return None 

823 

824 def _warn_gated_skipped(self, api: str, names: List[str], stacklevel: int = 3) -> None: 

825 """One warning per sweep for filter-matched gated-off names.""" 

826 if names: 

827 warnings.warn( 

828 f"{api}: skipped {len(names)} gated-off hook name(s) " 

829 f"that would never fire: {names}. Call the relevant " 

830 "set_use_*(True) setter first to enable them.", 

831 stacklevel=stacklevel, 

832 ) 

833 

834 def add_hook( 

835 self, 

836 name: Union[str, Callable[[str], bool]], 

837 hook_fn: Any, 

838 dir: Literal["fwd", "bwd"] = "fwd", 

839 is_permanent: bool = False, 

840 level: Optional[int] = None, 

841 prepend: bool = False, 

842 ) -> None: 

843 """Add a hook to a specific component or to all components matching a filter. 

844 

845 Args: 

846 name: Either a string hook point name (e.g. "blocks.0.attn.hook_q") 

847 or a callable filter ``(str) -> bool`` that is applied to every 

848 hook point name; the hook is added to each point where the filter 

849 returns True. 

850 hook_fn: The hook function ``(activation, hook) -> activation | None``. 

851 dir: Hook direction, ``"fwd"`` or ``"bwd"``. 

852 is_permanent: If True the hook survives ``reset_hooks()`` calls. 

853 level: Context level to tag the hook with; ``reset_hooks(level=...)`` removes only 

854 the hooks tagged with that level. 

855 prepend: If True the hook runs before those already on the hook point. 

856 """ 

857 if callable(name) and not isinstance(name, str): 

858 hook_dict = self.hook_dict 

859 seen_hooks: set = set() 

860 gated_names_skipped: List[str] = [] 

861 for hook_name, hook_point in hook_dict.items(): 

862 if name(hook_name): 

863 hook_id = id(hook_point) 

864 if hook_id in seen_hooks: 864 ↛ 865line 864 didn't jump to line 865 because the condition on line 864 was never true

865 continue 

866 seen_hooks.add(hook_id) 

867 # A filter is a sweep, not a targeted request, so a gated-off 

868 # match is skipped rather than raised on — but silently 

869 # attaching here would leave a dead hook that never fires, 

870 # which is the failure this warns about. 

871 if self._gated_hook_reason(hook_point.name or hook_name) is not None: 

872 gated_names_skipped.append(hook_name) 

873 continue 

874 self._add_fn_to_hook_point( 

875 hook_point, hook_name, hook_fn, dir, is_permanent, level, prepend 

876 ) 

877 self._warn_gated_skipped("add_hook", gated_names_skipped) 

878 return 

879 

880 # Explicit-name attaches raise on gated-off points inside 

881 # check_hooks_to_add (via _add_fn_to_hook_point) — every path below 

882 # funnels through it. 

883 # Fast path: canonical registry names skip the alias-map build (hook_dict + 

884 # map construction cost ~ms on large models; add_hook is often called per layer). 

885 registry_hp = self._hook_registry.get(name) 

886 if registry_hp is not None: 

887 self._check_hook_fireable(name) 

888 self._add_fn_to_hook_point( 

889 registry_hp, name, hook_fn, dir, is_permanent, level, prepend 

890 ) 

891 return 

892 # Same alias resolution run_with_hooks uses, so HT-style names work here too. 

893 canonical = build_alias_to_canonical_map(self.hook_dict).get(name, name) 

894 if canonical != name: 

895 self._check_hook_fireable(name, canonical) 

896 else: 

897 self._check_hook_fireable(name) 

898 registry_hp = self._hook_registry.get(canonical) 

899 if registry_hp is not None: 899 ↛ 905line 899 didn't jump to line 905 because the condition on line 899 was always true

900 self._add_fn_to_hook_point( 

901 registry_hp, canonical, hook_fn, dir, is_permanent, level, prepend 

902 ) 

903 return 

904 

905 component: Any = self 

906 parts = name.split(".") 

907 for part in parts[:-1]: 

908 if hasattr(component, part): 

909 component = getattr(component, part) 

910 else: 

911 raise AttributeError(f"Component path '{'.'.join(parts[:-1])}' not found") 

912 hook_name = parts[-1] 

913 if hasattr(component, hook_name): 

914 hook_point = getattr(component, hook_name) 

915 if isinstance(hook_point, HookPoint): 

916 self._add_fn_to_hook_point( 

917 hook_point, name, hook_fn, dir, is_permanent, level, prepend 

918 ) 

919 else: 

920 raise AttributeError( 

921 f"'{hook_name}' is not a hook point. Found object of type: {type(hook_point)} with value: {hook_point}" 

922 ) 

923 else: 

924 raise AttributeError(f"Hook point '{hook_name}' not found on component") 

925 

926 def add_perma_hook( 

927 self, 

928 name: Union[str, Callable[[str], bool]], 

929 hook_fn: Callable, 

930 dir: Literal["fwd", "bwd"] = "fwd", 

931 ) -> None: 

932 """Add a permanent hook that survives ``reset_hooks()`` calls. 

933 

934 Convenience wrapper for ``add_hook(..., is_permanent=True)``. To remove, 

935 call ``reset_hooks(including_permanent=True)`` or remove from the 

936 underlying ``HookPoint`` directly. 

937 """ 

938 self.add_hook(name, hook_fn, dir=dir, is_permanent=True) 

939 

940 def hook_points(self) -> Iterable[HookPoint]: 

941 """All :class:`HookPoint` instances (registry is canonical and complete).""" 

942 return self._hook_registry.values() 

943 

944 def clear_contexts(self) -> None: 

945 """Clear the stored ``ctx`` on every hook point.""" 

946 for hp in self._hook_registry.values(): 

947 hp.clear_context() 

948 

949 def remove_all_hook_fns( 

950 self, 

951 direction: Literal["fwd", "bwd", "both"] = "both", 

952 including_permanent: bool = False, 

953 level: Optional[int] = None, 

954 ) -> None: 

955 """Remove hook functions from every hook point.""" 

956 for hp in self._hook_registry.values(): 

957 hp.remove_hooks(direction, including_permanent=including_permanent, level=level) 

958 

959 def reset_hooks( 

960 self, 

961 clear_contexts: bool = True, 

962 direction: Literal["fwd", "bwd", "both"] = "both", 

963 including_permanent: bool = False, 

964 level: Optional[int] = None, 

965 ) -> None: 

966 """Remove hooks from every hook point; mirrors ``HookedRootModule.reset_hooks``. 

967 

968 The hook registry is canonical and complete (every component's HookPoint 

969 is registered), so a single pass covers the whole model. 

970 

971 Args: 

972 clear_contexts: Also clear each hook point's stored ``ctx``. 

973 direction: Which direction(s) to remove — ``"fwd"``, ``"bwd"``, or ``"both"``. 

974 including_permanent: If True, also remove hooks added via ``add_perma_hook``. 

975 level: If set, only remove hooks registered at this context level. 

976 """ 

977 if clear_contexts: 

978 self.clear_contexts() 

979 self.remove_all_hook_fns(direction, including_permanent=including_permanent, level=level) 

980 

981 @staticmethod 

982 def _normalize_names_filter( 

983 names_filter: Optional[Union[str, List[str], Callable[[str], bool]]], 

984 ) -> Callable[[str], bool]: 

985 """Turn None / str / list / callable into a name predicate.""" 

986 if names_filter is None: 

987 return lambda name: True 

988 if isinstance(names_filter, str): 

989 return lambda name: name == names_filter 

990 if isinstance(names_filter, list): 

991 return lambda name: name in names_filter 

992 if callable(names_filter): 992 ↛ 994line 992 didn't jump to line 994 because the condition on line 992 was always true

993 return names_filter 

994 raise ValueError("names_filter must be None, a string, a list of strings, or a callable") 

995 

996 @staticmethod 

997 def _pos_slice_dim(name: str, hook_point: Any = None) -> int: 

998 """Position axis of a hook's activation in its batched layout. 

999 

1000 Position is dim 1 for most bridge activations (resid ``[b, p, d]``, per-head 

1001 ``[b, p, h, d]``, token ids ``[b, p]``) and -2 for attention patterns/scores 

1002 (``[b, h, q_pos, k_pos]``). Hooks fired on another layout, such as a 

1003 post-reshape qk-norm (``[b, h, p, d]``) or a Mamba conv input 

1004 (``[b, channels, p]``), declare their axis via ``HookPoint.pos_dim``. 

1005 """ 

1006 pos_dim = getattr(hook_point, "pos_dim", None) 

1007 if pos_dim is not None: 

1008 return pos_dim 

1009 return -2 if name.endswith(("hook_pattern", "hook_attn_scores")) else 1 

1010 

1011 def get_caching_hooks( 

1012 self, 

1013 names_filter: Optional[Union[str, List[str], Callable[[str], bool]]] = None, 

1014 incl_bwd: bool = False, 

1015 device: Any = None, 

1016 remove_batch_dim: bool = False, 

1017 cache: Optional[dict] = None, 

1018 pos_slice: Optional[Union[Slice, SliceInput]] = None, 

1019 ) -> Tuple[dict, list, list]: 

1020 """Build caching hooks without adding them. Mirrors ``HookedRootModule.get_caching_hooks``. 

1021 

1022 ``remove_batch_dim`` drops a leading dimension of size 1 and leaves any other tensor as 

1023 it is, so a batch larger than 1 keeps its batch dimension instead of losing examples. 

1024 The check is per tensor, so a broadcast activation with a size-1 leading dimension 

1025 (e.g. rotary ``hook_cos``/``hook_sin``) is squeezed even when the batch is larger. 

1026 Unlike ``run_with_cache``, which raises for a batch larger than 1, a hook sees one tensor 

1027 at a time and cannot tell a batch dimension from a flattened ``[batch * pos, ...]`` one. 

1028 Hooks that run under ``run_with_hooks(remove_batch_dim=True)`` already receive tensors 

1029 without a batch dimension, so set the flag on only one of the two. 

1030 

1031 Returns ``(cache, fwd_hooks, bwd_hooks)`` where each hook is a 

1032 ``(name, hook_fn)`` pair suitable for ``hooks()`` / ``run_with_hooks``. 

1033 Activations are keyed by the HookPoint's canonical name, and also by any 

1034 alias spelling that ``names_filter`` matched. This is broader than 

1035 ``run_with_cache`` for callable filters: one that matches only an alias 

1036 yields both the canonical and alias keys here, while ``run_with_cache`` 

1037 stores only the alias. Backward hooks append ``"_grad"``. ``bwd_hooks`` 

1038 is empty unless ``incl_bwd``. 

1039 """ 

1040 if cache is None: 

1041 cache = {} 

1042 pos_slice_obj = Slice.unwrap(pos_slice) 

1043 filter_fn = self._normalize_names_filter(names_filter) 

1044 

1045 def save_hook( 

1046 tensor: Any, hook: Any, is_backward: bool = False, alias_names: Tuple[str, ...] = () 

1047 ) -> None: 

1048 assert hook.name is not None 

1049 suffix = "_grad" if is_backward else "" 

1050 stored = tensor.detach().to(device) 

1051 # Slice before dropping the batch dim: _pos_slice_dim indexes the 

1052 # batched layout, so the order must match run_with_cache. 

1053 if pos_slice_obj is not None and stored.dim() >= 2: 1053 ↛ 1055line 1053 didn't jump to line 1055 because the condition on line 1053 was always true

1054 stored = pos_slice_obj.apply(stored, dim=self._pos_slice_dim(hook.name, hook)) 

1055 if remove_batch_dim: 

1056 stored = drop_batch_dim(stored) 

1057 for key in (hook.name, *alias_names): 

1058 cache[key + suffix] = stored 

1059 

1060 # One hook point can be reachable under several names (canonical + aliases). 

1061 # Gather every name the filter matched so the cache has an entry under the 

1062 # spelling the caller asked for, not just the canonical one. 

1063 matched: Dict[int, Tuple[str, HookPoint, List[str]]] = {} 

1064 for name, hook_point in self.hook_dict.items(): 

1065 if not filter_fn(name): 

1066 continue 

1067 entry = matched.setdefault(id(hook_point), (name, hook_point, [])) 

1068 if name != hook_point.name: 

1069 entry[2].append(name) 

1070 

1071 fwd_hooks: list = [] 

1072 bwd_hooks: list = [] 

1073 for name, hook_point, alias_names in matched.values(): 

1074 # The default sweep must not emit gated-off points: they never 

1075 # fire (empty cache entries at best), and feeding them to 

1076 # hooks()/run_with_hooks — the advertised composition — would 

1077 # raise. An explicit filter keeps them so downstream can warn. 

1078 if names_filter is None and self._gated_hook_reason(hook_point.name or name): 

1079 continue 

1080 # The unfiltered sweep matches every alias too; keep it canonical-only. 

1081 extra_names = () if names_filter is None else tuple(alias_names) 

1082 fwd_hooks.append((name, partial(save_hook, is_backward=False, alias_names=extra_names))) 

1083 if incl_bwd: 

1084 bwd_hooks.append( 

1085 (name, partial(save_hook, is_backward=True, alias_names=extra_names)) 

1086 ) 

1087 return cache, fwd_hooks, bwd_hooks 

1088 

1089 def add_caching_hooks( 

1090 self, 

1091 names_filter: Optional[Union[str, List[str], Callable[[str], bool]]] = None, 

1092 incl_bwd: bool = False, 

1093 device: Any = None, 

1094 remove_batch_dim: bool = False, 

1095 cache: Optional[dict] = None, 

1096 ) -> dict: 

1097 """Attach caching hooks to the model (does not run it). Returns the cache dict. 

1098 

1099 Mirrors ``HookedRootModule.add_caching_hooks``. The hooks persist until 

1100 ``reset_hooks()``. ``remove_batch_dim`` behaves as in :meth:`get_caching_hooks`: a leading 

1101 dimension of size 1 is dropped and a larger batch keeps its batch dimension. 

1102 """ 

1103 cache, fwd_hooks, bwd_hooks = self.get_caching_hooks( 

1104 names_filter, 

1105 incl_bwd=incl_bwd, 

1106 device=device, 

1107 remove_batch_dim=remove_batch_dim, 

1108 cache=cache, 

1109 ) 

1110 

1111 # Gated-off hook points never fire, so caching them is a no-op; skip 

1112 # them rather than trip add_hook's explicit-name guard. Warn only when 

1113 # the caller EXPLICITLY asked for them (run_with_cache's rule: the 

1114 # default filter matches everything and must not read as a request). 

1115 def _point_reason(name: str): 

1116 hp = self.hook_dict.get(name) 

1117 return self._gated_hook_reason(hp.name or name if hp is not None else name) 

1118 

1119 gated_skipped = [] 

1120 for name, hook_fn in fwd_hooks: 

1121 if _point_reason(name) is None: 

1122 self.add_hook(name, hook_fn, dir="fwd") 

1123 else: 

1124 gated_skipped.append(name) 

1125 for name, hook_fn in bwd_hooks: 1125 ↛ 1126line 1125 didn't jump to line 1126 because the loop on line 1125 never started

1126 if _point_reason(name) is None: 

1127 self.add_hook(name, hook_fn, dir="bwd") 

1128 elif name not in gated_skipped: 

1129 gated_skipped.append(name) 

1130 if names_filter is not None: 

1131 self._warn_gated_skipped("add_caching_hooks", gated_skipped) 

1132 return cache 

1133 

1134 def cache_all( 

1135 self, 

1136 cache: Optional[dict], 

1137 incl_bwd: bool = False, 

1138 device: Any = None, 

1139 remove_batch_dim: bool = False, 

1140 ) -> None: 

1141 """Deprecated: cache every activation. Use ``run_with_cache`` / ``add_caching_hooks``.""" 

1142 warnings.warn( 

1143 "cache_all is deprecated; use run_with_cache or add_caching_hooks.", 

1144 DeprecationWarning, 

1145 stacklevel=2, 

1146 ) 

1147 self.add_caching_hooks( 

1148 names_filter=None, 

1149 cache=cache, 

1150 incl_bwd=incl_bwd, 

1151 device=device, 

1152 remove_batch_dim=remove_batch_dim, 

1153 ) 

1154 

1155 def cache_some( 

1156 self, 

1157 cache: Optional[dict], 

1158 names: Callable[[str], bool], 

1159 incl_bwd: bool = False, 

1160 device: Any = None, 

1161 remove_batch_dim: bool = False, 

1162 ) -> None: 

1163 """Deprecated: cache activations matching ``names``. Use ``run_with_cache``.""" 

1164 warnings.warn( 

1165 "cache_some is deprecated; use run_with_cache or add_caching_hooks.", 

1166 DeprecationWarning, 

1167 stacklevel=2, 

1168 ) 

1169 self.add_caching_hooks( 

1170 names_filter=names, 

1171 cache=cache, 

1172 incl_bwd=incl_bwd, 

1173 device=device, 

1174 remove_batch_dim=remove_batch_dim, 

1175 ) 

1176 

1177 @staticmethod 

1178 def _resolve_stop_at_layer(stop_at_layer: int, n_blocks: int) -> int: 

1179 """Map ``stop_at_layer`` to ``[0, n_blocks]``, with ``n_blocks`` past the last block. 

1180 

1181 Any other value would run to completion and return logits as if it had stopped. 

1182 """ 

1183 resolved = n_blocks + stop_at_layer if stop_at_layer < 0 else stop_at_layer 

1184 if not 0 <= resolved <= n_blocks: 

1185 raise ValueError( 

1186 f"stop_at_layer={stop_at_layer} out of range [{-n_blocks}, {n_blocks}]." 

1187 ) 

1188 return resolved 

1189 

1190 @staticmethod 

1191 def _remove_temporary_hook( 

1192 hook_point: HookPoint, direction: Literal["fwd", "bwd"], handle: LensHandle 

1193 ) -> None: 

1194 """Remove an invocation's handle, not retained hooks at a reused lexical level.""" 

1195 if handle.is_permanent: 1195 ↛ 1196line 1195 didn't jump to line 1196 because the condition on line 1195 was never true

1196 return 

1197 handle.hook.remove() 

1198 handles = hook_point.fwd_hooks if direction == "fwd" else hook_point.bwd_hooks 

1199 handles[:] = [existing for existing in handles if existing is not handle] 

1200 

1201 def hooks( 

1202 self, 

1203 fwd_hooks: List = [], 

1204 bwd_hooks: List = [], 

1205 reset_hooks_end: bool = True, 

1206 clear_contexts: bool = False, 

1207 ) -> Any: 

1208 """Context manager for temporarily adding hooks. 

1209 

1210 ``reset_hooks_end`` removes the hooks this context added when it exits — 

1211 hooks the caller attached beforehand are left alone either way; 

1212 ``clear_contexts`` also wipes the touched hook points' ``ctx``. 

1213 

1214 Example: 

1215 with model.hooks(fwd_hooks=[("hook_embed", my_hook)]): 

1216 output = model("Hello world") 

1217 """ 

1218 

1219 @contextmanager 

1220 def _hooks_context() -> Iterator["BridgeCore"]: 

1221 added_hooks: List[Tuple[HookPoint, Literal["fwd", "bwd"], LensHandle]] = [] 

1222 context_level = getattr(self, "context_level", 0) + 1 

1223 self.context_level = context_level 

1224 

1225 def add_hook_to_point( 

1226 hook_point: HookPoint, 

1227 hook_fn: Callable, 

1228 name: str, 

1229 dir: Literal["fwd", "bwd"] = "fwd", 

1230 ) -> None: 

1231 self.check_hooks_to_add(hook_point, name, hook_fn, dir=dir) 

1232 if self.compatibility_mode and name != hook_point.name: 1232 ↛ 1233line 1232 didn't jump to line 1233 because the condition on line 1232 was never true

1233 alias_names_list: list = [] 

1234 if hook_point.name is not None: 

1235 alias_names_list.append(hook_point.name) 

1236 alias_names_list.append(name) 

1237 handle = hook_point.add_hook( 

1238 hook_fn, 

1239 dir=dir, 

1240 level=context_level, 

1241 alias_names=alias_names_list, 

1242 ) 

1243 else: 

1244 handle = hook_point.add_hook(hook_fn, dir=dir, level=context_level) 

1245 added_hooks.append((hook_point, dir, handle)) 

1246 

1247 def apply_hooks(hook_list: List[Tuple[Any, Callable]], is_fwd: bool) -> None: 

1248 direction: Literal["fwd", "bwd"] = "fwd" if is_fwd else "bwd" 

1249 hook_dict = self.hook_dict 

1250 aliases = build_alias_to_canonical_map(hook_dict) 

1251 for hook_name_or_filter, hook_fn in hook_list: 

1252 if isinstance(hook_name_or_filter, str): 

1253 actual_hook_name, hook_point = self._resolve_hook_point( 

1254 hook_name_or_filter, aliases, hook_dict 

1255 ) 

1256 add_hook_to_point(hook_point, hook_fn, actual_hook_name, direction) 

1257 else: 

1258 seen_hooks = set() 

1259 gated_skipped: List[str] = [] 

1260 for n, hook_point in hook_dict.items(): 

1261 if hook_name_or_filter(n): 

1262 hook_id = id(hook_point) 

1263 if hook_id in seen_hooks: 

1264 continue 

1265 seen_hooks.add(hook_id) 

1266 if self._gated_hook_reason(hook_point.name or n) is not None: 

1267 gated_skipped.append(n) 

1268 continue 

1269 hook_name_to_use = hook_point.name if hook_point.name else n 

1270 add_hook_to_point(hook_point, hook_fn, hook_name_to_use, direction) 

1271 self._warn_gated_skipped("hooks", gated_skipped, stacklevel=4) 

1272 

1273 try: 

1274 apply_hooks(fwd_hooks, True) 

1275 apply_hooks(bwd_hooks, False) 

1276 yield self 

1277 finally: 

1278 try: 

1279 for hook_point, direction, handle in added_hooks: 

1280 if reset_hooks_end: 

1281 self._remove_temporary_hook(hook_point, direction, handle) 

1282 if clear_contexts: 1282 ↛ 1283line 1282 didn't jump to line 1283 because the condition on line 1282 was never true

1283 hook_point.clear_context() 

1284 finally: 

1285 self.context_level -= 1 

1286 

1287 return _hooks_context() 

1288 

1289 # ---- high-level execution: run_with_hooks ---- 

1290 

1291 def run_with_hooks( 

1292 self, 

1293 input: Any, 

1294 fwd_hooks: List[Tuple[Union[str, Callable], Callable]] = [], 

1295 bwd_hooks: List[Tuple[Union[str, Callable], Callable]] = [], 

1296 reset_hooks_end: bool = True, 

1297 clear_contexts: bool = False, 

1298 return_type: Optional[str] = "logits", 

1299 stop_at_layer: Optional[int] = None, 

1300 start_at_layer: Optional[int] = None, 

1301 remove_batch_dim: bool = False, 

1302 **kwargs: Any, 

1303 ) -> Any: 

1304 """Run the model with specified forward and backward hooks. 

1305 

1306 ``stop_at_layer`` raises :class:`StopAtLayerException` to stop early 

1307 (KV cache cleaned up on stop). ``start_at_layer`` treats ``input`` as the 

1308 residual entering block ``k`` (see :meth:`forward`); hooks on blocks below 

1309 ``k`` are skipped to match HookedTransformer. ``remove_batch_dim`` 

1310 squeezes/unsqueezes the leading dim around each hook callback whenever 

1311 that tensor's leading dim is 1 — a per-tensor rule, so broadcast 

1312 activations such as rotary ``hook_cos``/``hook_sin`` lose their size-1 

1313 leading dim even at batch > 1. 

1314 ``reset_hooks_end`` removes the hooks this call added when it finishes — 

1315 hooks the caller attached beforehand are left alone either way; 

1316 ``clear_contexts`` also wipes the touched hook points' ``ctx``. 

1317 """ 

1318 _validate_execution_kwargs(kwargs, "run_with_hooks") 

1319 added_hooks: List[Tuple[HookPoint, Literal["fwd", "bwd"], LensHandle]] = [] 

1320 effective_stop_layer = None 

1321 if stop_at_layer is not None and hasattr(self, "blocks"): 

1322 effective_stop_layer = self._resolve_stop_at_layer(stop_at_layer, len(self.blocks)) 

1323 effective_start_layer = None 

1324 if start_at_layer is not None and hasattr(self, "blocks"): 1324 ↛ 1329line 1324 didn't jump to line 1329 because the condition on line 1324 was always true

1325 effective_start_layer = ( 

1326 len(self.blocks) + start_at_layer if start_at_layer < 0 else start_at_layer 

1327 ) 

1328 

1329 def add_hook_to_point( 

1330 hook_point: HookPoint, 

1331 hook_fn: Callable, 

1332 name: str, 

1333 dir: Literal["fwd", "bwd"] = "fwd", 

1334 ) -> None: 

1335 if effective_start_layer is not None and self._is_embedding_stage_hook(name): 1335 ↛ 1336line 1335 didn't jump to line 1336 because the condition on line 1335 was never true

1336 return 

1337 if name.startswith("blocks."): 

1338 try: 

1339 layer_num: Optional[int] = int(name.split(".")[1]) 

1340 except (IndexError, ValueError): 

1341 layer_num = None 

1342 if layer_num is not None: 1342 ↛ 1347line 1342 didn't jump to line 1347 because the condition on line 1342 was always true

1343 if effective_stop_layer is not None and layer_num >= effective_stop_layer: 

1344 return 

1345 if effective_start_layer is not None and layer_num < effective_start_layer: 

1346 return 

1347 self.check_hooks_to_add(hook_point, name, hook_fn, dir=dir) 

1348 if self.compatibility_mode and name != hook_point.name: 1348 ↛ 1349line 1348 didn't jump to line 1349 because the condition on line 1348 was never true

1349 alias_names_list: list = [] 

1350 if hook_point.name is not None: 

1351 alias_names_list.append(hook_point.name) 

1352 alias_names_list.append(name) 

1353 handle = hook_point.add_hook( 

1354 hook_fn, 

1355 dir=dir, 

1356 level=context_level, 

1357 alias_names=alias_names_list, 

1358 ) 

1359 else: 

1360 handle = hook_point.add_hook(hook_fn, dir=dir, level=context_level) 

1361 added_hooks.append((hook_point, dir, handle)) 

1362 

1363 def apply_hooks( 

1364 hook_list: List[Tuple[Union[str, Callable], Callable]], is_fwd: bool 

1365 ) -> None: 

1366 direction: Literal["fwd", "bwd"] = "fwd" if is_fwd else "bwd" 

1367 hook_dict = self.hook_dict 

1368 aliases = build_alias_to_canonical_map(hook_dict) 

1369 for hook_name_or_filter, hook_fn in hook_list: 

1370 if remove_batch_dim: 

1371 original_hook_fn = hook_fn 

1372 

1373 # Default arg captures hook_fn by value (avoids closure issue) 

1374 def wrapped_hook_fn(tensor, hook, _orig_fn=original_hook_fn): 

1375 if tensor.shape[0] == 1: 

1376 tensor_no_batch = tensor.squeeze(0) 

1377 result = _orig_fn(tensor_no_batch, hook) 

1378 if result is not None and result.dim() == tensor_no_batch.dim(): 

1379 result = result.unsqueeze(0) 

1380 return result 

1381 else: 

1382 return _orig_fn(tensor, hook) 

1383 

1384 hook_fn = wrapped_hook_fn 

1385 if isinstance(hook_name_or_filter, str): 

1386 # Resolve BEFORE gating: an aliased HT name may point at an 

1387 # always-firing override, which must not be refused. The 

1388 # message still names the caller's spelling. 

1389 actual_hook_name, hook_point = self._resolve_hook_point( 

1390 hook_name_or_filter, aliases, hook_dict 

1391 ) 

1392 reason = self._gated_hook_reason(hook_point.name or actual_hook_name) 

1393 if reason is not None: 

1394 raise ValueError( 

1395 f"Cannot add hook {hook_name_or_filter} because {reason} is False. " 

1396 f"Call set_{reason}(True) first." 

1397 ) 

1398 add_hook_to_point(hook_point, hook_fn, actual_hook_name, direction) 

1399 else: 

1400 seen_hooks: set = set() 

1401 gated_skipped: List[str] = [] 

1402 for n, hook_point in hook_dict.items(): 

1403 if hook_name_or_filter(n): 

1404 hook_id = id(hook_point) 

1405 if hook_id in seen_hooks: 1405 ↛ 1406line 1405 didn't jump to line 1406 because the condition on line 1405 was never true

1406 continue 

1407 seen_hooks.add(hook_id) 

1408 if self._gated_hook_reason(hook_point.name or n) is not None: 

1409 gated_skipped.append(n) 

1410 continue 

1411 hook_name_to_use = hook_point.name if hook_point.name else n 

1412 add_hook_to_point(hook_point, hook_fn, hook_name_to_use, direction) 

1413 self._warn_gated_skipped("run_with_hooks", gated_skipped, stacklevel=4) 

1414 

1415 context_level = getattr(self, "context_level", 0) + 1 

1416 self.context_level = context_level 

1417 try: 

1418 if effective_stop_layer is not None: 

1419 stop_at_layer = effective_stop_layer 

1420 apply_hooks(fwd_hooks, True) 

1421 apply_hooks(bwd_hooks, False) 

1422 if start_at_layer is not None: 

1423 kwargs["start_at_layer"] = start_at_layer 

1424 try: 

1425 output = self.forward( 

1426 input, return_type=return_type, stop_at_layer=stop_at_layer, **kwargs 

1427 ) 

1428 except StopAtLayerException as e: 

1429 output = e.layer_output 

1430 return output 

1431 finally: 

1432 try: 

1433 for hook_point, direction, handle in added_hooks: 

1434 if reset_hooks_end: 

1435 self._remove_temporary_hook(hook_point, direction, handle) 

1436 if clear_contexts: 

1437 hook_point.clear_context() 

1438 finally: 

1439 self.context_level -= 1 

1440 

1441 # ---- high-level execution: run_with_cache ---- 

1442 

1443 @overload 

1444 def run_with_cache( 

1445 self, 

1446 input: Union[str, List[str], torch.Tensor], 

1447 return_cache_object: Literal[True] = True, 

1448 remove_batch_dim: bool = False, 

1449 **kwargs, 

1450 ) -> Tuple[Any, ActivationCache]: 

1451 """Run with cache - placeholder implementation.""" 

1452 pass 

1453 

1454 @overload 

1455 def run_with_cache( 

1456 self, 

1457 input: Union[str, List[str], torch.Tensor], 

1458 return_cache_object: Literal[False], 

1459 remove_batch_dim: bool = False, 

1460 **kwargs, 

1461 ) -> Tuple[Any, Dict[str, torch.Tensor]]: 

1462 """Run with cache - placeholder implementation.""" 

1463 pass 

1464 

1465 def run_with_cache( 

1466 self, 

1467 input: Union[str, List[str], torch.Tensor], 

1468 return_cache_object: bool = True, 

1469 remove_batch_dim: bool = False, 

1470 names_filter: Optional[Union[str, List[str], Callable[[str], bool]]] = None, 

1471 stop_at_layer: Optional[int] = None, 

1472 start_at_layer: Optional[int] = None, 

1473 pos_slice: Optional[Union[Slice, SliceInput]] = None, 

1474 incl_bwd: bool = False, 

1475 reset_hooks_end: bool = True, 

1476 clear_contexts: bool = False, 

1477 **kwargs, 

1478 ) -> Tuple[Any, Union[ActivationCache, Dict[str, torch.Tensor]]]: 

1479 """Run the model and cache activations. Returns ``(output, cache)``. 

1480 

1481 ``stop_at_layer`` raises :class:`StopAtLayerException` to stop early. 

1482 ``start_at_layer`` treats ``input`` as the residual entering block ``k`` 

1483 (see :meth:`forward`); blocks below ``k`` are excluded from the cache to 

1484 match HookedTransformer. ``pos_slice`` slices each cached activation along 

1485 its position dimension (dim 1 for resid/per-head/token-id activations; the 

1486 query position ``-2`` for attention patterns/scores; ``HookPoint.pos_dim`` 

1487 for hooks fired on another layout). ``incl_bwd`` also caches gradients 

1488 under ``"<name>_grad"`` by running ``output.backward()``; 

1489 the caller must request a scalar output (``return_type="loss"``) and the 

1490 model must be on the gradients-capable transformers driver. 

1491 ``reset_hooks_end`` removes the hooks this call added when it finishes — 

1492 hooks the caller attached beforehand are left alone either way; 

1493 ``clear_contexts`` also wipes the touched hook points' ``ctx``. ``device`` 

1494 offloads cached activations (matches ``ActivationCache.to``); the model and 

1495 inputs stay where the caller put them. 

1496 To intervene while caching, use ``with model.hooks(fwd_hooks=...)`` 

1497 around this call; hook lists passed directly here raise ``TypeError``. 

1498 """ 

1499 _validate_execution_kwargs(kwargs, "run_with_cache") 

1500 if incl_bwd and stop_at_layer is not None: 

1501 raise ValueError( 

1502 "incl_bwd=True cannot be combined with stop_at_layer: the run returns the " 

1503 "intermediate activation at that layer, not a scalar to call backward() on." 

1504 ) 

1505 if incl_bwd and not torch.is_grad_enabled(): 

1506 raise ValueError( 

1507 "incl_bwd=True needs autograd, but gradient tracking is off " 

1508 "(torch.no_grad(), set_grad_enabled(False) or inference mode). " 

1509 "Run the call with gradients enabled." 

1510 ) 

1511 pos_slice_obj = Slice.unwrap(pos_slice) 

1512 aliases = build_alias_to_canonical_map(self.hook_dict) 

1513 

1514 def create_names_filter_fn(filter_input): 

1515 if filter_input is None: 

1516 return lambda name: True 

1517 elif isinstance(filter_input, str): 

1518 mapped_name = aliases.get(filter_input, None) 

1519 if mapped_name: 

1520 return lambda name: name == mapped_name or name == filter_input 

1521 else: 

1522 return lambda name: name == filter_input 

1523 elif isinstance(filter_input, list): 

1524 mapped_list = [] 

1525 for item in filter_input: 

1526 mapped_list.append(item) 

1527 mapped_name = aliases.get(item, None) 

1528 if mapped_name: 

1529 mapped_list.append(mapped_name) 

1530 return lambda name: name in mapped_list 

1531 elif callable(filter_input): 1531 ↛ 1534line 1531 didn't jump to line 1534 because the condition on line 1531 was always true

1532 return filter_input 

1533 else: 

1534 raise ValueError("names_filter must be a string, list of strings, or callable") 

1535 

1536 names_filter_fn = create_names_filter_fn(names_filter) 

1537 if isinstance(names_filter, (str, list)): 

1538 requested = [names_filter] if isinstance(names_filter, str) else names_filter 

1539 for name in requested: 

1540 self._check_hook_fireable(name, aliases.get(name, name)) 

1541 cache: Dict[str, torch.Tensor] = {} 

1542 hooks: List[Tuple[HookPoint, str]] = [] 

1543 visited: set[int] = set() 

1544 stop_hook_point: Optional[HookPoint] = None 

1545 stop_hook_fn: Optional[Callable] = None 

1546 

1547 # None → no-op .to(None), tensors stay on their current device. 

1548 cache_device = kwargs.pop("device", None) 

1549 

1550 def _store(name: str, value: torch.Tensor, hook: Any, suffix: str = "") -> None: 

1551 stored = value.detach().to(cache_device) 

1552 if pos_slice_obj is not None and stored.dim() >= 2: 

1553 # A gradient has its activation's layout, so the axis comes from 

1554 # the unsuffixed name — see _pos_slice_dim. 

1555 stored = pos_slice_obj.apply(stored, dim=self._pos_slice_dim(name, hook)) 

1556 cache[name + suffix] = stored 

1557 

1558 def make_cache_hook(name: str): 

1559 def cache_hook(tensor: torch.Tensor, *, hook: Any) -> torch.Tensor: 

1560 if tensor is None: 1560 ↛ 1561line 1560 didn't jump to line 1561 because the condition on line 1560 was never true

1561 cache[name] = None 

1562 elif isinstance(tensor, torch.Tensor): 1562 ↛ 1564line 1562 didn't jump to line 1564 because the condition on line 1562 was always true

1563 _store(name, tensor, hook) 

1564 elif isinstance(tensor, tuple): 

1565 if len(tensor) > 0 and isinstance(tensor[0], torch.Tensor): 

1566 _store(name, tensor[0], hook) 

1567 else: 

1568 pass 

1569 else: 

1570 try: 

1571 if hasattr(tensor, "detach"): 

1572 _store(name, tensor, hook) 

1573 except: 

1574 pass 

1575 return tensor 

1576 

1577 return cache_hook 

1578 

1579 hook_dict = self.hook_dict 

1580 effective_stop_layer = None 

1581 if stop_at_layer is not None and hasattr(self, "blocks"): 

1582 effective_stop_layer = self._resolve_stop_at_layer(stop_at_layer, len(self.blocks)) 

1583 if effective_stop_layer == len(self.blocks): 

1584 # No block follows the last for a hook_in to stop on; forward stops on its exit. 

1585 kwargs["stop_at_layer"] = effective_stop_layer 

1586 else: 

1587 # Stop at the beginning of the specified block, not at the end of the previous block 

1588 block_hook_name = f"blocks.{effective_stop_layer}.hook_in" 

1589 if block_hook_name in hook_dict: 1589 ↛ anywhereline 1589 didn't jump anywhere: it always raised an exception.

1590 

1591 def stop_hook(tensor: torch.Tensor, *, hook: Any) -> torch.Tensor: 

1592 raise StopAtLayerException(tensor) 

1593 

1594 stop_hook_point = hook_dict[block_hook_name] 

1595 stop_hook_fn = stop_hook 

1596 effective_start_layer = None 

1597 if start_at_layer is not None and hasattr(self, "blocks"): 

1598 effective_start_layer = ( 

1599 len(self.blocks) + start_at_layer if start_at_layer < 0 else start_at_layer 

1600 ) 

1601 matched_any = False 

1602 for hook_name, hook in hook_dict.items(): 

1603 if names_filter_fn(hook_name): 

1604 matched_any = True 

1605 if effective_start_layer is not None and self._is_embedding_stage_hook(hook_name): 

1606 continue 

1607 if hook_name.startswith("blocks."): 

1608 try: 

1609 layer_num = int(hook_name.split(".")[1]) 

1610 except (IndexError, ValueError): 

1611 layer_num = None 

1612 if layer_num is not None: 1612 ↛ 1620line 1612 didn't jump to line 1620 because the condition on line 1612 was always true

1613 # stop/start bound the executed range; blocks outside it 

1614 # either don't run (stop) or run on discarded input (start), 

1615 # so their activations must not enter the cache. 

1616 if effective_stop_layer is not None and layer_num >= effective_stop_layer: 

1617 continue 

1618 if effective_start_layer is not None and layer_num < effective_start_layer: 

1619 continue 

1620 hooks.append((hook, hook_name)) 

1621 # Explicit string/list filters matching nothing must not return (logits, {}) silently. 

1622 if not matched_any and names_filter and isinstance(names_filter, (str, list)): 1622 ↛ 1628line 1622 didn't jump to line 1628 because the condition on line 1622 was always true

1623 raise KeyError( 

1624 f"names_filter {names_filter!r} matched no hook points on this model; " 

1625 "check the name against model.hook_dict (this backend may not serve it)." 

1626 ) 

1627 

1628 def make_grad_cache_hook(name: str): 

1629 def grad_hook(tensor: torch.Tensor, *, hook: Any) -> None: 

1630 if isinstance(tensor, torch.Tensor): 1630 ↛ 1633line 1630 didn't jump to line 1633 because the condition on line 1630 was always true

1631 _store(name, tensor, hook, suffix="_grad") 

1632 # A non-None return from a backward hook replaces grad_input; stay read-only. 

1633 return None 

1634 

1635 return grad_hook 

1636 

1637 processed_args = [input] 

1638 # Driver-aware input placement: torch drivers move input_ids to the model's 

1639 # device; remote drivers (no local parameters) leave them as-is. 

1640 target_device = self._input_device() 

1641 if processed_args and isinstance(processed_args[0], str): 

1642 assert self.tokenizer is not None, "Tokenizer must be set to pass string input." 

1643 prepend_bos = kwargs.pop("prepend_bos", None) 

1644 input_ids = self.to_tokens(processed_args[0], prepend_bos=prepend_bos) 

1645 if target_device is not None: 1645 ↛ 1647line 1645 didn't jump to line 1647 because the condition on line 1645 was always true

1646 input_ids = input_ids.to(target_device) 

1647 kwargs["input_ids"] = input_ids 

1648 processed_args = processed_args[1:] 

1649 elif "input" in kwargs and isinstance(kwargs["input"], str): 1649 ↛ 1650line 1649 didn't jump to line 1650 because the condition on line 1649 was never true

1650 assert self.tokenizer is not None, "Tokenizer must be set to pass string input." 

1651 prepend_bos = kwargs.pop("prepend_bos", None) 

1652 input_ids = self.to_tokens(kwargs["input"], prepend_bos=prepend_bos) 

1653 if target_device is not None: 

1654 input_ids = input_ids.to(target_device) 

1655 kwargs["input_ids"] = input_ids 

1656 del kwargs["input"] 

1657 filtered_kwargs = kwargs.copy() 

1658 # ``cache_device`` is honored by ``make_cache_hook`` above (``tensor.detach().to(cache_device)``); 

1659 # the model and inputs stay where the caller put them, matching ``ActivationCache.to``. 

1660 if cache_device is not None and getattr(self.cfg, "n_devices", 1) > 1: 

1661 # Moving a dispatched model to a single device collapses accelerate's 

1662 # split and breaks its routing hooks. The cache will stay spread across 

1663 # the per-layer devices; callers can .to(cache_device) on cache entries 

1664 # after the fact if they need a single-device cache. 

1665 warnings.warn( 

1666 f"run_with_cache(device={cache_device!r}) ignored: model is dispatched " 

1667 f"across {self.cfg.n_devices} devices via device_map. Cached activations " 

1668 "will remain on their per-layer devices.", 

1669 stacklevel=2, 

1670 ) 

1671 if start_at_layer is not None: 

1672 filtered_kwargs["start_at_layer"] = start_at_layer 

1673 # Only validate gated hooks when the caller explicitly supplied a 

1674 # names_filter. The default filter matches every hook and must not 

1675 # cause gated hooks to be treated as explicitly requested. 

1676 gated_names_skipped: List[str] = [] 

1677 if names_filter is not None: 

1678 kept = [] 

1679 for hp, name in hooks: 

1680 if self._gated_hook_reason(hp.name or name) is not None: 

1681 gated_names_skipped.append(name) 

1682 else: 

1683 kept.append((hp, name)) 

1684 hooks = kept 

1685 if gated_names_skipped: 

1686 warnings.warn( 

1687 f"run_with_cache: skipped {len(gated_names_skipped)} gated-off hook name(s) " 

1688 f"that will never be cached: {gated_names_skipped}. Call the relevant " 

1689 "set_use_*(True) setter first to enable them.", 

1690 stacklevel=2, 

1691 ) 

1692 context_level = getattr(self, "context_level", 0) + 1 

1693 self.context_level = context_level 

1694 added_hooks: List[Tuple[HookPoint, Literal["fwd", "bwd"], LensHandle]] = [] 

1695 stop_handle: Optional[LensHandle] = None 

1696 try: 

1697 for hp, name in hooks: 

1698 fwd_handle = hp.add_hook(make_cache_hook(name), level=context_level) 

1699 added_hooks.append((hp, "fwd", fwd_handle)) 

1700 if incl_bwd: 

1701 bwd_handle = hp.add_hook( 

1702 make_grad_cache_hook(name), dir="bwd", level=context_level 

1703 ) 

1704 added_hooks.append((hp, "bwd", bwd_handle)) 

1705 if stop_hook_point is not None and stop_hook_fn is not None: 

1706 stop_handle = stop_hook_point.add_hook(stop_hook_fn, level=context_level) 

1707 added_hooks.append((stop_hook_point, "fwd", stop_handle)) 

1708 except Exception: 

1709 try: 

1710 for hp, direction, handle in added_hooks: 

1711 self._remove_temporary_hook(hp, direction, handle) 

1712 finally: 

1713 self.context_level -= 1 

1714 raise 

1715 try: 

1716 if ( 

1717 "output_attentions" not in filtered_kwargs 

1718 and self.adapter.supports_hf_output_attentions 

1719 ): 

1720 # Attention-free remote-code models (e.g. HyenaDNA) reject the 

1721 # kwarg outright; only pass it when the forward actually accepts 

1722 # it. Non-torch drivers expose no local module to introspect — 

1723 # keep the kwarg for them, as before. 

1724 underlying = getattr(self._driver, "underlying_model", None) 

1725 if underlying is None: 

1726 filtered_kwargs["output_attentions"] = True 

1727 else: 

1728 fwd_params = inspect.signature(underlying.forward).parameters 

1729 if "output_attentions" in fwd_params or any( 

1730 p.kind is inspect.Parameter.VAR_KEYWORD for p in fwd_params.values() 

1731 ): 

1732 filtered_kwargs["output_attentions"] = True 

1733 if processed_args: 

1734 output = self.forward(processed_args[0], **filtered_kwargs) 

1735 elif "input_ids" in filtered_kwargs: 1735 ↛ 1741line 1735 didn't jump to line 1741 because the condition on line 1735 was always true

1736 output = self.forward( 

1737 filtered_kwargs["input_ids"], 

1738 **{k: v for k, v in filtered_kwargs.items() if k != "input_ids"}, 

1739 ) 

1740 else: 

1741 output = self.forward(**filtered_kwargs) 

1742 if hasattr(output, "logits"): 1742 ↛ 1743line 1742 didn't jump to line 1743 because the condition on line 1742 was never true

1743 output = output.logits 

1744 if incl_bwd: 

1745 # Gradients land in the cache via the bwd hooks, which the finally below 

1746 # removes, so the backward pass has to happen inside this try. 

1747 if not isinstance(output, torch.Tensor) or output.numel() != 1: 

1748 shape = tuple(output.shape) if isinstance(output, torch.Tensor) else None 

1749 raise ValueError( 

1750 "incl_bwd=True needs a scalar output to call backward() on, got " 

1751 f"{type(output).__name__}{f' of shape {shape}' if shape else ''}. " 

1752 'Pass return_type="loss".' 

1753 ) 

1754 if not output.requires_grad: 

1755 raise ValueError( 

1756 "incl_bwd=True got an output with no grad_fn — the model's parameters " 

1757 "have requires_grad=False, so there is nothing to differentiate." 

1758 ) 

1759 output.backward() 

1760 except StopAtLayerException as e: 

1761 output = e.layer_output 

1762 except Exception as e: 

1763 raise e 

1764 finally: 

1765 try: 

1766 for hp, direction, handle in added_hooks: 

1767 # Retain requested cache hooks, but never internal early-stop hooks. 

1768 if reset_hooks_end or handle is stop_handle: 

1769 self._remove_temporary_hook(hp, direction, handle) 

1770 if clear_contexts: 

1771 for hp, _ in hooks: 

1772 hp.clear_context() 

1773 if stop_hook_point is not None: 1773 ↛ 1774line 1773 didn't jump to line 1774 because the condition on line 1773 was never true

1774 stop_hook_point.clear_context() 

1775 finally: 

1776 self.context_level -= 1 

1777 if self.compatibility_mode == True: 

1778 reverse_aliases = {} 

1779 for old_name, new_name in aliases.items(): 

1780 if isinstance(new_name, list): 1780 ↛ 1781line 1780 didn't jump to line 1781 because the condition on line 1780 was never true

1781 for single_new_name in new_name: 

1782 reverse_aliases[single_new_name] = old_name 

1783 else: 

1784 reverse_aliases[new_name] = old_name 

1785 # Gradient entries are keyed "<hook_name>_grad", so alias lookups run on the 

1786 # base name and the suffix is re-attached to the aliased key. 

1787 suffixes = ("", "_grad") if incl_bwd else ("",) 

1788 cache_items_to_add = {} 

1789 for cache_name, cached_value in cache.items(): 

1790 base_name, suffix = ( 

1791 (cache_name[: -len("_grad")], "_grad") 

1792 if cache_name.endswith("_grad") 

1793 else (cache_name, "") 

1794 ) 

1795 old_name = reverse_aliases.get(base_name) 

1796 if old_name is not None: 

1797 cache_items_to_add[old_name + suffix] = cached_value 

1798 cache.update(cache_items_to_add) 

1799 for alias_name, target_name in aliases.items(): 

1800 targets = target_name if isinstance(target_name, list) else [target_name] 

1801 for suffix in suffixes: 

1802 if alias_name + suffix in cache: 

1803 continue 

1804 for single_target in targets: 

1805 if single_target + suffix in cache: 1805 ↛ 1806line 1805 didn't jump to line 1806 because the condition on line 1805 was never true

1806 cache[alias_name + suffix] = cache[single_target + suffix] 

1807 break 

1808 # The input states the batch size; inferring it from the cached shapes goes wrong 

1809 # when the filter selects only flattened or position-indexed hooks. 

1810 batch_size = _input_batch_size( 

1811 processed_args[0] if processed_args else None, 

1812 filtered_kwargs.get("input_ids"), 

1813 filtered_kwargs.get("inputs_embeds"), 

1814 ) 

1815 if return_cache_object: 

1816 activation_cache = ActivationCache(cache, self, has_batch_dim=True) 

1817 if remove_batch_dim: 

1818 activation_cache.remove_batch_dim(batch_size=batch_size) 

1819 return (output, activation_cache) 

1820 else: 

1821 if remove_batch_dim: 

1822 # Same batch-size check and squeeze rule as the ActivationCache path. 

1823 tensors = {k: v for k, v in cache.items() if isinstance(v, torch.Tensor)} 

1824 cache.update( 

1825 ActivationCache(tensors, self) 

1826 .remove_batch_dim(batch_size=batch_size) 

1827 .cache_dict 

1828 ) 

1829 return (output, cache)