Coverage for transformer_lens/ActivationCache.py: 98%
677 statements
« prev ^ index » next coverage.py v7.10.1, created at 2026-11-25 00:28 +0000
« prev ^ index » next coverage.py v7.10.1, created at 2026-11-25 00:28 +0000
1"""Activation Cache.
3The :class:`ActivationCache` is at the core of Transformer Lens. It is a wrapper that stores all
4important activations from a forward pass of the model, and provides a variety of helper functions
5to investigate them.
7Getting Started:
9When reading these docs for the first time, we recommend reading the main :class:`ActivationCache`
10class first, including the examples, and then skimming the available methods. You can then refer
11back to these docs depending on what you need to do.
12"""
14from __future__ import annotations
16import logging
17from collections import Counter
18from typing import (
19 TYPE_CHECKING,
20 Any,
21 Callable,
22 Dict,
23 Iterator,
24 List,
25 Optional,
26 Tuple,
27 Union,
28 cast,
29)
31import einops
32import torch
33from jaxtyping import Float, Int
34from typing_extensions import Literal
36import transformer_lens.utilities as utils
37from transformer_lens.utilities import Slice, SliceInput, warn_if_mps
39if TYPE_CHECKING:
40 from transformer_lens.model_protocol import TransformerLensModelWithWeights
43def _normalize_projection_to_2d(
44 project: Optional[torch.Tensor],
45) -> Tuple[Optional[torch.Tensor], bool]:
46 """Return ``(project_2d, squeeze_at_end)`` — 1D projections are reshaped to 2D for uniform internal handling and squeezed back at the user-facing return."""
47 if project is None:
48 return None, False
49 if project.ndim == 1:
50 return project.unsqueeze(-1), True
51 return project, False
54class ActivationCache:
55 """Activation Cache.
57 A wrapper that stores all important activations from a forward pass of the model, and provides a
58 variety of helper functions to investigate them.
60 The :class:`ActivationCache` is at the core of Transformer Lens. It is a wrapper that stores all
61 important activations from a forward pass of the model, and provides a variety of helper
62 functions to investigate them. The common way to access it is to run the model with
63 :meth:`transformer_lens.model_bridge.TransformerBridge.run_with_cache`.
65 Examples:
67 When investigating a particular behaviour of a model, a very common first step is to try and
68 understand which components of the model are most responsible for that behaviour. For example,
69 if you're investigating the prompt "Why did the chicken cross the" -> " road", you might want to
70 understand if there is a specific sublayer (mlp or multi-head attention) that is responsible for
71 the model predicting "road". This kind of analysis commonly falls under the category of "logit
72 attribution" or "direct logit attribution" (DLA).
74 >>> from transformer_lens.model_bridge import TransformerBridge
75 >>> model = TransformerBridge.boot_transformers("roneneldan/TinyStories-1M")
76 >>> model.enable_compatibility_mode()
78 >>> _logits, cache = model.run_with_cache("Why did the chicken cross the")
79 >>> residual_stream, labels = cache.decompose_resid(return_labels=True, mode="attn")
80 >>> print(labels[0:3])
81 ['embed', 'pos_embed', '0_attn_out']
83 >>> answer = " road" # Note the proceeding space to match the model's tokenization
84 >>> logit_attrs = cache.logit_attrs(residual_stream, answer)
85 >>> print(logit_attrs.shape) # Attention layers
86 torch.Size([10, 1, 7])
88 >>> most_important_component_idx = torch.argmax(logit_attrs)
89 >>> print(labels[most_important_component_idx])
90 3_attn_out
92 You can also dig in with more granularity, using :meth:`get_full_resid_decomposition` to get the
93 residual stream by individual component (mlp neurons and individual attention heads). This
94 creates a larger residual stack, but the approach of using :meth"`logit_attrs` remains the same.
96 Equally you might want to find out if the model struggles to construct such excellent jokes
97 until the very last layers, or if it is trivial and the first few layers are enough. This kind
98 of analysis is called "logit lens", and you can find out more about how to do that with
99 :meth:`ActivationCache.accumulated_resid`.
101 Warning:
103 :class:`ActivationCache` is designed to be used with
104 :class:`transformer_lens.model_bridge.TransformerBridge`. Advanced helpers expect the model to
105 expose the TransformerLens weight-processing interface and generally expect a complete cache;
106 some internal methods may break with other models or partial caches.
108 The biggest footgun and source of bugs in this code will be keeping track of indexes,
109 dimensions, and the numbers of each. There are several kinds of activations:
111 * Internal attn head vectors: q, k, v, z. Shape [batch, pos, head_index, d_head].
112 * Internal attn pattern style results: pattern (post softmax), attn_scores (pre-softmax). Shape
113 [batch, head_index, query_pos, key_pos].
114 * Attn head results: result. Shape [batch, pos, head_index, d_model].
115 * Internal MLP vectors: pre, post, mid (only used for solu_ln - the part between activation +
116 layernorm). Shape [batch, pos, d_mlp].
117 * Residual stream vectors: resid_pre, resid_mid, resid_post, attn_out, mlp_out, embed,
118 pos_embed, normalized (output of each LN or LNPre). Shape [batch, pos, d_model].
119 * LayerNorm Scale: scale. Shape [batch, pos, 1].
121 Sometimes the batch dimension will be missing because we applied `remove_batch_dim` (used when
122 batch_size=1), and as such all library functions *should* be robust to that.
124 Type annotations are in the following form:
126 * layers_covered is the number of layers queried in functions that stack the residual stream.
127 * batch_and_pos_dims is the set of dimensions from batch and pos - by default this is ["batch",
128 "pos"], but is only ["pos"] if we've removed the batch dimension and is [()] if we've removed
129 batch dimension and are applying a pos slice which indexes a specific position.
131 Args:
132 cache_dict:
133 A dictionary of cached activations from a model run.
134 model:
135 The model that the activations are from.
136 has_batch_dim:
137 Whether the activations have a batch dimension.
138 """
140 def __init__(
141 self,
142 cache_dict: Dict[str, torch.Tensor],
143 model: Any,
144 has_batch_dim: bool = True,
145 ):
146 self.cache_dict = cache_dict
147 # Advanced helpers (LN folding, residual-direction projection) need the
148 # weight-processing surface, which TransformerBridge exposes.
149 self.model = cast("TransformerLensModelWithWeights", model)
150 self.has_batch_dim = has_batch_dim
151 self.has_embed = "hook_embed" in self.cache_dict
152 self.has_pos_embed = "hook_pos_embed" in self.cache_dict
154 # Note: model reference prevents garbage collection. Set cache.model = None if unneeded.
156 def _batch_size(self) -> int:
157 """The cache's batch size: the most common leading dim across entries.
159 Caches may hold non-batch entries alongside genuinely batched
160 activations — broadcast entries with a leading dim of 1 (e.g. the
161 bridge's position-index inputs) or position-indexed entries whose
162 leading dim is the sequence length (e.g. T5's relative position bias).
163 The batched activations vastly outnumber both, so the mode is the
164 reliable signal where max/min are not.
165 """
166 counts = Counter(v.size(0) for v in self.cache_dict.values() if v.ndim > 0)
167 return counts.most_common(1)[0][0] if counts else 1
169 def remove_batch_dim(self, batch_size: Optional[int] = None) -> ActivationCache:
170 """Remove the Batch Dimension (if a single batch item).
172 Args:
173 batch_size:
174 The true batch size, when the caller knows it. By default it is inferred from
175 the most common leading dimension of the cached entries, which is wrong for a
176 cache holding only flattened or position-indexed activations.
178 Returns:
179 The ActivationCache with the batch dimension removed.
180 """
181 if self.has_batch_dim:
182 if batch_size is None:
183 batch_size = self._batch_size()
184 assert (
185 batch_size == 1
186 ), f"Cannot remove batch dimension from cache with batch size {batch_size}"
187 for key in self.cache_dict:
188 if self.cache_dict[key].ndim > 0 and self.cache_dict[key].size(0) == 1:
189 self.cache_dict[key] = self.cache_dict[key][0]
190 self.has_batch_dim = False
191 else:
192 logging.warning("Tried removing batch dimension after already having removed it.")
193 return self
195 def __repr__(self) -> str:
196 """Representation of the ActivationCache.
198 Special method that returns a string representation of an object. It's normally used to give
199 a string that can be used to recreate the object, but here we just return a string that
200 describes the object.
201 """
202 return f"ActivationCache with keys {list(self.cache_dict.keys())}"
204 def __getitem__(self, key) -> torch.Tensor:
205 """Retrieve Cached Activations by Key or Shorthand.
207 Enables direct access to cached activations via dictionary-style indexing using keys or
208 shorthand naming conventions.
210 It also supports tuples for advanced indexing, with the dimension order as (name, layer_index, layer_type).
211 See :func:`transformer_lens.utilities.get_act_name` for how shorthand is converted to a full name.
214 Args:
215 key:
216 The key or shorthand name for the activation to retrieve.
218 Returns:
219 The cached activation tensor corresponding to the given key.
220 """
221 if key in self.cache_dict:
222 return self.cache_dict[key]
223 elif type(key) == str:
224 return self.cache_dict[utils.get_act_name(key)]
225 else:
226 if len(key) > 1 and key[1] is not None:
227 if key[1] < 0:
228 # Supports negative indexing on the layer dimension
229 key = (key[0], self.model.cfg.n_layers + key[1], *key[2:])
230 return self.cache_dict[utils.get_act_name(*key)]
232 def __len__(self) -> int:
233 """Length of the ActivationCache.
235 Special method that returns the length of an object (in this case the number of different
236 activations in the cache).
237 """
238 return len(self.cache_dict)
240 def to(self, device: Union[str, torch.device]) -> ActivationCache:
241 """Move the Cache to a Device.
243 Mostly useful for moving the cache to the CPU after model computation finishes to save GPU
244 memory. Note however that operations will be much slower on the CPU. Note also that some
245 methods will break unless the model is also moved to the same device, eg
246 `compute_head_results`.
248 Args:
249 device:
250 The device to move the cache to (e.g. `torch.device.cpu`).
252 """
253 warn_if_mps(device)
254 self.cache_dict = {key: value.to(device) for key, value in self.cache_dict.items()}
255 return self
257 def toggle_autodiff(self, mode: bool = False):
258 """Toggle Autodiff Globally.
260 Applies `torch.set_grad_enabled(mode)` to the global state (not just TransformerLens).
262 Warning:
264 This is pretty dangerous, since autodiff is global state - this turns off torch's
265 ability to take gradients completely and it's easy to get a bunch of errors if you don't
266 realise what you're doing.
268 But autodiff consumes a LOT of GPU memory (since every intermediate activation is cached
269 until all downstream activations are deleted - this means that computing the loss and
270 storing it in a list will keep every activation sticking around!). So often when you're
271 analysing a model's activations, and don't need to do any training, autodiff is more trouble
272 than its worth.
274 If you don't want to mess with global state, using torch.inference_mode as a context manager
275 or decorator achieves similar effects:
277 >>> with torch.inference_mode():
278 ... y = torch.Tensor([1., 2, 3])
279 >>> y.requires_grad
280 False
281 """
282 logging.warning("Changed the global state, set autodiff to %s", mode)
283 torch.set_grad_enabled(mode)
285 def keys(self):
286 """Keys of the ActivationCache.
288 Examples:
290 >>> from transformer_lens.model_bridge import TransformerBridge
291 >>> model = TransformerBridge.boot_transformers("roneneldan/TinyStories-1M")
292 >>> model.enable_compatibility_mode()
293 >>> _logits, cache = model.run_with_cache("Some prompt")
294 >>> list(cache.keys())[0:8]
295 ['embed.hook_in', 'hook_embed', 'embed.hook_out', 'pos_embed.hook_in',
296 'hook_pos_embed', 'pos_embed.hook_out', 'blocks.0.hook_in',
297 'blocks.0.hook_resid_pre']
299 Returns:
300 List of all keys.
301 """
302 return self.cache_dict.keys()
304 def values(self):
305 """Values of the ActivationCache.
307 Returns:
308 List of all values.
309 """
310 return self.cache_dict.values()
312 def items(self):
313 """Items of the ActivationCache.
315 Returns:
316 List of all items ((key, value) tuples).
317 """
318 return self.cache_dict.items()
320 def __iter__(self) -> Iterator[str]:
321 """ActivationCache Iterator.
323 Special method that returns an iterator over the keys in the ActivationCache. Allows looping over the
324 cache.
326 Examples:
328 >>> from transformer_lens.model_bridge import TransformerBridge
329 >>> model = TransformerBridge.boot_transformers("roneneldan/TinyStories-1M")
330 >>> model.enable_compatibility_mode()
331 >>> _logits, cache = model.run_with_cache("Some prompt")
332 >>> cache_interesting_names = []
333 >>> for key in cache:
334 ... if not key.startswith("blocks.") or key.startswith("blocks.0"):
335 ... cache_interesting_names.append(key)
336 >>> print(cache_interesting_names[0:8])
337 ['embed.hook_in', 'hook_embed', 'embed.hook_out', 'pos_embed.hook_in',
338 'hook_pos_embed', 'pos_embed.hook_out', 'blocks.0.hook_in',
339 'blocks.0.hook_resid_pre']
341 Returns:
342 Iterator over the cache.
343 """
344 return self.cache_dict.__iter__()
346 def apply_slice_to_batch_dim(self, batch_slice: Union[Slice, SliceInput]) -> ActivationCache:
347 """Apply a Slice to the Batch Dimension.
349 Args:
350 batch_slice:
351 The slice to apply to the batch dimension.
353 Returns:
354 The ActivationCache with the batch dimension sliced.
355 """
356 if not isinstance(batch_slice, Slice):
357 batch_slice = Slice(batch_slice)
358 batch_slice = cast(Slice, batch_slice) # mypy can't seem to infer this
359 assert (
360 self.has_batch_dim or batch_slice.mode == "identity"
361 ), "Cannot index into a cache without a batch dim"
362 still_has_batch_dim = (batch_slice.mode != "int") and self.has_batch_dim
363 batch_size = self._batch_size()
364 # Broadcast entries (leading dim 1 when the true batch is larger) are not
365 # batched — leave them untouched so slicing can't index out of bounds.
366 new_cache_dict = {
367 name: (
368 batch_slice.apply(param, dim=0)
369 if param.ndim > 0 and param.size(0) == batch_size
370 else param
371 )
372 for name, param in self.cache_dict.items()
373 }
374 return ActivationCache(new_cache_dict, self.model, has_batch_dim=still_has_batch_dim)
376 def _mlp_input_includes_attn(self, layer: int) -> bool:
377 """Whether the target block's MLP reads the current attention contribution."""
378 return layer < self.model.cfg.n_layers and bool(
379 getattr(self.model.blocks[layer], "mlp_input_includes_attn", True)
380 )
382 def _block_modules(self, layer: int) -> Optional[Dict[str, Any]]:
383 """Bridged submodules of block ``layer``, or None when the model exposes none."""
384 blocks = getattr(self.model, "blocks", None)
385 if blocks is None or layer >= len(blocks): 385 ↛ 386line 385 didn't jump to line 386 because the condition on line 385 was never true
386 return None
387 modules = getattr(blocks[layer], "_modules", None)
388 return modules if isinstance(modules, dict) else None
390 def _has_attn(self, layer: int) -> bool:
391 """Whether block ``layer`` has attention (and so ``hook_attn_out`` / per-head hooks)."""
392 from transformer_lens.model_bridge.generalized_components.block import (
393 VARIANT_SUBMODULE_NAMES,
394 )
396 modules = self._block_modules(layer)
397 # Blocks declaring no sequence-mixer slot keep the attention default.
398 return (
399 modules is None
400 or "attn" in modules
401 or not any(name in modules for name in VARIANT_SUBMODULE_NAMES)
402 )
404 def _mixer_out_names(self, layer: int) -> List[str]:
405 """Variant slots (``linear_attn``, ``mixer``, …) of a block without attention.
407 Hybrid and SSM blocks write their sequence-mixer output in place of
408 ``hook_attn_out``; empty for attention blocks.
409 """
410 from transformer_lens.model_bridge.generalized_components.block import (
411 VARIANT_SUBMODULE_NAMES,
412 )
414 if self._has_attn(layer):
415 return []
416 modules = self._block_modules(layer) or {}
417 return [name for name in VARIANT_SUBMODULE_NAMES if name in modules]
419 def _has_mlp(self, layer: int) -> bool:
420 """Whether block ``layer`` writes an MLP output separate from its mixer."""
421 from transformer_lens.model_bridge.generalized_components.block import (
422 _BLOCK_INTERNAL_MODULES,
423 _NORM_PREFIXES,
424 _VARIANT_SUBMODULE_SET,
425 )
427 if self.model.cfg.attn_only: 427 ↛ 428line 427 didn't jump to line 428 because the condition on line 427 was never true
428 return False
429 modules = self._block_modules(layer)
430 if modules is None or "mlp" in modules:
431 return True
432 # Mamba / NemotronH blocks hold only norms and a mixer. Anything else that writes to the
433 # residual stream (e.g. a MoE without an `mlp` slot) keeps the `mlp_out` contract.
434 return any(
435 name not in _VARIANT_SUBMODULE_SET
436 and name not in _BLOCK_INTERNAL_MODULES
437 and not name.startswith(_NORM_PREFIXES)
438 for name in modules
439 )
441 def _mixer_role(self, layer: int) -> Literal["attn", "mlp"]:
442 """Residual slot a non-attention block's mixer fills.
444 Single-mixer blocks (NemotronH) wrap attention, Mamba and MLP layers alike in one
445 passthrough ``mixer``; ``cfg.layers_block_type`` says which one it is.
446 """
447 block_types = getattr(self.model.cfg, "layers_block_type", None)
448 if isinstance(block_types, (list, tuple)) and layer < len(block_types):
449 if block_types[layer] in ("mlp", "moe"):
450 return "mlp"
451 return "attn"
453 def _mixer_label(self, layer: int, name: str) -> str:
454 """``{l}_mlp_out`` / ``{l}_attn_out`` for typed passthrough mixers, else ``{l}_{name}_out``."""
455 block_types = getattr(self.model.cfg, "layers_block_type", None)
456 block_type = (
457 block_types[layer]
458 if isinstance(block_types, (list, tuple)) and layer < len(block_types)
459 else None
460 )
461 if block_type in ("mlp", "moe"):
462 return f"{layer}_mlp_out"
463 if block_type in ("attention", "full_attention"):
464 return f"{layer}_attn_out"
465 return f"{layer}_{name}_out"
467 def _mixer_stack(
468 self, layer: int, pos_slice: Slice, subtract_bias: bool = False
469 ) -> Tuple[List[torch.Tensor], List[str]]:
470 """Residual contributions of a non-attention block's mixer, e.g. ``0_linear_attn_out``.
472 Scaled by the block's ``residual_contribution_scale`` (Granite's ``residual_multiplier``
473 is applied after ``hook_out``), matching the head and neuron paths. ``subtract_bias``
474 drops the mixer's output bias first, for decompositions that carry it in their own
475 ``bias`` row.
476 """
477 components: List[torch.Tensor] = []
478 labels: List[str] = []
479 names = self._mixer_out_names(layer)
480 block = self.model.blocks[layer]
481 scale = getattr(block, "residual_contribution_scale", 1.0)
482 # Same bias accumulated_bias counts for this block, so the two cancel exactly.
483 bias = None
484 if subtract_bias and names:
485 get_bias = getattr(self.model, "_get_block_variant_bias", None)
486 bias = get_bias(block) if callable(get_bias) else None
487 for i, name in enumerate(names):
488 out = pos_slice.apply(self[f"blocks.{layer}.{name}.hook_out"], dim=-2)
489 if i == 0 and isinstance(bias, torch.Tensor):
490 out = out - bias.to(out.device, out.dtype)
491 if scale != 1.0:
492 out = out * scale
493 components.append(out)
494 labels.append(self._mixer_label(layer, name))
495 return components, labels
497 def accumulated_resid(
498 self,
499 layer: Optional[int] = None,
500 incl_mid: bool = False,
501 apply_ln: bool = False,
502 pos_slice: Optional[Union[Slice, SliceInput]] = None,
503 mlp_input: bool = False,
504 return_labels: bool = False,
505 ) -> Union[
506 Float[torch.Tensor, "layers_covered *batch_and_pos_dims d_model"],
507 Tuple[Float[torch.Tensor, "layers_covered *batch_and_pos_dims d_model"], List[str]],
508 ]:
509 """Accumulated Residual Stream.
511 Returns the accumulated residual stream at each layer/sub-layer. This is useful for `Logit
512 Lens <https://www.lesswrong.com/posts/AcKRB8wDpdaN6v6ru/interpreting-gpt-the-logit-lens>`
513 style analysis, where it can be thought of as what the model "believes" at each point in the
514 residual stream.
516 :meth:`logit_lens` does the whole projection below in one call (final norm, ``W_U``,
517 ``b_U`` and the adapter's output transform, chunked over the vocabulary); the recipe
518 here shows what it computes.
520 To project this into the vocabulary space, remember that there is a final layer norm in most
521 decoder-only transformers. Therefore, you need to first apply the final layer norm (which
522 can be done with `apply_ln`), and then multiply by the unembedding matrix (:math:`W_U`)
523 and optionally add the unembedding bias (:math:`b_U`).
525 **Note on bias terms:** There are two valid approaches for the final projection:
527 1. **With bias terms:** Use `model.unembed(normalized_resid)` which applies both :math:`W_U`
528 and :math:`b_U` (equivalent to `normalized_resid @ model.W_U + model.b_U`). This works
529 correctly with both `fold_ln=True` and `fold_ln=False` settings, as the biases are
530 handled consistently.
531 2. **Without bias terms:** Use only `normalized_resid @ model.W_U`. If taking this approach,
532 you should instantiate the model with `fold_ln=True`, which folds the layer norm scaling
533 into :math:`W_U` and the layer norm bias into :math:`b_U`. Since `apply_ln=True` will
534 apply the (now parameter-free) layer norm, and you skip :math:`b_U`, no bias terms are
535 included. With `fold_ln=False`, the layer norm bias would still be applied, which is
536 typically not desired when excluding bias terms.
538 Both approaches are commonly used in the literature and are valid interpretability choices.
540 If you instead want to look at contributions to the residual stream from each component
541 (e.g. for direct logit attribution), see :meth:`decompose_resid` instead, or
542 :meth:`get_full_resid_decomposition` if you want contributions broken down further into each
543 MLP neuron.
545 Examples:
547 Logit Lens analysis can be done as follows:
549 >>> from transformer_lens.model_bridge import TransformerBridge
550 >>> import torch
551 >>> import pandas as pd
553 >>> model = TransformerBridge.boot_transformers("roneneldan/TinyStories-1M", device="cpu")
554 >>> model.enable_compatibility_mode()
556 >>> prompt = "Why did the chicken cross the"
557 >>> answer = " road"
558 >>> logits, cache = model.run_with_cache("Why did the chicken cross the")
559 >>> answer_token = model.to_single_token(answer)
560 >>> print(answer_token)
561 2975
563 >>> accum_resid, labels = cache.accumulated_resid(return_labels=True, apply_ln=True)
564 >>> last_token_accum = accum_resid[:, 0, -1, :] # layer, batch, pos, d_model
565 >>> print(last_token_accum.shape) # layer, d_model
566 torch.Size([9, 64])
569 >>> W_U = model.W_U
570 >>> print(W_U.shape)
571 torch.Size([64, 50257])
573 >>> # Project to vocabulary without unembedding bias
574 >>> layers_logits = last_token_accum @ W_U # layer, d_vocab
575 >>> print(layers_logits.shape)
576 torch.Size([9, 50257])
578 >>> # The unembedding bias can be added on top when the model carries one
579 >>> # (the rank table below stays on the bias-free logits):
580 >>> b_U = getattr(model, "b_U", None)
581 >>> with_bias = layers_logits + b_U if b_U is not None else layers_logits
582 >>> print(with_bias.shape)
583 torch.Size([9, 50257])
585 >>> # Get the rank of the correct answer by layer
586 >>> sorted_indices = torch.argsort(layers_logits, dim=1, descending=True)
587 >>> rank_answer = (sorted_indices == 2975).nonzero(as_tuple=True)[1]
588 >>> print(pd.Series(rank_answer, index=labels))
589 0_pre 4442
590 1_pre 382
591 2_pre 982
592 3_pre 1160
593 4_pre 408
594 5_pre 145
595 6_pre 78
596 7_pre 387
597 final_post 6
598 dtype: int64
600 Args:
601 layer:
602 The layer to take components up to - by default includes resid_pre for that layer
603 and excludes resid_mid and resid_post for that layer. If set as `n_layers`, `-1` or
604 `None` it will return all residual streams, including the final one (i.e.
605 immediately pre logits). The indices are taken such that this gives the accumulated
606 streams up to the input to layer l.
607 incl_mid:
608 Whether to return `resid_mid` for previous sequential-residual layers.
609 Parallel-residual layers have no distinct mid stream.
610 apply_ln:
611 Whether to apply the final layer norm to the stack. When True, applies
612 `model.ln_final`, which recomputes normalization statistics (mean and
613 variance/RMS) for each intermediate state in the stack, transforming the
614 activations into the format expected by the unembedding layer.
615 pos_slice:
616 A slice object to apply to the pos dimension. Defaults to None, do nothing.
617 mlp_input:
618 Target the MLP input: include the current resid_mid for sequential blocks;
619 parallel blocks already expose this input as resid_pre.
620 return_labels:
621 Whether to return a list of labels for the residual stream components. Useful for
622 labelling graphs.
624 Returns:
625 A tensor of the accumulated residual streams. If `return_labels` is True, also returns a
626 list of labels for the components (as a tuple in the form `(components, labels)`).
627 """
628 if not isinstance(pos_slice, Slice):
629 pos_slice = Slice(pos_slice)
630 if layer is None or layer == -1:
631 # Default to the residual stream immediately pre unembed
632 layer = self.model.cfg.n_layers
633 assert isinstance(layer, int)
634 labels = []
635 components_list = []
636 for l in range(layer + 1):
637 if l == self.model.cfg.n_layers:
638 components_list.append(self[("resid_post", self.model.cfg.n_layers - 1)])
639 labels.append("final_post")
640 continue
641 components_list.append(self[("resid_pre", l)])
642 labels.append(f"{l}_pre")
643 if ((incl_mid and l < layer) or (mlp_input and l == layer)) and (
644 self._mlp_input_includes_attn(l)
645 ):
646 components_list.append(self[("resid_mid", l)])
647 labels.append(f"{l}_mid")
648 components_list = [pos_slice.apply(c, dim=-2) for c in components_list]
649 components = torch.stack(components_list, dim=0)
650 if apply_ln:
651 recompute_ln = layer == self.model.cfg.n_layers
652 components = self.apply_ln_to_stack(
653 components,
654 layer,
655 pos_slice=pos_slice,
656 mlp_input=mlp_input,
657 has_batch_dim=self.has_batch_dim,
658 recompute_ln=recompute_ln,
659 )
660 if return_labels:
661 return components, labels
662 else:
663 return components
665 def logit_lens(self, **kwargs: Any) -> Any:
666 """One-call logit lens over this cache's accumulated residual stream.
668 Delegates to :func:`transformer_lens.tools.analysis.logit_lens.logit_lens`
669 with this cache; see it for the keyword arguments (``layers``,
670 ``positions``, ``targets``, ``top_k``, ``vocab``, ``return_type`` ...).
671 The final stack entry reproduces the model's logits through the real
672 final norm, ``W_U``, ``b_U`` and the adapter's output transform.
673 """
674 # Lazy import: tools.analysis imports this module.
675 from transformer_lens.tools.analysis.logit_lens import logit_lens
677 return logit_lens(self.model, cache=self, **kwargs)
679 def logit_attrs(
680 self,
681 residual_stack: Float[torch.Tensor, "num_components *batch_and_pos_dims d_model"],
682 tokens: Union[
683 str,
684 int,
685 Int[torch.Tensor, ""],
686 Int[torch.Tensor, "batch"],
687 Int[torch.Tensor, "batch position"],
688 ],
689 incorrect_tokens: Optional[
690 Union[
691 str,
692 int,
693 Int[torch.Tensor, ""],
694 Int[torch.Tensor, "batch"],
695 Int[torch.Tensor, "batch position"],
696 ]
697 ] = None,
698 pos_slice: Union[Slice, SliceInput] = None,
699 batch_slice: Union[Slice, SliceInput] = None,
700 has_batch_dim: bool = True,
701 ) -> Float[torch.Tensor, "num_components *batch_and_pos_dims_out"]:
702 """Logit Attributions.
704 Takes a residual stack (typically the residual stream decomposed by components), and
705 calculates how much each item in the stack "contributes" to specific tokens.
707 It does this by:
708 1. Getting the residual directions of the tokens (i.e. reversing the unembed)
709 2. Taking the dot product of each item in the residual stack, with the token residual
710 directions.
712 Note that if incorrect tokens are provided, it instead takes the difference between the
713 correct and incorrect tokens (to calculate the residual directions). This is useful as
714 sometimes we want to know e.g. which components are most responsible for selecting the
715 correct token rather than an incorrect one. For example in the `Interpretability in the Wild
716 paper <https://arxiv.org/abs/2211.00593>` prompts such as "John and Mary went to the shops,
717 John gave a bag to" were investigated, and it was therefore useful to calculate attribution
718 for the :math:`\\text{Mary} - \\text{John}` residual direction.
720 Warning:
722 Choosing the correct `tokens` and `incorrect_tokens` is both important and difficult. When
723 investigating specific components it's also useful to look at it's impact on all tokens
724 (i.e. :math:`\\text{final_ln}(\\text{residual_stack_item}) W_U`).
726 Args:
727 residual_stack:
728 Stack of components of residual stream to get logit attributions for.
729 tokens:
730 Tokens to compute logit attributions on. A [batch] tensor selects one token
731 per example across all retained positions. A 1-D tensor whose length differs
732 from the batch size selects one token per position, shared across examples.
733 Use [1, position] to share per-position targets when batch and position sizes
734 are equal; [batch, position] selects targets for each example and position.
735 Token tensors should already match any batch/position slices.
736 incorrect_tokens:
737 If provided, compute attributions on logit difference between tokens and
738 incorrect_tokens. Must have the same shape as tokens.
739 pos_slice:
740 The slice to apply layer norm scaling on. Defaults to None, do nothing.
741 batch_slice:
742 The slice to take on the batch dimension during layer norm scaling. Defaults to
743 None, do nothing.
744 has_batch_dim:
745 Whether residual_stack has a batch dimension. Defaults to True.
747 Returns:
748 A tensor of the logit attributions or logit difference attributions if incorrect_tokens
749 was provided.
750 """
751 if not isinstance(pos_slice, Slice):
752 pos_slice = Slice(pos_slice)
754 if not isinstance(batch_slice, Slice):
755 batch_slice = Slice(batch_slice)
757 # Convert tokens to tensor for shape checking, but pass original to tokens_to_residual_directions
758 tokens_for_shape_check = tokens
760 if isinstance(tokens_for_shape_check, str):
761 tokens_for_shape_check = torch.as_tensor(
762 self.model.to_single_token(tokens_for_shape_check)
763 )
764 elif isinstance(tokens_for_shape_check, int):
765 tokens_for_shape_check = torch.as_tensor(tokens_for_shape_check)
767 logit_directions = self.model.tokens_to_residual_directions(tokens)
769 if incorrect_tokens is not None:
770 # Convert incorrect_tokens to tensor for shape checking, but pass original to tokens_to_residual_directions
771 incorrect_tokens_for_shape_check = incorrect_tokens
773 if isinstance(incorrect_tokens_for_shape_check, str):
774 incorrect_tokens_for_shape_check = torch.as_tensor(
775 self.model.to_single_token(incorrect_tokens_for_shape_check)
776 )
777 elif isinstance(incorrect_tokens_for_shape_check, int):
778 incorrect_tokens_for_shape_check = torch.as_tensor(incorrect_tokens_for_shape_check)
780 if tokens_for_shape_check.shape != incorrect_tokens_for_shape_check.shape:
781 raise ValueError(
782 f"tokens and incorrect_tokens must have the same shape! \
783 (tokens.shape={tokens_for_shape_check.shape}, \
784 incorrect_tokens.shape={incorrect_tokens_for_shape_check.shape})"
785 )
787 # If incorrect_tokens was provided, take the logit difference
788 logit_directions = logit_directions - self.model.tokens_to_residual_directions(
789 incorrect_tokens
790 )
792 scaled_residual_stack = self.apply_ln_to_stack(
793 residual_stack,
794 layer=-1,
795 pos_slice=pos_slice,
796 batch_slice=batch_slice,
797 has_batch_dim=has_batch_dim,
798 )
800 if (
801 has_batch_dim
802 and batch_slice.mode != "int"
803 and scaled_residual_stack.ndim == 4
804 and logit_directions.ndim == 2
805 and logit_directions.shape[0] == scaled_residual_stack.shape[1]
806 ):
807 # Per-example directions must broadcast over positions, not across the batch.
808 logit_directions = logit_directions.unsqueeze(-2)
810 logit_attrs = (scaled_residual_stack * logit_directions).sum(dim=-1)
811 return logit_attrs
813 def decompose_resid(
814 self,
815 layer: Optional[int] = None,
816 mlp_input: bool = False,
817 mode: Literal["all", "mlp", "attn"] = "all",
818 apply_ln: bool = False,
819 pos_slice: Union[Slice, SliceInput] = None,
820 incl_embeds: bool = True,
821 return_labels: bool = False,
822 ) -> Union[
823 Float[torch.Tensor, "layers_covered *batch_and_pos_dims d_model"],
824 Tuple[Float[torch.Tensor, "layers_covered *batch_and_pos_dims d_model"], List[str]],
825 ]:
826 """Decompose the Residual Stream.
828 Decomposes the residual stream input to layer L into a stack of the output of previous
829 layers. The sum of these is the input to layer L (plus embedding and pos embedding). This is
830 useful for attributing model behaviour to different components of the residual stream
832 Args:
833 layer:
834 The layer to take components up to - by default includes
835 resid_pre for that layer and excludes resid_mid and resid_post for that layer.
836 layer==n_layers means to return all layer outputs incl in the final layer, layer==0
837 means just embed and pos_embed. The indices are taken such that this gives the
838 accumulated streams up to the input to layer l
839 mlp_input:
840 Decompose the MLP input rather than the attention input. The current layer's
841 attention contribution is included only for sequential-residual blocks.
842 mode:
843 Values are "all", "mlp" or "attn". "all" returns all
844 components, "mlp" returns only the MLP components, and "attn" returns only the
845 attention components. Defaults to "all". On SSM / hybrid models, blocks without
846 attention contribute their sequence-mixer output (e.g. ``0_linear_attn_out``,
847 ``0_mixer_out``) in the attention slot, and blocks without an MLP contribute no
848 ``mlp_out``.
849 apply_ln:
850 Whether to apply LayerNorm to the stack.
851 pos_slice:
852 A slice object to apply to the pos dimension.
853 Defaults to None, do nothing.
854 incl_embeds:
855 Whether to include embed & pos_embed, whose hooks expose their
856 contributions to the residual stream.
857 return_labels:
858 Whether to return a list of labels for the residual stream components.
859 Useful for labelling graphs.
861 Returns:
862 A tensor of the accumulated residual streams. If `return_labels` is True, also returns
863 a list of labels for the components (as a tuple in the form `(components, labels)`).
864 """
865 if not isinstance(pos_slice, Slice):
866 pos_slice = Slice(pos_slice)
867 pos_slice = cast(Slice, pos_slice) # mypy can't seem to infer this
868 if layer is None or layer == -1:
869 # Default to the residual stream immediately pre unembed
870 layer = self.model.cfg.n_layers
871 assert isinstance(layer, int)
873 incl_attn = mode != "mlp"
874 incl_mlp = mode != "attn" and not self.model.cfg.attn_only
875 components_list = []
876 labels = []
877 if incl_embeds: 877 ↛ 885line 877 didn't jump to line 885 because the condition on line 877 was always true
878 if self.has_embed: 878 ↛ 881line 878 didn't jump to line 881 because the condition on line 878 was always true
879 components_list = [self["hook_embed"]]
880 labels.append("embed")
881 if self.has_pos_embed: 881 ↛ 885line 881 didn't jump to line 885 because the condition on line 881 was always true
882 components_list.append(self["hook_pos_embed"])
883 labels.append("pos_embed")
885 def add_mixer(l: int) -> None:
886 mixers, mixer_labels = self._mixer_stack(l, Slice(None))
887 components_list.extend(mixers)
888 labels.extend(mixer_labels)
890 def add_attn_slot(l: int) -> None:
891 if self._has_attn(l):
892 components_list.append(self[("attn_out", l)])
893 labels.append(f"{l}_attn_out")
894 elif self._mixer_role(l) == "attn":
895 add_mixer(l)
897 for l in range(layer):
898 if incl_attn:
899 add_attn_slot(l)
900 if incl_mlp:
901 if self._has_mlp(l):
902 components_list.append(self[("mlp_out", l)])
903 labels.append(f"{l}_mlp_out")
904 elif not self._has_attn(l) and self._mixer_role(l) == "mlp":
905 add_mixer(l)
906 if mlp_input and incl_attn and self._mlp_input_includes_attn(layer):
907 add_attn_slot(layer)
908 components_list = [pos_slice.apply(c, dim=-2) for c in components_list]
909 if components_list:
910 components = torch.stack(components_list, dim=0)
911 else:
912 # e.g. mode="mlp" on a model whose blocks have no MLP: an empty, stackable result.
913 empty_src = pos_slice.apply(self[("resid_pre", 0)], dim=-2)
914 components = torch.zeros(
915 0, *empty_src.shape, dtype=empty_src.dtype, device=empty_src.device
916 )
917 if apply_ln:
918 components = self.apply_ln_to_stack(
919 components, layer, pos_slice=pos_slice, mlp_input=mlp_input
920 )
921 if return_labels:
922 return components, labels
923 else:
924 return components
926 def compute_head_results(
927 self,
928 ):
929 """Compute Head Results.
931 Computes and caches the results for each attention head, ie the amount contributed to the
932 residual stream from that head. attn_out for a layer is the sum of head results plus b_O.
933 Intended use is to enable use_attn_results when running and caching the model, but this can
934 be useful if you forget.
936 Existing per-head results are preserved, including those without a batch dimension.
937 Missing or invalid results are recomputed from cached ``hook_z`` and the model's
938 ``W_O`` weights. A per-head contraction avoids materializing the broadcast product
939 over both ``d_head`` and ``d_model``. As in the bridge forward pass, the contraction
940 follows active autocast settings.
942 TransformerBridge exposes ``blocks[i].attn.W_O`` via its component-mapping
943 compatibility shim.
944 """
945 if self._ensure_head_results():
946 logging.warning("Tried to compute head results when they were already cached")
948 def _ensure_head_results(self) -> bool:
949 """Recompute missing or invalid per-head results; True if all were already cached."""
950 expected_ndim = 4 if self.has_batch_dim else 3
951 all_cached = True
952 for layer in range(self.model.cfg.n_layers):
953 # SSM / linear-attention blocks have no heads.
954 if not self._has_attn(layer):
955 continue
956 result_key = f"blocks.{layer}.attn.hook_result"
957 cached_result = self.cache_dict.get(result_key)
958 # Batchless per-head results are valid 3D tensors.
959 if (
960 isinstance(cached_result, torch.Tensor)
961 and cached_result.ndim == expected_ndim
962 and cached_result.shape[-2] == self.model.cfg.n_heads
963 ):
964 continue
965 all_cached = False
967 z = self[("z", layer, "attn")]
968 weights = self.model.blocks[layer].attn.W_O
969 if z.dtype != weights.dtype:
970 # Preserve broadcast promotion for caches collected under autocast.
971 dtype = torch.promote_types(z.dtype, weights.dtype)
972 z, weights = z.to(dtype), weights.to(dtype)
973 result = torch.einsum("...hd,hdm->...hm", z, weights)
974 scale = getattr(self.model.blocks[layer].attn, "_result_contribution_scale", 1.0)
975 self.cache_dict[result_key] = result if scale == 1.0 else result * scale
976 return all_cached
978 def ssm_layers(self, mixer_type: Optional[Union[type, Tuple[type, ...]]] = None) -> List[int]:
979 """Return the block indices whose mixer is an SSM / recurrent mixer.
981 Family-agnostic and purely structural: finds each block's *realized* SSM
982 mixer in its variant slot (``.mixer`` / ``.linear_attn`` / …) via
983 ``find_ssm_mixer``, which excludes a hybrid's passthrough ``.mixer`` on
984 non-SSM layers (e.g. NemotronH attention/MLP/MoE) — no dependence on
985 ``cfg.layers_block_type``.
987 Args:
988 mixer_type: Optional concrete bridge class to filter to (e.g.
989 ``SSM2MixerBridge`` for only Mamba-2 layers).
991 Returns:
992 Ascending list of SSM block indices.
993 """
994 from transformer_lens.model_bridge.generalized_components.ssm_protocol import (
995 find_ssm_mixer,
996 )
998 bridge = self.model
999 layers: List[int] = []
1000 for i, block in enumerate(bridge.blocks):
1001 mixer = find_ssm_mixer(block)
1002 if mixer is None:
1003 continue
1004 if mixer_type is not None and not isinstance(mixer, mixer_type):
1005 continue
1006 layers.append(i)
1007 return layers
1009 def _over_ssm_layers(
1010 self,
1011 fn: Callable[[Any, int], torch.Tensor],
1012 mixer_type: Optional[Union[type, Tuple[type, ...]]] = None,
1013 ) -> Union[torch.Tensor, Dict[int, torch.Tensor]]:
1014 """Apply ``fn(mixer, layer_idx)`` over every SSM layer; stack or dict.
1016 The single SSM layer-enumeration used by both ``compute_ssm_state`` and
1017 ``compute_ssm_effective_attention``. Returns a stacked tensor (dim 0 =
1018 layer) when *every* block is an SSM layer, else a ``{layer_idx: result}``
1019 dict over the SSM layers (heterogeneous hybrids).
1020 """
1021 from transformer_lens.model_bridge.generalized_components.ssm_protocol import (
1022 find_ssm_mixer,
1023 )
1025 bridge = self.model
1026 indices = self.ssm_layers(mixer_type=mixer_type)
1027 if not indices: 1027 ↛ 1028line 1027 didn't jump to line 1028 because the condition on line 1027 was never true
1028 raise RuntimeError(
1029 "No SSM mixer layers found. Use an SSM / hybrid bridge and "
1030 "run_with_cache first (gated-delta-net needs use_cache=False)."
1031 )
1032 results: Dict[int, torch.Tensor] = {
1033 i: fn(cast(Any, find_ssm_mixer(bridge.blocks[i])), i) for i in indices
1034 }
1035 if indices == list(range(len(bridge.blocks))):
1036 return torch.stack([results[i] for i in indices], dim=0)
1037 return results
1039 def compute_ssm_effective_attention(
1040 self,
1041 layer: Optional[int] = None,
1042 include_dt_scaling: bool = False,
1043 per_state_coord: bool = False,
1044 ) -> Union[torch.Tensor, Dict[int, torch.Tensor]]:
1045 """Materialize SSM effective attention for one or all SSM layers, any family.
1047 The single discovery surface for effective attention across Mamba-1,
1048 Mamba-2, and gated-delta-net layers; dispatches to each layer's mixer
1049 ``compute_effective_attention`` regardless of family. Family-specific
1050 options are forwarded only to mixers whose signature accepts them.
1052 Args:
1053 layer: Specific block index, or None for every SSM layer.
1054 include_dt_scaling: Forwarded to Mamba-1/Mamba-2 mixers (the
1055 reconstruction form); gated-delta-net does not accept it.
1056 per_state_coord: Forwarded to Mamba-1 only (per-state-coordinate
1057 matrices). Setting it True for another family raises ValueError.
1059 Returns:
1060 A per-layer matrix for a single ``layer``; for ``layer=None`` a
1061 stacked tensor (dim 0 = layer) when every block is an SSM layer, else
1062 a ``{layer_idx: matrix}`` dict over the SSM layers.
1064 Raises:
1065 TypeError: If the requested ``layer`` has no SSM mixer.
1066 ValueError: If an option is set that the target mixer does not support.
1067 RuntimeError: If ``layer=None`` finds no SSM layers.
1068 """
1069 import inspect
1071 from transformer_lens.model_bridge.generalized_components.ssm_protocol import (
1072 find_ssm_mixer,
1073 )
1075 def _call(mixer: Any, layer_idx: int) -> torch.Tensor:
1076 fn = cast(Any, mixer).compute_effective_attention
1077 params = inspect.signature(fn).parameters
1078 kwargs: Dict[str, Any] = {}
1079 for name, value in (
1080 ("include_dt_scaling", include_dt_scaling),
1081 ("per_state_coord", per_state_coord),
1082 ):
1083 if name in params:
1084 kwargs[name] = value
1085 elif value:
1086 raise ValueError(
1087 f"{type(mixer).__name__}.compute_effective_attention does not "
1088 f"support {name}=True."
1089 )
1090 result: torch.Tensor = fn(cache=self, layer_idx=layer_idx, **kwargs)
1091 return result
1093 if layer is not None:
1094 single = find_ssm_mixer(self.model.blocks[layer])
1095 if single is None:
1096 raise TypeError(f"Block {layer} has no SSM mixer (no compute_effective_attention).")
1097 return _call(single, layer)
1098 return self._over_ssm_layers(_call)
1100 def compute_ssm_state(
1101 self,
1102 layer: Optional[int] = None,
1103 time_step: Optional[int] = None,
1104 ) -> Union[torch.Tensor, Dict[int, torch.Tensor]]:
1105 """Reconstruct the recurrent SSM state ``S`` from this cache.
1107 The single discovery surface for recurrent state across families —
1108 ``SSMMixerBridge`` (Mamba-1), ``SSM2MixerBridge`` (Mamba-2) and
1109 ``GatedDeltaNetBridge`` (gated delta rule) each reconstruct it — mirroring
1110 ``compute_head_results``. Read-only post-hoc reconstruction from cached
1111 hooks (no forward re-run); requires an SSM / SSM-hybrid bridge cached via
1112 ``run_with_cache`` (gated-delta-net additionally needs ``use_cache=False``
1113 so its interior hooks fire). See the mixer's ``compute_ssm_state`` for the
1114 recurrence, shapes, and the ``time_step`` memory bound; state shape is
1115 family-specific, so ``layer=None`` returns a dict except when every block
1116 shares one mixer type.
1118 Args:
1119 layer: Specific block index, or None for every SSM-state layer.
1120 time_step: Optional single position (memory-bounded); None for all.
1122 Returns:
1123 A per-layer state tensor for a single ``layer``; for ``layer=None`` a
1124 stacked tensor (dim 0 = layer) when every block is an SSM-state layer,
1125 else a ``{layer_idx: state}`` dict over those layers.
1127 Raises:
1128 TypeError: If the requested ``layer`` has no state-reconstructing mixer.
1129 RuntimeError: If ``layer=None`` finds no such layers.
1130 """
1131 from transformer_lens.model_bridge.generalized_components import (
1132 GatedDeltaNetBridge,
1133 SSM2MixerBridge,
1134 SSMMixerBridge,
1135 )
1136 from transformer_lens.model_bridge.generalized_components.ssm_protocol import (
1137 find_ssm_mixer,
1138 )
1140 # Every recurrent family reconstructs S_t from its cached interior hooks.
1141 state_mixers = (SSMMixerBridge, SSM2MixerBridge, GatedDeltaNetBridge)
1143 def _call(mixer: Any, layer_idx: int) -> torch.Tensor:
1144 state: torch.Tensor = cast(Any, mixer).compute_ssm_state(
1145 self, layer_idx=layer_idx, time_step=time_step
1146 )
1147 return state
1149 if layer is not None:
1150 single = find_ssm_mixer(self.model.blocks[layer])
1151 if not isinstance(single, state_mixers):
1152 raise TypeError(
1153 f"Block {layer} has no state-reconstructing SSM mixer; "
1154 "compute_ssm_state supports Mamba-1 / Mamba-2 / gated-delta-net."
1155 )
1156 return _call(single, layer)
1157 return self._over_ssm_layers(_call, mixer_type=state_mixers)
1159 def _post_norm_map(
1160 self, layer: int, norm_name: str, pos_slice: Slice
1161 ) -> Optional[Tuple[torch.Tensor, Optional[torch.Tensor], bool, Optional[torch.Tensor]]]:
1162 """Cached-scale affine map ``(s, w, centers, b)`` of a post-sublayer norm, or None.
1164 With ``s`` fixed, ``norm(x) = center(x) / s * w + b`` is affine, so each component of
1165 the sublayer output contributes ``center(x_i) / s * w`` and the block adds ``b`` once.
1166 """
1167 norm = self.model.blocks[layer]._modules.get(norm_name)
1168 if norm is None:
1169 return None
1170 key = f"blocks.{layer}.{norm_name}.hook_scale"
1171 if norm._modules.get("hook_scale") is None:
1172 # Leaving it unmapped would silently return pre-norm contributions.
1173 raise KeyError(
1174 f"blocks.{layer}.{norm_name} is a post-sublayer norm with no hook_scale (not "
1175 f"bridged as a normalization component), so head and neuron contributions "
1176 f"cannot be mapped through it on this architecture."
1177 )
1178 try:
1179 cached_scale = self[key]
1180 except KeyError as e:
1181 raise KeyError(
1182 f"Post-sublayer norm scale not found at '{key}'. Head and neuron decompositions "
1183 f"on post-norm architectures divide by it; include it in run_with_cache's "
1184 f"names_filter."
1185 ) from e
1186 scale = pos_slice.apply(cached_scale, dim=-2)
1187 weight = getattr(norm, "weight", None)
1188 if weight is not None and getattr(norm, "uses_weight_offset", False):
1189 weight = 1.0 + weight
1190 centers = not getattr(norm, "uses_rms_norm", False)
1191 return scale, weight, centers, getattr(norm, "bias", None)
1193 @staticmethod
1194 def _apply_post_norm_map(
1195 x: torch.Tensor, scale: torch.Tensor, weight: Optional[torch.Tensor], centers: bool
1196 ) -> torch.Tensor:
1197 """``center(x) / scale * weight`` over the last (d_model) axis; ``scale`` broadcasts."""
1198 input_dtype = x.dtype
1199 if centers: 1199 ↛ 1200line 1199 didn't jump to line 1200 because the condition on line 1199 was never true
1200 x = x - x.mean(dim=-1, keepdim=True)
1201 x = x / scale
1202 x = x * weight if weight is not None else x
1203 # The fp32 scale would otherwise promote half-precision stacks; the norm casts back too.
1204 return x.to(input_dtype)
1206 def _post_norm_bias_correction(
1207 self, layer: int, mlp_input: bool, include_mlp_biases: bool, pos_slice: Slice
1208 ) -> Optional[torch.Tensor]:
1209 """Per-position ``accumulated_bias`` fix: post-norm blocks add ``norm_map(b) + norm_b``."""
1210 correction: Optional[torch.Tensor] = None
1211 sublayers = [(l, "attn") for l in range(layer)]
1212 if include_mlp_biases:
1213 sublayers += [(l, "mlp") for l in range(layer)]
1214 if mlp_input and layer < self.model.cfg.n_layers and self._mlp_input_includes_attn(layer):
1215 sublayers.append((layer, "attn"))
1216 for l, kind in sublayers:
1217 post = self._post_norm_map(l, "ln1_post" if kind == "attn" else "ln2_post", pos_slice)
1218 if post is None:
1219 continue
1220 scale, weight, centers, norm_bias = post
1221 block = self.model.blocks[l]
1222 if kind == "attn":
1223 # Same lookup as accumulated_bias, so the raw bias it added is the one replaced.
1224 out_bias = getattr(self.model, "_get_block_variant_bias")(block)
1225 else:
1226 out_bias = getattr(block.mlp, "b_out", None) if "mlp" in block._modules else None
1227 raw = torch.zeros(self.model.cfg.d_model, device=scale.device, dtype=scale.dtype)
1228 if out_bias is not None:
1229 raw = out_bias.to(device=scale.device, dtype=scale.dtype)
1230 mapped = self._apply_post_norm_map(raw, scale, weight, centers)
1231 if norm_bias is not None: 1231 ↛ 1232line 1231 didn't jump to line 1232 because the condition on line 1231 was never true
1232 mapped = mapped + norm_bias.to(device=scale.device)
1233 delta = (mapped - raw) * getattr(block, "residual_contribution_scale", 1.0)
1234 correction = delta if correction is None else correction + delta
1235 return correction
1237 def stack_head_results(
1238 self,
1239 layer: int = -1,
1240 return_labels: bool = False,
1241 incl_remainder: bool = False,
1242 pos_slice: Union[Slice, SliceInput] = None,
1243 apply_ln: bool = False,
1244 ) -> Union[
1245 Float[torch.Tensor, "num_components *batch_and_pos_dims d_model"],
1246 Tuple[Float[torch.Tensor, "num_components *batch_and_pos_dims d_model"], List[str]],
1247 ]:
1248 """Stack Head Results.
1250 Returns a stack of all head results (ie residual stream contribution) up to layer L. A good
1251 way to decompose the outputs of attention layers into attribution by specific heads. Note
1252 that the num_components axis has length layer x n_heads ((layer head_index) in einops
1253 notation). On SSM / hybrid models only attention layers contribute heads; the other
1254 blocks' outputs are part of the remainder.
1256 Args:
1257 layer:
1258 Layer index - heads at all layers strictly before this are included. layer must be
1259 in [1, n_layers-1], or any of (n_layers, -1, None), which all mean the final layer.
1260 return_labels:
1261 Whether to also return a list of labels of the form "L0H0" for the heads.
1262 incl_remainder:
1263 Whether to return a final term which is "the rest of the residual stream".
1264 pos_slice:
1265 A slice object to apply to the pos dimension. Defaults to None, do nothing.
1266 apply_ln:
1267 Whether to apply LayerNorm to the stack.
1268 """
1269 if not isinstance(pos_slice, Slice):
1270 pos_slice = Slice(pos_slice)
1271 pos_slice = cast(Slice, pos_slice) # mypy can't seem to infer this
1272 if layer is None or layer == -1:
1273 # Default to the residual stream immediately pre unembed
1274 layer = self.model.cfg.n_layers
1276 # Same contract as stack_neuron_results: layer=0 is the whole-model case (remainder reads
1277 # resid_post of layer -1, the final layer). Anything below it would wrap the remainder
1278 # target to an arbitrary late layer via __getitem__, silently returning the wrong
1279 # residual stream with no heads in the stack.
1280 if incl_remainder and layer < 0:
1281 raise ValueError(
1282 f"layer must be >= 0 with incl_remainder=True (-1/None mean n_layers); got {layer}."
1283 )
1285 # Idempotent; cleans up stale Bridge entries without the 'already cached' warning,
1286 # which is only meaningful for direct compute_head_results callers.
1287 self._ensure_head_results()
1289 components: Any = []
1290 labels = []
1291 for l in range(layer):
1292 # SSM / linear-attention blocks have no heads; their output lands in the remainder.
1293 if not self._has_attn(l):
1294 continue
1295 # Note that this has shape batch x pos x head_index x d_model
1296 result = pos_slice.apply(self[("result", l, "attn")], dim=-3)
1297 post = self._post_norm_map(l, "ln1_post", pos_slice)
1298 if post is not None:
1299 scale, weight, centers, _ = post
1300 result = self._apply_post_norm_map(result, scale.unsqueeze(-2), weight, centers)
1301 components.append(result)
1302 labels.extend([f"L{l}H{h}" for h in range(self.model.cfg.n_heads)])
1303 if components:
1304 components = torch.cat(components, dim=-2)
1305 components = einops.rearrange(
1306 components,
1307 "... concat_head_index d_model -> concat_head_index ... d_model",
1308 )
1309 if incl_remainder:
1310 remainder = pos_slice.apply(
1311 self[("resid_post", layer - 1)], dim=-2
1312 ) - components.sum(dim=0)
1313 components = torch.cat([components, remainder[None]], dim=0)
1314 labels.append("remainder")
1315 elif incl_remainder:
1316 # There are no components, so the remainder is the entire thing.
1317 components = torch.cat(
1318 [pos_slice.apply(self[("resid_post", layer - 1)], dim=-2)[None]], dim=0
1319 )
1320 labels.append("remainder")
1321 else:
1322 # If this is called with layer 0, we return an empty tensor of the right shape to be
1323 # stacked correctly. This uses the shape of hook_embed, which is pretty janky since it
1324 # assumes embed is in the cache. But it's hard to explicitly code the shape, since it
1325 # depends on the pos slice, whether we have a batch dim, etc. And it's pretty messy!
1326 empty_src = pos_slice.apply(self["hook_embed"], dim=-2)
1327 components = torch.zeros(
1328 0,
1329 *empty_src.shape,
1330 dtype=empty_src.dtype,
1331 device=empty_src.device,
1332 )
1334 if apply_ln:
1335 components = self.apply_ln_to_stack(components, layer, pos_slice=pos_slice)
1337 if return_labels:
1338 return components, labels
1339 else:
1340 return components
1342 def stack_activation(
1343 self,
1344 activation_name: str,
1345 layer: int = -1,
1346 sublayer_type: Optional[str] = None,
1347 ) -> Float[torch.Tensor, "layers_covered ..."]:
1348 """Stack Activations.
1350 Flexible way to stack activations with a given name.
1352 Args:
1353 activation_name:
1354 The name of the activation to be stacked
1355 layer:
1356 'Layer index - heads' at all layers strictly before this are included. layer must be
1357 in [1, n_layers-1], or any of (n_layers, -1, None), which all mean the final layer.
1358 sublayer_type:
1359 The sub layer type of the activation, passed to utils.get_act_name. Can normally be
1360 inferred.
1361 incl_remainder:
1362 Whether to return a final term which is "the rest of the residual stream".
1363 """
1364 if layer is None or layer == -1:
1365 # Default to the residual stream immediately pre unembed
1366 layer = self.model.cfg.n_layers
1368 components = []
1369 for l in range(layer):
1370 components.append(self[(activation_name, l, sublayer_type)])
1372 return torch.stack(components, dim=0)
1374 def get_neuron_results(
1375 self,
1376 layer: int,
1377 neuron_slice: Union[Slice, SliceInput] = None,
1378 pos_slice: Union[Slice, SliceInput] = None,
1379 project_output_onto: Optional[torch.Tensor] = None,
1380 ) -> torch.Tensor:
1381 """Get Neuron Results.
1383 Get the results of for neurons in a specific layer (i.e, how much each neuron contributes to
1384 the residual stream). Does it for the subset of neurons specified by neuron_slice, defaults
1385 to all of them. Does *not* cache these because it's expensive in space and cheap to compute.
1387 Args:
1388 layer:
1389 Layer index.
1390 neuron_slice:
1391 Slice of the neuron.
1392 pos_slice:
1393 Slice of the positions.
1394 project_output_onto:
1395 Optional ``[d_model]`` or ``[d_model, num_outputs]`` projection. Contracted with
1396 ``W_out`` *before* the per-neuron expansion so the ``[..., d_mlp, d_model]``
1397 intermediate is never materialized.
1399 Returns:
1400 Last-dim is ``d_model`` (default), ``num_outputs`` (2D projection), or squeezed
1401 (1D projection).
1402 """
1403 if not isinstance(neuron_slice, Slice):
1404 neuron_slice = Slice(neuron_slice)
1405 if not isinstance(pos_slice, Slice):
1406 pos_slice = Slice(pos_slice)
1408 neuron_acts = self[("post", layer, "mlp")]
1409 block = self.model.blocks[layer]
1410 W_out = block.mlp.W_out
1411 contribution_scale = getattr(block, "residual_contribution_scale", 1.0)
1412 if pos_slice is not None: 1412 ↛ 1416line 1412 didn't jump to line 1416 because the condition on line 1412 was always true
1413 # Note - order is important, as Slice.apply *may* collapse a dimension, so this ensures
1414 # that position dimension is -2 when we apply position slice
1415 neuron_acts = pos_slice.apply(neuron_acts, dim=-2)
1416 if neuron_slice is not None: 1416 ↛ 1419line 1416 didn't jump to line 1419 because the condition on line 1416 was always true
1417 neuron_acts = neuron_slice.apply(neuron_acts, dim=-1)
1418 W_out = neuron_slice.apply(W_out, dim=0)
1419 if contribution_scale != 1.0:
1420 neuron_acts = neuron_acts * contribution_scale
1421 post = self._post_norm_map(layer, "ln2_post", pos_slice)
1422 if post is not None:
1423 scale, weight, centers, _ = post
1424 # center(a_n W_out_n) / s * w = (a_n / s) * center(W_out_n) * w
1425 W_out = self._apply_post_norm_map(W_out, torch.ones(()), weight, centers)
1426 neuron_acts = (neuron_acts / scale).to(neuron_acts.dtype)
1427 if project_output_onto is None:
1428 return neuron_acts[..., None] * W_out
1429 # W_out: [d_mlp, d_model]; project: [d_model] or [d_model, n_outs]
1430 projected = W_out @ project_output_onto
1431 if project_output_onto.ndim == 1:
1432 return neuron_acts * projected
1433 return neuron_acts[..., None] * projected
1435 def _uses_ln_centering(self, layer: Optional[int]) -> bool:
1436 """Use the target norm's semantics, not just the block normalization family."""
1437 is_final = layer is None or layer == self.model.cfg.n_layers
1438 return self.model.cfg.normalization_type in ["LN", "LNPre"] and not (
1439 is_final and getattr(self.model.cfg, "final_rms", False)
1440 )
1442 def _get_cached_ln_scale(
1443 self,
1444 layer: Optional[int],
1445 mlp_input: bool,
1446 pos_slice: Slice,
1447 batch_slice: Optional[Slice] = None,
1448 ) -> torch.Tensor:
1449 """Look up the cached LN scale and apply pos/batch slicing. Surfaces a clearer error
1450 when the expected hook isn't in the cache (some non-decoder-only architectures expose
1451 LN scale at a different path or not at all).
1452 """
1453 norm = "ln2" if mlp_input else "ln1"
1454 blocks = getattr(self.model, "blocks", None)
1455 block = (
1456 blocks[layer]
1457 if blocks is not None and layer is not None and layer != self.model.cfg.n_layers
1458 else None
1459 )
1460 if (
1461 mlp_input
1462 and block is not None
1463 and layer is not None
1464 and not self._mlp_input_includes_attn(layer)
1465 and getattr(block, "ln2", None) is None
1466 and getattr(block, "ln2_post", None) is None
1467 ):
1468 # Shared-norm parallel blocks feed the MLP from ln1, not a separate ln2.
1469 norm = "ln1"
1470 if layer == self.model.cfg.n_layers or layer is None:
1471 key = "ln_final.hook_scale"
1472 else:
1473 key = f"blocks.{layer}.{norm}.hook_scale"
1474 try:
1475 scale = self[key]
1476 except KeyError as e:
1477 if (
1478 block is not None
1479 and getattr(block, norm, None) is None
1480 and getattr(block, f"{norm}_post", None) is not None
1481 ):
1482 sublayer = "MLP" if mlp_input else "attention"
1483 raise KeyError(
1484 f"Layer {layer} has no {norm} (pre-{sublayer} norm): this architecture "
1485 f"normalizes sublayer outputs ({norm}_post) instead, so a mid-layer cached-scale "
1486 f"LN is undefined. Use apply_ln=False, or apply LN at the final layer."
1487 ) from e
1488 raise KeyError(
1489 f"Cached LN scale not found at '{key}'. apply_ln operations require the model "
1490 f"to have cached this hook (some non-decoder-only architectures expose LN scale "
1491 f"under different module paths)."
1492 ) from e
1493 scale = pos_slice.apply(scale, dim=-2)
1494 if batch_slice is not None and self.has_batch_dim:
1495 scale = batch_slice.apply(scale)
1496 return scale
1498 def _stack_neuron_results_apply_ln_projected(
1499 self,
1500 layer: int,
1501 pos_slice: Slice,
1502 neuron_slice: Slice,
1503 project_2d: torch.Tensor,
1504 mlp_input: bool = False,
1505 ) -> torch.Tensor:
1506 """LN-applied neuron stack with projection folded in — no d_mlp×d_model intermediate.
1508 Analytical formula (LN models, cached scale ``s``):
1509 ``LN_s(a_n * W_out_n) @ p = (a_n / s) * (W_out_n @ p - mean(W_out_n) * sum_p)``
1510 RMS models drop the ``mean(W_out_n) * sum_p`` term (no centering). ``s`` is the
1511 MLP-input norm scale when ``mlp_input`` is set, else the ln1 scale.
1512 """
1513 scale = self._get_cached_ln_scale(layer, mlp_input=mlp_input, pos_slice=pos_slice)
1515 apply_centering = self._uses_ln_centering(layer)
1516 sum_p = project_2d.sum(dim=0) if apply_centering else None # [n_outs]
1518 components: list = []
1519 for l in range(layer):
1520 if not self._has_mlp(l):
1521 continue
1522 block = self.model.blocks[l]
1523 W_out_l = block.mlp.W_out # [d_mlp, d_model]
1524 contribution_scale = getattr(block, "residual_contribution_scale", 1.0)
1525 post = self._post_norm_map(l, "ln2_post", pos_slice)
1526 if post is not None:
1527 post_scale, post_weight, post_centers, _ = post
1528 W_out_l = self._apply_post_norm_map(
1529 W_out_l, torch.ones(()), post_weight, post_centers
1530 )
1531 W_out_l_sliced = neuron_slice.apply(W_out_l, dim=0)
1532 W_proj_l = W_out_l_sliced @ project_2d # [d_mlp, n_outs]
1533 if apply_centering:
1534 assert sum_p is not None # set when apply_centering, narrow for mypy
1535 W_means_l = W_out_l_sliced.mean(dim=-1) # [d_mlp]
1536 lin_form_l = W_proj_l - W_means_l[:, None] * sum_p[None, :]
1537 else:
1538 lin_form_l = W_proj_l
1539 if contribution_scale != 1.0:
1540 lin_form_l = lin_form_l * contribution_scale
1541 a_l = self[("post", l, "mlp")]
1542 a_l = pos_slice.apply(a_l, dim=-2)
1543 a_l = neuron_slice.apply(a_l, dim=-1)
1544 if post is not None:
1545 a_l = a_l / post_scale
1546 # (a_l / s)[..., None] is [..., d_mlp, 1]; broadcast with lin_form_l [d_mlp, n_outs]
1547 components.append((a_l / scale)[..., None] * lin_form_l)
1548 if not components:
1549 empty_src = pos_slice.apply(self["hook_embed"], dim=-2)
1550 return torch.zeros(
1551 0,
1552 *empty_src.shape[:-1],
1553 project_2d.shape[-1],
1554 dtype=torch.promote_types(
1555 torch.promote_types(empty_src.dtype, scale.dtype), project_2d.dtype
1556 ),
1557 device=empty_src.device,
1558 )
1559 stacked = torch.cat(components, dim=-2)
1560 return einops.rearrange(
1561 stacked, "... concat_neuron_index n_outs -> concat_neuron_index ... n_outs"
1562 )
1564 def stack_neuron_results(
1565 self,
1566 layer: int,
1567 pos_slice: Union[Slice, SliceInput] = None,
1568 neuron_slice: Union[Slice, SliceInput] = None,
1569 return_labels: bool = False,
1570 incl_remainder: bool = False,
1571 apply_ln: bool = False,
1572 project_output_onto: Optional[torch.Tensor] = None,
1573 mlp_input: bool = False,
1574 ) -> Union[torch.Tensor, Tuple[torch.Tensor, List[str]]]:
1575 """Stack Neuron Results
1577 Returns a stack of all neuron results (ie residual stream contribution) up to layer L - ie
1578 the amount each individual neuron contributes to the residual stream. Also returns a list of
1579 labels of the form "L0N0" for the neurons. A good way to decompose the outputs of MLP layers
1580 into attribution by specific neurons.
1582 Note that doing this for all neurons is SUPER expensive on GPU memory and only works for
1583 small models or short inputs. Pass ``project_output_onto`` to fold the projection into the
1584 per-neuron expansion and avoid the ``[..., d_mlp, d_model]`` intermediate.
1586 Args:
1587 layer:
1588 Layer index - heads at all layers strictly before this are included. layer must be
1589 in [1, n_layers]. ``layer=0`` follows the negative-index convention: the neuron
1590 stack is empty and with ``incl_remainder=True`` the remainder is the final layer's
1591 residual stream (``resid_post`` of layer ``n_layers - 1``), i.e. the whole model.
1592 pos_slice:
1593 Slice of the positions.
1594 neuron_slice:
1595 Slice of the neurons. An int or an integer-mode ``Slice(n)`` selects a single
1596 neuron and is treated like ``[n]``.
1597 return_labels:
1598 Whether to also return a list of labels of the form "L0N0" for the neurons.
1599 incl_remainder:
1600 Whether to return a final term which is "the rest of the residual stream".
1601 apply_ln:
1602 Whether to apply LayerNorm to the stack.
1603 project_output_onto:
1604 Optional ``[d_model]`` or ``[d_model, num_outputs]`` tensor. When set, each
1605 component's last d_model dim is replaced by the projection (memory-efficient for
1606 direction analyses; see ``get_neuron_results``). Combined with ``apply_ln=True``,
1607 the projection is folded into the analytical cached-scale LN so the
1608 ``[..., d_mlp, d_model]`` intermediate is still never materialized.
1609 mlp_input:
1610 Treat the stack as the input to ``layer``'s MLP rather than its attention, as in
1611 ``decompose_resid``: with ``incl_remainder=True`` the remainder fills the stack up to
1612 ``resid_mid`` for sequential blocks or ``resid_pre`` for parallel blocks.
1613 With ``apply_ln=True`` the scale of the norm feeding the MLP is used
1614 (ln2, or ln1 on shared-norm parallel blocks).
1615 The neurons stacked are unchanged.
1616 """
1617 if layer is None or layer == -1:
1618 # Default to the residual stream immediately pre unembed
1619 layer = self.model.cfg.n_layers
1621 # layer=0 is the documented whole-model case (remainder reads resid_post of layer -1, the
1622 # final layer). Anything below it would wrap the remainder target to an arbitrary late
1623 # layer via __getitem__, silently returning the wrong residual stream.
1624 if incl_remainder and layer < 0:
1625 raise ValueError(
1626 f"layer must be >= 0 with incl_remainder=True (-1/None mean n_layers); got {layer}."
1627 )
1629 # Layers are concatenated along the neuron axis, so it must not collapse. unwrap turns an
1630 # int into [n] but leaves a Slice as is, so an integer-mode Slice(n) is rebuilt as [n]
1631 # here. A new Slice is made, so the caller's Slice still collapses elsewhere.
1632 neuron_slice = Slice.unwrap(neuron_slice)
1633 if neuron_slice.mode == "int":
1634 assert isinstance(neuron_slice.slice, int) # narrow for mypy
1635 neuron_slice = Slice([neuron_slice.slice])
1636 if not isinstance(pos_slice, Slice):
1637 pos_slice = Slice(pos_slice)
1639 project_2d, squeeze_projected = _normalize_projection_to_2d(project_output_onto)
1641 d_mlp = self.model.cfg.d_mlp
1642 assert d_mlp is not None, "model.cfg.d_mlp must be set"
1643 neuron_labels = neuron_slice.apply(torch.arange(d_mlp), dim=0)
1645 # Mamba / NemotronH blocks without an MLP have no neurons.
1646 mlp_layers = [l for l in range(layer) if self._has_mlp(l)]
1647 for l in mlp_layers:
1648 modules = self._block_modules(l)
1649 if modules is not None and "mlp" not in modules:
1650 names = ", ".join(n for n in modules if not n.startswith(("hook", "_")))
1651 raise NotImplementedError(
1652 f"blocks.{l} writes an MLP-side output without an `mlp` submodule "
1653 f"({names}), so its neurons cannot be expanded. Use "
1654 "expand_neurons=False or decompose_resid instead."
1655 )
1656 labels = [f"L{l}N{h}" for l in mlp_layers for h in neuron_labels]
1657 if mlp_input and layer < self.model.cfg.n_layers:
1658 stream = "resid_mid" if self._mlp_input_includes_attn(layer) else "resid_pre"
1659 remainder_target = (stream, layer)
1660 else:
1661 remainder_target = ("resid_post", layer - 1)
1662 components: Any
1663 ln_folded = apply_ln and project_2d is not None
1664 if ln_folded:
1665 assert project_2d is not None # narrow for mypy
1666 # Analytical LN+projection — no d_mlp×d_model intermediate.
1667 components = self._stack_neuron_results_apply_ln_projected(
1668 layer, pos_slice, neuron_slice, project_2d, mlp_input=mlp_input
1669 )
1670 if incl_remainder:
1671 # Linearity of cached-scale LN: remainder is LN_s(target) @ p - sum(neurons).
1672 target = pos_slice.apply(self[remainder_target], dim=-2)
1673 target_ln = self.apply_ln_to_stack(
1674 target[None], layer, pos_slice=pos_slice, mlp_input=mlp_input
1675 )[0]
1676 remainder = target_ln @ project_2d
1677 if components.shape[0] > 0:
1678 remainder = remainder - components.sum(dim=0)
1679 components = torch.cat([components, remainder[None]], dim=0)
1680 labels.append("remainder")
1681 else:
1682 per_layer: list = []
1683 for l in mlp_layers:
1684 per_layer.append(
1685 self.get_neuron_results(
1686 l,
1687 pos_slice=pos_slice,
1688 neuron_slice=neuron_slice,
1689 project_output_onto=project_2d,
1690 )
1691 )
1692 if per_layer:
1693 components = torch.cat(per_layer, dim=-2)
1694 components = einops.rearrange(
1695 components,
1696 "... concat_neuron_index d_model -> concat_neuron_index ... d_model",
1697 )
1698 if incl_remainder:
1699 remainder_full = pos_slice.apply(self[remainder_target], dim=-2)
1700 if project_2d is not None:
1701 remainder_full = remainder_full @ project_2d
1702 remainder = remainder_full - components.sum(dim=0)
1703 components = torch.cat([components, remainder[None]], dim=0)
1704 labels.append("remainder")
1705 elif incl_remainder:
1706 remainder_full = pos_slice.apply(self[remainder_target], dim=-2)
1707 if project_2d is not None:
1708 remainder_full = remainder_full @ project_2d
1709 components = torch.cat([remainder_full[None]], dim=0)
1710 labels.append("remainder")
1711 else:
1712 empty_src = pos_slice.apply(self["hook_embed"], dim=-2)
1713 empty_shape = tuple(empty_src.shape)
1714 empty_dtype = empty_src.dtype
1715 if project_2d is not None:
1716 # Shape only: a real matmul would demand the cache and direction share a dtype.
1717 empty_shape = (*empty_shape[:-1], project_2d.shape[-1])
1718 empty_dtype = torch.promote_types(empty_dtype, project_2d.dtype)
1719 components = torch.zeros(
1720 0, *empty_shape, dtype=empty_dtype, device=empty_src.device
1721 )
1723 if apply_ln:
1724 components = self.apply_ln_to_stack(
1725 components, layer, pos_slice=pos_slice, mlp_input=mlp_input
1726 )
1728 if squeeze_projected:
1729 components = components.squeeze(-1)
1731 if return_labels:
1732 return components, labels
1733 else:
1734 return components
1736 def apply_ln_to_stack(
1737 self,
1738 residual_stack: Float[torch.Tensor, "num_components *batch_and_pos_dims d_model"],
1739 layer: Optional[int] = None,
1740 mlp_input: bool = False,
1741 pos_slice: Union[Slice, SliceInput] = None,
1742 batch_slice: Union[Slice, SliceInput] = None,
1743 has_batch_dim: bool = True,
1744 recompute_ln: bool = False,
1745 ) -> Float[torch.Tensor, "num_components *batch_and_pos_dims_out d_model"]:
1746 """Apply Layer Norm to a Stack.
1748 Takes a stack of components of the residual stream (eg outputs of decompose_resid or
1749 accumulated_resid), treats them as the input to a specific layer, and applies the layer norm
1750 scaling of that layer to them, using the cached scale factors - simulating what that
1751 component of the residual stream contributes to that layer's input.
1753 The layernorm scale is global across the entire residual stream for each layer, batch
1754 element and position, which is why we need to use the cached scale factors rather than just
1755 applying a new LayerNorm.
1757 When recompute_ln=True and the target layer is the final layer (unembed), each
1758 component is normalized using stats recomputed from that component; use this for logit lens
1759 analysis. When recompute_ln=False, a single cached scale is used for all components.
1761 If the model does not use LayerNorm or RMSNorm, it returns the residual stack unchanged.
1763 Args:
1764 residual_stack:
1765 A tensor, whose final dimension is d_model. The other trailing dimensions are
1766 assumed to be the same as the stored hook_scale - which may or may not include batch
1767 or position dimensions.
1768 layer:
1769 The layer we're taking the input to. In [0, n_layers], n_layers means the unembed.
1770 None maps to the n_layers case, ie the unembed.
1771 mlp_input:
1772 Whether the input is to the MLP or attention. The MLP uses ln2 when present,
1773 or ln1 on shared-norm parallel blocks. Defaults to False, ie ln1.
1774 If layer==n_layers, must be False, and we use ln_final
1775 pos_slice:
1776 The slice to take of positions, if residual_stack is not over the full context, None
1777 means do nothing. It is assumed that pos_slice has already been applied to
1778 residual_stack, and this is only applied to the scale. See utils.Slice for details.
1779 Defaults to None, do nothing.
1780 batch_slice:
1781 The slice to take on the batch dimension. Defaults to None, do nothing.
1782 has_batch_dim:
1783 Whether residual_stack has a batch dimension.
1784 recompute_ln:
1785 If True and target layer is the unembed (final layer), apply the final layer norm
1786 to each component with statistics recomputed from that component. Defaults to False.
1788 """
1789 if not isinstance(pos_slice, Slice):
1790 pos_slice = Slice(pos_slice)
1791 if not isinstance(batch_slice, Slice):
1792 batch_slice = Slice(batch_slice)
1794 if layer is None or layer == -1:
1795 # Default to the residual stream immediately pre unembed
1796 layer = self.model.cfg.n_layers
1798 if has_batch_dim:
1799 # Apply batch slice to the stack
1800 residual_stack = batch_slice.apply(residual_stack, dim=1)
1802 # Checked only after slicing so callers like logit_attrs still get their
1803 # batch_slice honoured on models without LayerNorm/RMSNorm.
1804 if self.model.cfg.normalization_type not in ["LN", "LNPre", "RMS", "RMSPre"]:
1805 return residual_stack
1807 # Logit lens: apply final layer norm to each component with recomputed statistics
1808 if recompute_ln and layer == self.model.cfg.n_layers and hasattr(self.model, "ln_final"):
1809 ln_final = self.model.ln_final
1810 results = []
1811 for i in range(residual_stack.shape[0]):
1812 x = residual_stack[i]
1813 original_shape = x.shape
1814 # ln_final expects (batch, pos, d_model); restore missing structural dimensions
1815 if not has_batch_dim:
1816 x = x.unsqueeze(0)
1817 if x.ndim == 2:
1818 x = x.unsqueeze(1)
1819 out = ln_final(x)
1820 results.append(out.reshape(original_shape))
1821 return torch.stack(results, dim=0)
1823 # Final RMSNorm must not inherit the block LayerNorm centering convention.
1824 if self._uses_ln_centering(layer):
1825 residual_stack = residual_stack - residual_stack.mean(dim=-1, keepdim=True)
1827 # Shape is [batch, position, 1] or [position, 1]; final dim is a dummy for broadcasting.
1828 scale = self._get_cached_ln_scale(layer, mlp_input, pos_slice, batch_slice)
1830 return residual_stack / scale
1832 def get_full_resid_decomposition(
1833 self,
1834 layer: Optional[int] = None,
1835 mlp_input: bool = False,
1836 expand_neurons: bool = True,
1837 apply_ln: bool = False,
1838 pos_slice: Union[Slice, SliceInput] = None,
1839 return_labels: bool = False,
1840 project_output_onto: Optional[torch.Tensor] = None,
1841 ) -> Union[torch.Tensor, Tuple[torch.Tensor, List[str]]]:
1842 """Get the full Residual Decomposition.
1844 Decomposes the residual stream that is input into some layer into its
1845 constituent components: every attention head result, every neuron (or
1846 MLP layer) result, the embeddings, and the accumulated biases.
1848 The returned tensor stacks components along ``dim=0`` in this order:
1850 1. Attention head results, layer-by-layer (``L * n_heads`` rows; attention
1851 layers only on SSM / hybrid models)
1852 2. Sequence-mixer results of blocks without attention heads (SSM / hybrid
1853 models only; one row per mixer, e.g. ``0_linear_attn_out``, output bias
1854 excluded since it is in the ``bias`` row). MLP-type passthrough mixers
1855 (NemotronH) appear here only when ``expand_neurons=True``; otherwise they
1856 are part of the MLP rows below.
1857 3. Neuron / MLP results (only if ``cfg.attn_only=False`` and
1858 ``layer > 0``; ``d_mlp`` rows per block with an MLP when
1859 ``expand_neurons=True``, else one row per MLP output)
1860 4. ``embed`` (1 row, including any post-embedding runtime multiplier)
1861 5. ``pos_embed`` (1 row, if the model has positional embeddings)
1862 6. ``bias`` (1 row, the accumulated layer biases)
1864 ``return_labels=True`` returns a list of strings in the same order, so
1865 ``labels[i]`` always names ``stack[i]``. If you need to extract a
1866 specific component, slice by label rather than by hard-coded index —
1867 the row counts depend on ``layer``, ``expand_neurons``,
1868 ``cfg.attn_only``, and whether the model has positional embeddings.
1870 Args:
1871 layer:
1872 The layer we're inputting into. layer is in [0, n_layers], if layer==n_layers (or
1873 None) we're inputting into the unembed (the entire stream), if layer==0 then it's
1874 just embed and pos_embed
1875 mlp_input:
1876 Are we inputting to the MLP in that layer or the attn? Must be False for final
1877 layer, since that's the unembed.
1878 expand_neurons:
1879 Whether to expand the MLP outputs to give every neuron's result or just return the
1880 MLP layer outputs.
1881 apply_ln:
1882 Whether to apply LayerNorm to the stack.
1883 pos_slice:
1884 Slice of the positions to take.
1885 return_labels:
1886 Whether to return the labels.
1887 project_output_onto:
1888 Optional ``[d_model]`` or ``[d_model, num_outputs]`` projection. Folded in
1889 *before* the per-neuron expansion, so the ``[..., d_mlp, d_model]`` intermediate
1890 is never materialized (memory saving applies only with ``expand_neurons=True``).
1891 Combined with ``apply_ln=True``, the projection is fused into the analytical
1892 cached-scale LN so the same memory benefit holds. Output last-dim is squeezed
1893 for a 1D projection; ``num_outputs`` for 2D.
1894 """
1895 if layer is None or layer == -1:
1896 # Default to the residual stream immediately pre unembed
1897 layer = self.model.cfg.n_layers
1898 assert layer is not None # keep mypy happy
1900 if not isinstance(pos_slice, Slice):
1901 pos_slice = Slice(pos_slice)
1903 project_2d, squeeze_projected = _normalize_projection_to_2d(project_output_onto)
1904 # When both apply_ln and projection are requested, LN is applied per-component (in
1905 # d_model space for the small ones, analytically for neurons) before projection, so the
1906 # final apply_ln_to_stack call is skipped — last-dim is already n_outs.
1907 ln_folded = apply_ln and project_2d is not None
1909 def _ln_then_project(stack: torch.Tensor) -> torch.Tensor:
1910 stack = self.apply_ln_to_stack(stack, layer, pos_slice=pos_slice, mlp_input=mlp_input)
1911 return stack @ project_2d if project_2d is not None else stack
1913 head_stack, head_labels = self.stack_head_results(
1914 layer + int(mlp_input and self._mlp_input_includes_attn(layer)),
1915 pos_slice=pos_slice,
1916 return_labels=True,
1917 )
1918 if ln_folded:
1919 head_stack = _ln_then_project(head_stack)
1920 elif project_2d is not None:
1921 head_stack = head_stack @ project_2d
1922 labels = head_labels
1923 components = [head_stack]
1924 # Blocks without attention heads: add each mixer output whole. Its output bias is dropped
1925 # here because the `bias` row below already accumulates it. MLP-type mixers come from
1926 # the MLP path when it is not expanded into neurons.
1927 mixer_layers = [l for l in range(layer) if expand_neurons or self._mixer_role(l) == "attn"]
1928 if mlp_input and self._mlp_input_includes_attn(layer) and self._mixer_role(layer) == "attn":
1929 mixer_layers.append(layer)
1930 mixer_list: List[torch.Tensor] = []
1931 for l in mixer_layers:
1932 mixers, mixer_labels = self._mixer_stack(l, pos_slice, subtract_bias=True)
1933 mixer_list.extend(mixers)
1934 labels.extend(mixer_labels)
1935 if mixer_list:
1936 mixer_stack = torch.stack(mixer_list, dim=0)
1937 if ln_folded:
1938 mixer_stack = _ln_then_project(mixer_stack)
1939 elif project_2d is not None: 1939 ↛ 1940line 1939 didn't jump to line 1940 because the condition on line 1939 was never true
1940 mixer_stack = mixer_stack @ project_2d
1941 components.append(mixer_stack)
1942 if not self.model.cfg.attn_only and layer > 0:
1943 if expand_neurons:
1944 # Only ask stack_neuron_results to apply LN when we want the fused analytical
1945 # path (ln_folded). For the unfolded case the outer apply_ln_to_stack handles it.
1946 neuron_stack, neuron_labels = self.stack_neuron_results(
1947 layer,
1948 pos_slice=pos_slice,
1949 return_labels=True,
1950 apply_ln=ln_folded,
1951 project_output_onto=project_2d,
1952 mlp_input=mlp_input,
1953 )
1954 labels.extend(neuron_labels)
1955 components.append(neuron_stack)
1956 else:
1957 # Get the stack of just the MLP outputs
1958 # mlp_input included for completeness, but it doesn't actually matter, since it's
1959 # just for MLP outputs
1960 mlp_stack, mlp_labels = self.decompose_resid(
1961 layer,
1962 mlp_input=mlp_input,
1963 pos_slice=pos_slice,
1964 incl_embeds=False,
1965 mode="mlp",
1966 return_labels=True,
1967 )
1968 if ln_folded:
1969 mlp_stack = _ln_then_project(mlp_stack)
1970 elif project_2d is not None:
1971 mlp_stack = mlp_stack @ project_2d
1972 labels.extend(mlp_labels)
1973 components.append(mlp_stack)
1975 if self.has_embed: 1975 ↛ 1983line 1975 didn't jump to line 1983 because the condition on line 1975 was always true
1976 embed = pos_slice.apply(self["hook_embed"], -2)[None]
1977 if ln_folded:
1978 embed = _ln_then_project(embed)
1979 elif project_2d is not None:
1980 embed = embed @ project_2d
1981 labels.append("embed")
1982 components.append(embed)
1983 if self.has_pos_embed:
1984 pos_embed = pos_slice.apply(self["pos_embed"], -2)[None]
1985 if ln_folded:
1986 pos_embed = _ln_then_project(pos_embed)
1987 elif project_2d is not None:
1988 pos_embed = pos_embed @ project_2d
1989 labels.append("pos_embed")
1990 components.append(pos_embed)
1991 # If we didn't expand the neurons, the MLP biases are already included in the MLP outputs.
1992 bias_full = self.model.accumulated_bias(layer, mlp_input, include_mlp_biases=expand_neurons)
1993 bias_correction = self._post_norm_bias_correction(
1994 layer, mlp_input, include_mlp_biases=expand_neurons, pos_slice=pos_slice
1995 )
1996 if ln_folded:
1997 # Expand bias to per-position d_model shape so LN can center, then project.
1998 expand_shape: tuple = (1,) + tuple(head_stack.shape[1:-1]) + (self.model.cfg.d_model,)
1999 bias_d_model = bias_full.expand(expand_shape)
2000 if bias_correction is not None:
2001 bias_d_model = bias_d_model + bias_correction
2002 bias = _ln_then_project(bias_d_model)
2003 else:
2004 if bias_correction is not None:
2005 bias_full = bias_full + bias_correction
2006 if project_2d is not None:
2007 # Bias is [d_model], so project post-hoc for shape compatibility — no memory win here.
2008 bias_full = bias_full @ project_2d
2009 bias = bias_full.expand((1,) + head_stack.shape[1:])
2010 labels.append("bias")
2011 components.append(bias)
2012 residual_stack = torch.cat(components, dim=0)
2013 if apply_ln and not ln_folded:
2014 residual_stack = self.apply_ln_to_stack(
2015 residual_stack, layer, pos_slice=pos_slice, mlp_input=mlp_input
2016 )
2018 if squeeze_projected:
2019 residual_stack = residual_stack.squeeze(-1)
2021 if return_labels:
2022 return residual_stack, labels
2023 else:
2024 return residual_stack