Coverage for transformer_lens/head_detector.py: 96%
92 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"""Head Detector.
3Utilities for detecting specific types of heads (e.g. previous token heads).
4"""
6import logging
7from collections import defaultdict
8from typing import Dict, List, Optional, Tuple, Union, cast
10import numpy as np
11import torch
12from typing_extensions import Literal, get_args
14from transformer_lens.ActivationCache import ActivationCache
15from transformer_lens.model_protocol import TransformerLensModel
16from transformer_lens.utilities import is_lower_triangular, is_square
18HeadName = Literal["previous_token_head", "duplicate_token_head", "induction_head"]
19HEAD_NAMES = cast(List[HeadName], get_args(HeadName))
20ErrorMeasure = Literal["abs", "mul"]
22LayerHeadTuple = Tuple[int, int]
23LayerToHead = Dict[int, List[int]]
25INVALID_HEAD_NAME_ERR = (
26 f"detection_pattern must be a Tensor or one of head names: {HEAD_NAMES}; got %s"
27)
29CACHE_WITH_SEQ_LIST_ERR = (
30 "A single cache cannot be reused across multiple prompts, so `cache` is not\n"
31 "supported when `seq` is a list. Pass one prompt at a time, or omit `cache`\n"
32 "and let each prompt be run separately."
33)
35EMPTY_SEQ_LIST_ERR = "`seq` is an empty list; pass at least one prompt."
37SEQ_LEN_ERR = "The sequence must be non-empty and must fit within the model's context window."
39DET_PAT_NOT_SQUARE_ERR = "The detection pattern must be a lower triangular matrix of shape (sequence_length, sequence_length); sequence_length=%d; got detection pattern of shape %s"
42def detect_head(
43 model: TransformerLensModel,
44 seq: Union[str, List[str]],
45 detection_pattern: Union[torch.Tensor, HeadName],
46 heads: Optional[Union[List[LayerHeadTuple], LayerToHead]] = None,
47 cache: Optional[ActivationCache] = None,
48 *,
49 exclude_bos: bool = False,
50 exclude_current_token: bool = False,
51 error_measure: ErrorMeasure = "mul",
52) -> torch.Tensor:
53 """Search for a Particular Type of Attention Head.
55 Searches the model (or a set of specific heads, for circuit analysis) for a particular type of
56 attention head. This head is specified by a detection pattern, a (sequence_length,
57 sequence_length) tensor representing the attention pattern we expect that type of attention head
58 to show. The detection pattern can be also passed not as a tensor, but as a name of one of
59 pre-specified types of attention head (see `HeadName` for available patterns), in which case the
60 tensor is computed within the function itself.
62 There are two error measures available for quantifying the match between the detection pattern
63 and the actual attention pattern.
65 1. `"mul"` (default) multiplies both tensors element-wise and divides the sum of the result by
66 the sum of the attention pattern. Typically, the detection pattern should in this case
67 contain only ones and zeros, which allows a straightforward interpretation of the score: how
68 big fraction of this head's attention is allocated to these specific query-key pairs? Using
69 values other than 0 or 1 is not prohibited but will raise a warning (which can be disabled,
70 of course).
72 2. `"abs"` calculates the mean element-wise absolute difference between the detection pattern
73 and the actual attention pattern. The "raw result" ranges from 0 to 2 where lower score
74 corresponds to greater accuracy. Subtracting it from 1 maps that range to (-1, 1) interval,
75 with 1 being perfect match and -1 perfect mismatch.
77 Which one should you use?
79 `"mul"` is likely better for quick or exploratory investigations. For precise examinations where
80 you're trying to reproduce as much functionality as possible or really test your understanding
81 of the attention head, you probably want to switch to `"abs"`.
83 The advantage of `"abs"` is that you can make more precise predictions, and have that measured
84 in the score. You can predict, for instance, 0.2 attention to X, and 0.8 attention to Y, and
85 your score will be better if your prediction is closer. The "mul" metric does not allow this,
86 you'll get the same score if attention is 0.2, 0.8 or 0.5, 0.5 or 0.8, 0.2.
88 Args:
89 model: Model being used.
90 seq: String or list of strings being fed to the model. A list is scored one prompt at a
91 time and averaged; with a tensor `detection_pattern`, every prompt in it must tokenise
92 to the pattern's sequence length.
93 head_name: Name of an existing head in HEAD_NAMES we want to check. Must pass either a
94 head_name or a detection_pattern, but not both!
95 detection_pattern: (sequence_length, sequence_length) Tensor representing what attention
96 pattern corresponds to the head we're looking for or the name of a pre-specified head.
97 Currently available heads are: `["previous_token_head", "duplicate_token_head",
98 "induction_head"]`.
99 heads: If specific attention heads is given here, all other heads' score is set to -1.
100 Useful for IOI-style circuit analysis. Heads can be specified as a list of tuples (layer,
101 head) or a dictionary mapping a layer to heads within that layer that we want to
102 analyze.
103 cache: Include the cache to save time if you want.
104 exclude_bos: Exclude attention paid to the beginning of sequence token.
105 exclude_current_token: Exclude attention paid to the current token.
106 error_measure: `"mul"` for using element-wise multiplication. `"abs"` for using absolute
107 values of element-wise differences as the error measure.
109 Returns:
110 Tensor representing the score for each attention head.
111 """
113 # Validate error_measure
115 assert error_measure in get_args(
116 ErrorMeasure
117 ), f"Invalid error_measure={error_measure}; valid values are {get_args(ErrorMeasure)}"
119 if isinstance(seq, list):
120 # One cache cannot serve multiple prompts, and each prompt needs its own
121 # batch dimension removed before its score can be averaged.
122 if cache is not None:
123 raise ValueError(CACHE_WITH_SEQ_LIST_ERR)
124 if not seq:
125 raise ValueError(EMPTY_SEQ_LIST_ERR)
126 batch_scores = [
127 detect_head(
128 model,
129 batch_seq,
130 detection_pattern,
131 heads=heads,
132 exclude_bos=exclude_bos,
133 exclude_current_token=exclude_current_token,
134 error_measure=error_measure,
135 )
136 for batch_seq in seq
137 ]
138 return torch.stack(batch_scores).mean(0)
140 cfg = model.cfg
141 tokens = model.to_tokens(seq).to(cfg.device)
142 seq_len = tokens.shape[-1]
144 # Validate detection pattern if it's a string
145 if isinstance(detection_pattern, str):
146 assert detection_pattern in HEAD_NAMES, INVALID_HEAD_NAME_ERR % detection_pattern
147 detection_pattern = cast(
148 torch.Tensor,
149 eval(f"get_{detection_pattern}_detection_pattern(tokens.cpu())"),
150 ).to(cfg.device)
152 # if we're using "mul", detection_pattern should consist of zeros and ones
153 if error_measure == "mul" and not set(detection_pattern.unique().tolist()).issubset({0, 1}): 153 ↛ 154line 153 didn't jump to line 154 because the condition on line 153 was never true
154 logging.warning(
155 "Using detection pattern with values other than 0 or 1 with error_measure 'mul'"
156 )
158 # Validate inputs and detection pattern shape
159 assert 1 < tokens.shape[-1] < cfg.n_ctx, SEQ_LEN_ERR
160 assert (
161 is_lower_triangular(detection_pattern) and seq_len == detection_pattern.shape[0]
162 ), DET_PAT_NOT_SQUARE_ERR % (seq_len, detection_pattern.shape)
164 if cache is None:
165 _, cache = model.run_with_cache(tokens, remove_batch_dim=True)
167 if heads is None:
168 layer2heads = {layer_i: list(range(cfg.n_heads)) for layer_i in range(cfg.n_layers)}
169 elif isinstance(heads, list): 169 ↛ 174line 169 didn't jump to line 174 because the condition on line 169 was always true
170 layer2heads = defaultdict(list)
171 for layer, head in heads:
172 layer2heads[layer].append(head)
173 else:
174 layer2heads = heads
176 matches = -torch.ones(cfg.n_layers, cfg.n_heads, dtype=cfg.dtype)
178 for layer, layer_heads in layer2heads.items():
179 # [n_heads q_pos k_pos]
180 layer_attention_patterns = cache["pattern", layer, "attn"]
181 for head in layer_heads:
182 head_attention_pattern = layer_attention_patterns[head, :, :]
183 head_score = compute_head_attention_similarity_score(
184 head_attention_pattern,
185 detection_pattern=detection_pattern,
186 exclude_bos=exclude_bos,
187 exclude_current_token=exclude_current_token,
188 error_measure=error_measure,
189 )
190 matches[layer, head] = head_score
191 return matches
194# Previous token head
195def get_previous_token_head_detection_pattern(
196 tokens: torch.Tensor, # [batch (1) x pos]
197) -> torch.Tensor:
198 """Outputs a detection score for [previous token heads](https://dynalist.io/d/n2ZWtnoYHrU1s4vnFSAQ519J#z=0O5VOHe9xeZn8Ertywkh7ioc).
200 Args:
201 tokens: Tokens being fed to the model.
202 """
203 detection_pattern = torch.zeros(tokens.shape[-1], tokens.shape[-1])
204 # Adds a diagonal of 1's below the main diagonal.
205 detection_pattern[1:, :-1] = torch.eye(tokens.shape[-1] - 1)
206 return torch.tril(detection_pattern)
209# Duplicate token head
210def get_duplicate_token_head_detection_pattern(
211 tokens: torch.Tensor, # [batch (1) x pos]
212) -> torch.Tensor:
213 """Outputs a detection score for [duplicate token heads](https://dynalist.io/d/n2ZWtnoYHrU1s4vnFSAQ519J#z=2UkvedzOnghL5UHUgVhROxeo).
215 Args:
216 sequence: String being fed to the model.
217 """
218 # [pos x pos]
219 token_pattern = tokens.repeat(tokens.shape[-1], 1).numpy()
221 # If token_pattern[i][j] matches its transpose, then token j and token i are duplicates.
222 eq_mask = np.equal(token_pattern, token_pattern.T).astype(int)
224 np.fill_diagonal(eq_mask, 0) # Current token is always a duplicate of itself. Ignore that.
225 detection_pattern = eq_mask.astype(int)
226 return torch.tril(torch.as_tensor(detection_pattern).float())
229# Induction head
230def get_induction_head_detection_pattern(
231 tokens: torch.Tensor, # [batch (1) x pos]
232) -> torch.Tensor:
233 """Outputs a detection score for [induction heads](https://dynalist.io/d/n2ZWtnoYHrU1s4vnFSAQ519J#z=_tFVuP5csv5ORIthmqwj0gSY).
235 Args:
236 sequence: String being fed to the model.
237 """
238 duplicate_pattern = get_duplicate_token_head_detection_pattern(tokens)
240 # Shift all items one to the right
241 shifted_tensor = torch.roll(duplicate_pattern, shifts=1, dims=1)
243 # Replace first column with 0's
244 # we don't care about bos but shifting to the right moves the last column to the first,
245 # and the last column might contain non-zero values.
246 zeros_column = torch.zeros(duplicate_pattern.shape[0], 1)
247 result_tensor = torch.cat((zeros_column, shifted_tensor[:, 1:]), dim=1)
248 return torch.tril(result_tensor)
251def get_supported_heads() -> None:
252 """Print the supported head names."""
253 print(f"Supported heads: {HEAD_NAMES}")
256def compute_head_attention_similarity_score(
257 attention_pattern: torch.Tensor, # [q_pos k_pos]
258 detection_pattern: torch.Tensor, # [seq_len seq_len] (seq_len == q_pos == k_pos)
259 *,
260 exclude_bos: bool,
261 exclude_current_token: bool,
262 error_measure: ErrorMeasure,
263) -> float:
264 """Compute the similarity between `attention_pattern` and `detection_pattern`.
266 Args:
267 attention_pattern: Lower triangular matrix (Tensor) representing the attention pattern of a particular attention head.
268 detection_pattern: Lower triangular matrix (Tensor) representing the attention pattern we are looking for.
269 exclude_bos: `True` if the beginning-of-sentence (BOS) token should be omitted from comparison. `False` otherwise.
270 exclude_bcurrent_token: `True` if the current token at each position should be omitted from comparison. `False` otherwise.
271 error_measure: "abs" for using absolute values of element-wise differences as the error measure. "mul" for using element-wise multiplication (legacy code).
272 """
273 assert is_square(
274 attention_pattern
275 ), f"Attention pattern is not square; got shape {attention_pattern.shape}"
277 # mul
279 if error_measure == "mul":
280 # Clone before masking. attention_pattern is a view into the caller's
281 # ActivationCache, so masking in place permanently corrupts the cached
282 # pattern: its rows stop summing to 1 and every later use of that cache
283 # silently reads modified activations.
284 if exclude_bos or exclude_current_token:
285 attention_pattern = attention_pattern.clone()
286 if exclude_bos:
287 attention_pattern[:, 0] = 0
288 if exclude_current_token:
289 attention_pattern.fill_diagonal_(0)
290 score = attention_pattern * detection_pattern
291 return (score.sum() / attention_pattern.sum()).item()
293 # abs
295 abs_diff = (attention_pattern - detection_pattern).abs()
296 assert (abs_diff - torch.tril(abs_diff).to(abs_diff.device)).sum() == 0
298 size = len(abs_diff)
299 if exclude_bos:
300 abs_diff[:, 0] = 0
301 if exclude_current_token:
302 abs_diff.fill_diagonal_(0)
304 return 1 - round((abs_diff.mean() * size).item(), 3)
305 return 1 - round((abs_diff.mean() * size).item(), 3)