Infrastructure: hooks and residual stream decomposition
Instrument your GPT with named hooks in each component and verify equivalent logits after importing it into TransformerLens. Implement direct logit attribution by freezing the final normalization so embeddings, heads and MLP contributions sum exactly to the logits. Visualize and classify attention patterns across heads.
After this lesson you can
- Add named hooks to the model to capture and replace activations.
- Load the model into TransformerLens and verify matching logits.
- Implement direct logit attribution and check that the contributions sum to the logits.
- Classify attention heads using quantitative pattern metrics.
Before you start
Open the model without confusing observation with cause
Give a GPT the sentence “When Mary and John went to the store, John gave a drink to” and it predicts “ Mary”. This is the indirect object identification task, and we know quite a bit about how GPT-2 small solves it. But this project’s question is different: what happens inside your model? Answering with evidence requires two things built in this first step. First, the ability to inspect and modify any intermediate activation without touching the rest of the computation. Second, exact accounting of how a logit is formed from each component’s writes.
Neither is yet a causal explanation. Seeing a head attend to “ Mary” does not say that head causes the prediction, and additive accounting describes the run that occurred, not what would happen if we removed a piece. Separating those questions is this lesson’s thread. The interpretability methods taxonomy calls the first observational methods and the second interventions; systematic interventions arrive in p11-l05.
The object of study is the model from p06-l06: the GPT-2 small architecture (12 blocks, 12 heads, width 768) with your vocabulary of 513 IDs, saved as weights-only copies model-*.pt. The lab reads it from the folder you specify. If you do not have it yet, use a declared alternative: published GPT-2 small, which has exactly the same architecture (the model with which you checked parity), or the same architecture with random weights for equivalence tests. The two data figures on this page (attribution and head gallery) are measured on GPT-2 small by the lab itself, not your model; both accept the JSON file generated by your run and then display yours.
The residual stream is a sum of writes
In a pre-LN transformer (the GPT-2 variant; see pre-norm versus post-norm), each block reads the current state through LayerNorm and adds its result to the state. Call the vector at one position on entry to block (in the lesson code, hook_resid_pre), with . The block performs
and the initial state is , the embedding of token plus the position embedding . Nothing a block writes is overwritten afterward: things are only added. This is the residual stream, which Elhage and colleagues describe as a shared communication channel. Each component reads from the channel with one projection and writes to it with another.
Multi-head attention adds another sum. With heads of dimension (the of general notation; we reserve for the head index), each head produces at position a vector , where is its attention pattern and the value at position . Multi-head attention concatenates the vectors and applies plus bias . If we split into column blocks, with , block multiplication gives
Proof
By induction on : from the two block equations, and attention output is by block multiplication. Summing differences from to and adding yields the formula: a telescoping sum.
∎The equality is exact for vectors calculated in this run. Each and is a nonlinear function of the previous residual, so the decomposition does not say how they would change if something earlier changed. But once calculated, they add. GPT-2 small has writes plus the twelve biases , all sharing the same 768-dimensional channel. A numbering convention before continuing: in formulas blocks run from 1 to , but in code and literature layers and heads are numbered from 0, so is blocks.{ℓ−1}.hook_resid_pre and “head 9.9” is the tenth head of the tenth layer.
Where to look: named hook points
Reading those writes requires intercepting them. A named hook point for capturing and replacing activations is an identity module placed at a precise computation site with a stable name, on which functions are registered to read or change its output. In PyTorch this is the module hooks machinery: module.register_forward_hook(f) ensures that after each module(x) call, f(module, args, output) runs; if f returns a tensor, it replaces the output (PyTorch documentation). The returned handle allows its removal.
The name is a contract, not a decorative label. It must fix layer, component, shape and what is included: whether a head write is before or after , whether a LayerNorm output already includes and . Our instrumented model uses exactly TransformerLens names and shapes (the HookedTransformer workflow), allowing name-by-name comparison with that library.
The figure makes two things clear. First, only some activations can be added to the residual. hook_z has components per head and does not live in residual space; hook_result is the same vector after its block and does live there. Confusing them produces sums with wrong dimensions or, worse, dimensions correct by chance. Second, memory. With tokens, saving 220 tensors in float32 costs 2.22 GiB, and half are scores and patterns growing with (the quadratic cost of attention). Attribution needs the two embeddings, hook_result of each layer, hook_mlp_out and the final scale, occupying 474 MiB; hook_attn_out is also a write, but is the sum of its layer’s heads plus , and saving it alongside them would double count. A cache is designed for the question.
Three rules so a hook does not lie
- Observing means copying. Save
output.detach().clone().detach()cuts the graph but shares memory with the model’s tensor (detach documentation): if something changes it later, your cache changes too. - Replacing means returning a new tensor. An intervention clones, modifies the copy and returns it. Modifying
outputin place changes what other functions already saved and can break autograd. - Always remove. Handles are removed in an
finallyblock even if the pass raises an exception. A forgotten notebook hook turns the next cell into an intervened experiment that looks normal.
Two more details. eval() and torch.no_grad() are not the same: the former changes behavior of modules such as dropout, the latter only avoids building the graph. Observation needs both. And if one point runs multiple times in a pass (with KV caching, or a model reusing a block), a dictionary with one entry per name silently overwrites; our cache turns it into an error.
Lab, part one: loading and instrumentation
Cells are local (PyTorch with GPU) and form a complete full-size lab; each page opens its own kernel, so this lesson uses nothing loaded on others. Requirements: torch, psutil, tiktoken, huggingface_hub and safetensors (and transformers only for the GPT-2 alternative’s tokenizer). Environment variables:
| Variable | Default | Use |
|---|---|---|
P11_CKPT | p06_pretrain/runs/full/snapshots | Folder (recursive) with p06-l06 model-*.pt, or a specific file. The latest is selected. |
P06_DATA_DIR | p06_data | p06-l02 manifest and vocabulary, to tokenize with your BPE. |
P11_FALLBACK | gpt2 | If no checkpoint: gpt2 (published GPT-2 small, about 550 MB the first time) or aleatorio. |
P11_OUT | p11_lab | Where atribucion.json and galeria.json for the figures are written. |
P11_MAX_RSS_GB | 3.5 | Process memory limit; if exceeded, the watchdog aborts the kernel. |
The checkpoint loads with torch.load(..., weights_only=True), which reconstructs only tensors and basic types: deserializing arbitrary .pt with pickle can execute code, as explained in p06-l06. Weights go straight to GPU.
import json, math, os, threading, time
from contextlib import contextmanager
from pathlib import Path
import psutil
import torch
from torch import nn
import torch.nn.functional as F
# Vigilante de memoria: si el proceso supera el límite, se aborta antes de saturar el equipo.
LIMITE_RAM = float(os.environ.get('P11_MAX_RSS_GB', '3.5')) * 2**30
def _vigilar():
proceso = psutil.Process(os.getpid())
while True:
if proceso.memory_info().rss > LIMITE_RAM:
print('Memoria por encima del límite: se aborta el proceso', flush=True)
os._exit(3)
time.sleep(0.5)
if '_VIGILANTE' not in globals():
_VIGILANTE = threading.Thread(target=_vigilar, daemon=True)
_VIGILANTE.start()
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
CKPT = Path(os.environ.get('P11_CKPT', 'p06_pretrain/runs/full/snapshots'))
P06_DATA = Path(os.environ.get('P06_DATA_DIR', 'p06_data'))
ALTERNATIVA = os.environ.get('P11_FALLBACK', 'gpt2') # 'gpt2' o 'aleatorio'
OUT = Path(os.environ.get('P11_OUT', 'p11_lab')).resolve()
GPT2_REPO, GPT2_REV = 'openai-community/gpt2', '607a30d783dfa663caf39e06633721c8d4cfcd7e'
TRANSPUESTOS = ('attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight')
def ultimo_snapshot(ruta):
if ruta.is_file():
return ruta
candidatos = sorted(ruta.rglob('model-*.pt')) if ruta.is_dir() else []
return candidatos[-1] if candidatos else None
def tokenizador_p06(datos):
"""Vocabulario BPE de p06-l02 como codificador de tiktoken (mismos rangos y regex)."""
import hashlib, tiktoken
manifiesto = json.loads((datos / 'manifest.json').read_text(encoding='utf-8'))
crudo = (datos / manifiesto['vocab_file']).read_bytes()
assert hashlib.sha256(crudo).hexdigest() == manifiesto['vocab_sha256']
vocab = json.loads(crudo)
rangos = {bytes.fromhex(k): v for k, v in vocab['vocab_hex'].items()}
enc = tiktoken.Encoding('p06', pat_str=vocab['pretokenization'], mergeable_ranks=rangos,
special_tokens={vocab['special_literal']: manifiesto['eot_id']})
return enc, manifiesto['eot_id']
def pesos_gpt2():
"""GPT-2 small publicado, con los nombres y la orientación nn.Linear del GPT de p06-l03."""
from huggingface_hub import hf_hub_download
from safetensors.torch import load_file
fichero = hf_hub_download(GPT2_REPO, 'model.safetensors', revision=GPT2_REV)
crudo = load_file(fichero, device=DEVICE) # directamente en la GPU
sd = {}
for k, v in crudo.items():
if k.endswith(('.attn.bias', '.attn.masked_bias')):
continue # máscaras guardadas, no parámetros
k = k if k.startswith('transformer.') else 'transformer.' + k
sd[k] = v.T.contiguous() if k.endswith(TRANSPUESTOS) else v
return sd
def pesos_aleatorios(vocab=50257, contexto=1024, capas=12, d=768, semilla=0):
"""Misma arquitectura e inicialización que p06-l03, sin entrenar."""
g = torch.Generator(device=DEVICE).manual_seed(semilla)
normal = lambda *forma, std=0.02: torch.randn(*forma, generator=g, device=DEVICE) * std
sd = {'transformer.wte.weight': normal(vocab, d), 'transformer.wpe.weight': normal(contexto, d)}
for l in range(capas):
p = f'transformer.h.{l}.'
for ln in ('ln_1', 'ln_2'):
sd[p + ln + '.weight'] = torch.ones(d, device=DEVICE)
sd[p + ln + '.bias'] = torch.zeros(d, device=DEVICE)
for nombre, (salida, entrada) in {'attn.c_attn': (3*d, d), 'attn.c_proj': (d, d),
'mlp.c_fc': (4*d, d), 'mlp.c_proj': (d, 4*d)}.items():
std = 0.02 / math.sqrt(2*capas) if nombre.endswith('c_proj') else 0.02
sd[p + nombre + '.weight'] = normal(salida, entrada, std=std)
sd[p + nombre + '.bias'] = torch.zeros(salida, device=DEVICE)
sd['transformer.ln_f.weight'] = torch.ones(d, device=DEVICE)
sd['transformer.ln_f.bias'] = torch.zeros(d, device=DEVICE)
return sd
snapshot = ultimo_snapshot(CKPT)
if snapshot is not None:
estado = torch.load(snapshot, map_location=DEVICE, weights_only=True)
pesos = {k.removeprefix('_orig_mod.'): v for k, v in estado.get('model', estado).items()
if torch.is_tensor(v)}
CABEZAS = int((estado.get('config') or {}).get('heads', 12))
enc, BOS = tokenizador_p06(P06_DATA)
FUENTE = f'GPT propio: {snapshot.name} (paso {estado.get("step")})'
del estado
else:
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained(GPT2_REPO, revision=GPT2_REV)
class _Enc: # misma interfaz que tiktoken
encode_ordinary = staticmethod(lambda s: tok(s, add_special_tokens=False)['input_ids'])
decode = staticmethod(lambda ids: tok.decode(ids))
enc, BOS, CABEZAS = _Enc(), tok.eos_token_id, 12
if ALTERNATIVA == 'aleatorio':
pesos = pesos_aleatorios()
FUENTE = 'ALTERNATIVA: arquitectura de GPT-2 small con pesos aleatorios (sin entrenar)'
else:
pesos = pesos_gpt2()
FUENTE = f'ALTERNATIVA: GPT-2 small publicado ({GPT2_REPO}@{GPT2_REV[:7]}), no tu modelo'
pesos['lm_head.weight'] = pesos['transformer.wte.weight'] # atado, como en p06-l03
V, D = pesos['transformer.wte.weight'].shape
CAPAS = 1 + max(int(k.split('.')[2]) for k in pesos if k.startswith('transformer.h.'))
print(FUENTE)
print(f'{CAPAS} capas, {CABEZAS} cabezas, d = {D}, vocabulario {V}, contexto '
f'{pesos["transformer.wpe.weight"].shape[0]}, dispositivo {DEVICE}')
print(f'parámetros únicos: {sum(t.numel() for k, t in pesos.items() if k != "lm_head.weight") / 1e6:.2f} M')
def tokens(texto, bos=True):
"""IDs con el token especial delante (el de fin de texto hace de BOS), en el dispositivo."""
return torch.tensor([([BOS] if bos else []) + enc.encode_ordinary(texto)], device=DEVICE)
def piezas(ids):
return [enc.decode([i]) for i in ids[0].tolist()]npm run lab and open the connection link.Published GPT-2 weights use Conv1D, which stores matrices input by output; p06-l03 GPT uses nn.Linear, output by input. Loading transposes those four matrices and keeps your model’s names, so the rest of the lab does not distinguish the two sources. All texts are tokenized with the special end-of-text token prepended: it acts as a fixed first position, like BOS in other models.
The next cell writes the instrumented model from scratch. It has the same submodule structure as class GPT from p06-l03, so it loads the same state_dict without translating anything. Three things change: attention is calculated manually instead of scaled_dot_product_attention (to see the pattern), each head write is calculated separately before summing, and there is an HookPoint at each map site.
class HookPoint(nn.Module):
"""Identidad con nombre: el sitio donde se lee o se sustituye una activación."""
def __init__(self, name):
super().__init__()
self.name = name
def forward(self, x):
return x
class LayerNormH(nn.LayerNorm):
"""LayerNorm escrita a mano para exponer la escala y la entrada normalizada."""
def __init__(self, d, name):
super().__init__(d, eps=1e-5)
self.hook_scale = HookPoint(f'{name}.hook_scale')
self.hook_normalized = HookPoint(f'{name}.hook_normalized')
def forward(self, x):
x = x - x.mean(-1, keepdim=True)
scale = self.hook_scale((x.pow(2).mean(-1, keepdim=True) + self.eps).sqrt())
return self.hook_normalized(x / scale * self.weight + self.bias) # con γ y β, como TransformerLens
class AttentionH(nn.Module):
def __init__(self, d, heads, p):
super().__init__()
self.heads, self.dh = heads, d // heads
self.c_attn, self.c_proj = nn.Linear(d, 3*d), nn.Linear(d, d)
for n in ('q', 'k', 'v', 'attn_scores', 'pattern', 'z', 'result'):
setattr(self, f'hook_{n}', HookPoint(f'{p}.attn.hook_{n}'))
def forward(self, x):
b, t, d = x.shape
q, k, v = (z.view(b, t, self.heads, self.dh) for z in self.c_attn(x).split(d, dim=-1))
q, k, v = self.hook_q(q), self.hook_k(k), self.hook_v(v)
scores = torch.einsum('bqhe,bkhe->bhqk', q, k) / math.sqrt(self.dh)
future = torch.ones(t, t, dtype=torch.bool, device=x.device).triu(1)
scores = self.hook_attn_scores(scores.masked_fill(future, -torch.inf))
pattern = self.hook_pattern(scores.softmax(-1)) # B × H × consulta × clave
z = self.hook_z(torch.einsum('bhqk,bkhe->bqhe', pattern, v)) # B × T × H × d_h
W_O = self.c_proj.weight.view(d, self.heads, self.dh) # columnas de cada cabeza
result = self.hook_result(torch.einsum('bqhe,dhe->bqhd', z, W_O)) # B × T × H × d
return result.sum(2) + self.c_proj.bias # b_O una sola vez por capa
class MLPH(nn.Module):
def __init__(self, d, p):
super().__init__()
self.c_fc, self.c_proj = nn.Linear(d, 4*d), nn.Linear(4*d, d)
self.hook_pre, self.hook_post = HookPoint(f'{p}.mlp.hook_pre'), HookPoint(f'{p}.mlp.hook_post')
def forward(self, x):
h = self.hook_pre(self.c_fc(x))
h = self.hook_post(0.5*h*(1.0 + torch.tanh(math.sqrt(2.0/math.pi)*(h + 0.044715*h**3))))
return self.c_proj(h)
class BlockH(nn.Module):
def __init__(self, d, heads, l):
super().__init__()
p = f'blocks.{l}'
self.ln_1, self.attn = LayerNormH(d, f'{p}.ln1'), AttentionH(d, heads, p)
self.ln_2, self.mlp = LayerNormH(d, f'{p}.ln2'), MLPH(d, p)
for n in ('resid_pre', 'attn_out', 'resid_mid', 'mlp_out', 'resid_post'):
setattr(self, f'hook_{n}', HookPoint(f'{p}.hook_{n}'))
def forward(self, x):
x = self.hook_resid_pre(x)
x = self.hook_resid_mid(x + self.hook_attn_out(self.attn(self.ln_1(x))))
return self.hook_resid_post(x + self.hook_mlp_out(self.mlp(self.ln_2(x))))
class HookedGPT(nn.Module):
"""El GPT de p06-l03 (mismos nombres de pesos) con puntos de enganche con nombre."""
def __init__(self, vocab, context, layers, heads, d):
super().__init__()
self.cfg = dict(vocab=vocab, context=context, layers=layers, heads=heads, d=d)
self.transformer = nn.Module()
self.transformer.wte, self.transformer.wpe = nn.Embedding(vocab, d), nn.Embedding(context, d)
self.transformer.h = nn.ModuleList([BlockH(d, heads, l) for l in range(layers)])
self.transformer.ln_f = LayerNormH(d, 'ln_final')
self.lm_head = nn.Linear(d, vocab, bias=False)
self.lm_head.weight = self.transformer.wte.weight # pesos atados
self.hook_embed, self.hook_pos_embed = HookPoint('hook_embed'), HookPoint('hook_pos_embed')
self.hook_points = {m.name: m for m in self.modules() if isinstance(m, HookPoint)}
def forward(self, ids):
b, t = ids.shape
pos = self.transformer.wpe(torch.arange(t, device=ids.device))[None].expand(b, t, -1)
x = self.hook_embed(self.transformer.wte(ids)) + self.hook_pos_embed(pos)
for block in self.transformer.h:
x = block(x)
return self.lm_head(self.transformer.ln_f(x))
@contextmanager
def hooks(self, fwd):
"""fwd: lista de (nombre, f(activación, nombre)). Si f devuelve un tensor, sustituye."""
handles = []
try:
for name, f in fwd:
handles.append(self.hook_points[name].register_forward_hook(
lambda module, args, out, f=f: f(out, module.name)))
yield self
finally: # también si la pasada lanza una excepción
for h in handles:
h.remove()
def run_with_hooks(self, ids, fwd):
with self.hooks(fwd), torch.no_grad():
return self(ids)
def run_with_cache(self, ids, names=None):
cache = {}
def save(act, name):
assert name not in cache, f'{name} se ejecutó dos veces en la misma pasada'
cache[name] = act.detach().clone() # copia propia, sin grafo
names = self.hook_points if names is None else names
return self.run_with_hooks(ids, [(n, save) for n in names]), cache
with torch.device(DEVICE):
model = HookedGPT(V, pesos['transformer.wpe.weight'].shape[0], CAPAS, CABEZAS, D)
model.load_state_dict(pesos)
model.eval()
del pesos
PROMPT = 'When Mary and John went to the store, John gave a drink to'
a, b = enc.encode_ordinary(' Mary'), enc.encode_ordinary(' John')
k = next(i for i in range(min(len(a), len(b))) if a[i] != b[i]) # primer token en que difieren
x = torch.cat([tokens(PROMPT), torch.tensor([a[:k]], dtype=torch.long, device=DEVICE)], dim=1)
mary, john = a[k], b[k]
with torch.no_grad():
base = model(x)
logits, cache = model.run_with_cache(x)
assert torch.equal(logits, base) # observar no cambia el cálculo
print(f'{len(model.hook_points)} puntos de enganche; caché de {len(cache)} tensores, '
f'{sum(t.numel()*t.element_size() for t in cache.values()) / 2**20:.1f} MiB para {x.shape[1]} tokens')
for n in ('hook_embed', 'blocks.0.attn.hook_q', 'blocks.0.attn.hook_pattern', 'blocks.0.attn.hook_z',
'blocks.0.attn.hook_result', 'blocks.0.mlp.hook_post', 'ln_final.hook_scale'):
print(f' {n:28s} {tuple(cache[n].shape)}')
# Una sustitución que devuelve una copia idéntica no cambia ni un bit.
L_, H_ = min(9, CAPAS - 1), min(9, CABEZAS - 1) # la cabeza 9.9 (o la última que exista)
punto = f'blocks.{L_}.attn.hook_z'
assert torch.equal(model.run_with_hooks(x, [(punto, lambda a, n: a.clone())]), base)
# La trampa: escribir in situ altera lo que otra función ya había guardado sin copiar.
guardado = {}
def sin_copia(a, n): guardado['vista'] = a.detach() # comparte memoria con a
def con_copia(a, n): guardado['copia'] = a.detach().clone()
def anula_in_situ(a, n): a[:, :, H_] = 0 # MAL: modifica el tensor del modelo
with model.hooks([(punto, sin_copia), (punto, con_copia), (punto, anula_in_situ)]), torch.no_grad():
model(x)
print(f'norma de la cabeza {L_}.{H_} guardada sin copia: {guardado["vista"][0, :, H_].norm():.3f}'
f' | con copia: {guardado["copia"][0, :, H_].norm():.3f}')
# La forma correcta: devolver un tensor nuevo.
def anula(a, n):
a = a.clone()
a[:, :, H_] = 0
return a
ablated = model.run_with_hooks(x, [(punto, anula)])
assert all(not hp._forward_hooks for hp in model.hook_points.values()) # nada queda enganchado
assert torch.equal(model.run_with_hooks(x, []), base)
diff = lambda z: (z[0, -1, mary] - z[0, -1, john]).item()
print(f'logit(" Mary") − logit(" John") en la última posición: {diff(base):.3f}; '
f'anulando la salida de la cabeza {L_}.{H_}: {diff(ablated):.3f}')npm run lab and open the connection link.In the short verification run, with the GPT-2 small alternative, the cell finds 220 hook points and the complete 15-token cache occupies 16.7 MiB. The trap is unambiguous: the copy stores head 9.9 at norm 11.773, while the uncopied reference reads 0.000, because the subsequently registered function zeroed that tensor in place and the “cache” was the same tensor. With your vocabulary of 513 IDs, “ Mary” and “ John” may start with the same token (for example the space); the cell adds common tokens to context and compares the first where they differ.
The last number anticipates the central issue. In GPT-2 small, the “ Mary” − “ John” logit difference is 3.362, and zeroing head 9.9 leaves it at 3.387: almost unchanged, even higher. Remember that; shortly we will see that head’s direct contribution to the same difference exceeds 2.
Equivalence with TransformerLens and normalization folding
An interpretability library offers tested caches, interventions and visualizations, but helps only if its model is yours. Converting weights is not copying matrices with similar names. TransformerLens stores per-head projections, , and applies them to row vectors (); nn.Linear stores an matrix with Q, K and V stacked by rows and applies it as . Translation of head takes rows of the Q block and transposes them; are corresponding columns of c_proj, which TransformerLens stores as . A mistaken transpose can preserve shape when dimensions coincide (), so checking shapes is insufficient: compare values.
The project’s required test compares both models’ logits on the same inputs, across several batches and lengths, and each activation with the same name. If something diverges, the first divergent name locates the error. It is useful to run in float64: in float32 two correct implementations summing in different orders differ by about for logits of magnitude 100, and such a discrepancy cannot distinguish a subtle mapping error from rounding. In float64 rounding falls to and any real error stands out.
Folding is an identity, not a new model
TransformerLens often loads processed models. Four transformations change parameters without changing the function (except for a constant in logits), and each has a one-line proof.
- Fold LayerNorm (
fold_ln). If LayerNorm feeds an affine map, , with . Save and , leaving a parameter-free LayerNorm. Centering and scaling remain: the affine part is folded. - Center writes (
center_writing_weights). Everything reading the residual begins with a LayerNorm, which subtracts the coordinate mean. Subtracting each written vector’s mean does not change any read, but changes residual values and write hooks. - Center the readout (
center_unembed). Subtracting the vocabulary mean from each column of adds the same constant to all logits at a position. Softmax is unchanged; absolute logits are not. - Fold value biases (
fold_value_biases). Pattern rows sum to 1, so , and is constant: move it to .hook_resultof each head changes, not the layer sum.
The practical consequence: absolute-logit equality is tested unprocessed, and the processed version is compared by log probabilities or differences between logits at the same position. Per-head attribution depends on convention: with fold_value_biases, some of what was bias now counts as head write. The library’s weight-processing notes describe its conventions; check your installed version.
def find_project_root():
configured = os.environ.get('P06_PROJECT_ROOT')
candidates = [Path(configured).resolve()] if configured else [Path.cwd(), *Path.cwd().parents]
for candidate in candidates:
if (candidate / 'src/content/lessons/p06/l03-modelo-gpt-y-paridad.mdx').is_file():
return candidate
return None
def p06_gpt_class(root):
"""La clase GPT tal como está en p06-l03, leída del fichero de la lección (sin sus pruebas)."""
text = (root / 'src/content/lessons/p06/l03-modelo-gpt-y-paridad.mdx').read_text(encoding='utf-8')
cell = text.split('```python run runtime=local title="GPT propio y controles"\n', 1)[1].split('\n```', 1)[0]
scope = {'__name__': 'gpt_p06_l03'}
exec(compile(cell.split('\nattention_test()', 1)[0], 'p06-l03.mdx', 'exec'), scope)
return scope['GPT']
def to_transformer_lens(m):
"""Traducción a mano de nuestros pesos a la convención de TransformerLens (vistas, sin copiar)."""
d, H = m.cfg['d'], m.cfg['heads']
dh, t = d // H, m.transformer
sd = {'embed.W_E': t.wte.weight, 'pos_embed.W_pos': t.wpe.weight,
'ln_final.w': t.ln_f.weight, 'ln_final.b': t.ln_f.bias,
'unembed.W_U': t.wte.weight.T, 'unembed.b_U': torch.zeros_like(t.wte.weight[:, 0])}
for l, blk in enumerate(t.h):
p = f'blocks.{l}.'
sd |= {p + 'ln1.w': blk.ln_1.weight, p + 'ln1.b': blk.ln_1.bias,
p + 'ln2.w': blk.ln_2.weight, p + 'ln2.b': blk.ln_2.bias}
for n, W, b in zip('QKV', blk.attn.c_attn.weight.split(d, dim=0), blk.attn.c_attn.bias.split(d)):
sd[p + f'attn.W_{n}'] = W.view(H, dh, d).transpose(1, 2) # H × d × d_h
sd[p + f'attn.b_{n}'] = b.view(H, dh)
sd[p + 'attn.W_O'] = blk.attn.c_proj.weight.view(d, H, dh).permute(1, 2, 0) # H × d_h × d
sd[p + 'attn.b_O'] = blk.attn.c_proj.bias
sd[p + 'mlp.W_in'], sd[p + 'mlp.b_in'] = blk.mlp.c_fc.weight.T, blk.mlp.c_fc.bias
sd[p + 'mlp.W_out'], sd[p + 'mlp.b_out'] = blk.mlp.c_proj.weight.T, blk.mlp.c_proj.bias
return {k: v.detach() for k, v in sd.items()}
def tl_model(m, processed):
from transformer_lens import HookedTransformer, HookedTransformerConfig
c = m.cfg
cfg = HookedTransformerConfig(
n_layers=c['layers'], d_model=c['d'], n_ctx=c['context'], d_head=c['d'] // c['heads'],
n_heads=c['heads'], d_mlp=4*c['d'], d_vocab=c['vocab'], act_fn='gelu_new', eps=1e-5,
normalization_type='LNPre' if processed else 'LN', device=DEVICE, use_attn_result=True,
default_prepend_bos=False, dtype=m.lm_head.weight.dtype, init_weights=False)
tl = HookedTransformer(cfg)
if processed: # plegado y centrados de la biblioteca
tl.load_and_process_state_dict(to_transformer_lens(m), fold_ln=True, center_writing_weights=True,
center_unembed=True, fold_value_biases=True,
refactor_factored_attn_matrices=False)
else: # copia literal: así se prueba nuestra traducción
r = tl.load_state_dict(to_transformer_lens(m), strict=False)
assert not r.unexpected_keys and all(k.endswith(('.mask', '.IGNORE')) for k in r.missing_keys), r
return tl.eval()
g = torch.Generator().manual_seed(1729)
lotes = [torch.randint(0, V, (2, 32), generator=g).to(DEVICE) for _ in range(3)] + [x]
with torch.no_grad():
ref32 = [model(b) for b in lotes]
# 1) Frente a la clase original de p06-l03, primero en float32 y después en float64.
root = find_project_root()
if root is None:
print('No se encontró la raíz del proyecto (fija P06_PROJECT_ROOT): se omite la comparación con p06-l03.')
else:
GPT = p06_gpt_class(root)
with torch.device(DEVICE):
plain = GPT(**model.cfg, dropout=0.0)
plain.load_state_dict(model.state_dict()) # mismos nombres: los HookPoint no tienen pesos
plain.eval()
with torch.no_grad():
e32 = max((plain(b) - r).abs().max().item() for b, r in zip(lotes, ref32))
plain.double(); model.double()
e64 = max((plain(b) - model(b)).abs().max().item() for b in lotes)
model.float()
del plain
print(f'clase GPT de p06-l03 frente a HookedGPT | float32: {e32:.2e} | float64: {e64:.2e} '
f'(logits de hasta {max(r.abs().max().item() for r in ref32):.0f} en valor absoluto)')
assert e64 < 1e-9
# 2) Frente a TransformerLens, si está instalado.
try:
import transformer_lens, importlib.metadata
print('TransformerLens', importlib.metadata.version('transformer-lens'))
except ImportError:
print('TransformerLens no está instalado en este entorno: no se ha hecho la comparación.')
else:
model.double()
tl = tl_model(model, processed=False)
peor_logit, peor = 0.0, {}
with torch.no_grad():
for b in lotes:
ours, oc = model.run_with_cache(b)
theirs, tc = tl.run_with_cache(b)
peor_logit = max(peor_logit, (ours - theirs).abs().max().item())
for name, value in oc.items():
other = tc[name]
finite = torch.isfinite(value)
assert value.shape == other.shape, name
assert torch.equal(finite, torch.isfinite(other)), name # mismas posiciones enmascaradas
peor[name] = max(peor.get(name, 0.0), (value - other)[finite].abs().max().item())
del oc, tc
print(f'sin procesar, float64 | error máximo de logits {peor_logit:.2e} | '
f'{len(peor)} activaciones comparadas por nombre, peor: {max(peor, key=peor.get)} {max(peor.values()):.2e}')
assert peor_logit < 1e-9 and max(peor.values()) < 1e-9 and set(peor) == set(model.hook_points)
del tl
model.float()
if DEVICE == 'cuda':
torch.cuda.empty_cache()
# Con el procesado habitual (plegado y centrados) los logits cambian en una constante por fila.
tl = tl_model(model, processed=True)
with torch.no_grad():
b = lotes[0]
ours, theirs = ref32[0], tl(b)
shift = theirs - ours
print('procesado (fold_ln, centrados, fold_value_biases), float32:')
print(f' diferencia máxima de logits {shift.abs().max().item():.3f} | variación de esa diferencia '
f'dentro de cada fila {(shift - shift.mean(-1, keepdim=True)).abs().max().item():.1e} | '
f'error de log-probabilidades {(ours.log_softmax(-1) - theirs.log_softmax(-1)).abs().max().item():.1e}')
del tl
if DEVICE == 'cuda':
torch.cuda.empty_cache()npm run lab and open the connection link.Comparison with p06-l03 reads class GPT from that lesson’s own file without running its tests: it is the class used to train, and the one to match. TransformerLens is not a basic requirement (it pins versions of other libraries); install it in a separate environment with pip install transformer-lens and run this cell there. If absent, the cell says so and does not claim the test was done.
In the short verification run (GPT-2 small alternative, TransformerLens 2.16.1, laptop RTX 4060, peak 2.9 GiB GPU memory):
- Against the p06-l03 class, maximum logit difference was in float32, with absolute logits up to 141, and in float64;
- Against unprocessed TransformerLens in float64, logits differed by at most and all 220 names existed in both models with identical shape and differences of at most ;
- With full processing, logits changed by up to 118.1, but that difference varied only within each row (float32 rounding) and log probabilities matched within : this is the per-position constant from
center_unembed.
Direct logit attribution
Return to the sum. Final readout applies LayerNorm and the output matrix. Let be centering, scale, the final LayerNorm parameters and row for token (in GPT-2 and your model, row of the embedding table because weights are tied). The logit of at a position with final residual is
with if there is no output bias, as in GPT-2. The only nonlinear ingredient is , one scalar per position. If treated as a constant of this run, everything else is a linear map of , and is the sum from the previous theorem.
Proof
is linear, so . For this run is a fixed number (positive because ), so division by it is linear; so are coordinate-wise multiplication by and the dot product with . Distributing those operations over the sum yields , and and are added once because they apply afterward. Notice what was not proved: that is linear in writes when they change, because then changes.
∎Three common omissions break the sum: forgetting scale (projecting directly onto ), forgetting , or miscounting biases , which belong to the layer rather than its heads. Conversely, if the sum works with a bias omitted, you probably counted it twice elsewhere.
Why a bar is not the effect of removing the piece
The next figure reduces the setting to , where it is visible in full. Centering erases direction , so everything happens in the centered plane, drawn with an orthonormal basis. With , and negligible , output always lies on a circle of radius : LayerNorm preserves residual direction and forgets its length.
Initially, and , distributed into bars , and . Removing “should” leave , but the actual logit changes to . The reason is geometric: has little component along , but is long, and removing it lowers scale from to ; the rest of the residual, which points toward , is amplified. A write can affect readout only through normalization, with no component in the read direction.
We can quantify bar error for small perturbations. With and , the chain rule gives and thus
The first term is exactly the bar; the second corrects the scale change and is proportional to the component of along the residual itself. In a real model there is a third, much larger effect: removing a head changes inputs to all subsequent layers, which may compensate or amplify. These are indirect effects, ignored by direct attribution by construction.
For a question like “why ‘ Mary’ rather than ‘ John’?” it helps to attribute difference , with direction . Writes pushing every token equally (and GPT-2 has huge components of that kind) cancel, and the constant reduces to .
For the names sentence, the largest bars of “ Mary” − “ John” are heads 9.9 (+2.13), 9.6 (+2.10) and 10.0 (+0.84), favoring “ Mary”, and 10.7 (−2.25) and 11.10 (−0.80), opposing it. These are exactly the heads Wang and colleagues identified in GPT-2 small as name movers (copying the correct name) and negative name movers (pushing the opposite way). Without comparison, the absolute “ Mary” logit (−74.75) is dominated by head 11.8 (−17.1) and MLP 10 (−12.6), which depress all names equally. For the Eiffel Tower, GPT-2 small splits almost equally: “ London” 6.9% and “ Paris” 6.9%, with a logit difference of 0.005 made of small bars with opposite signs. The figure does not say whether the model “knows” where the tower is, only how this readout was formed.
def residual_pieces(cache, m=None):
"""(nombres, tensor componentes × B × T × d): todo lo que se ha escrito en el residual final."""
m = m or model
names, parts = ['emb', 'pos'], [cache['hook_embed'], cache['hook_pos_embed']]
bias = 0
for l, blk in enumerate(m.transformer.h):
res = cache[f'blocks.{l}.attn.hook_result']
names += [f'{l}.{h}' for h in range(res.shape[2])]
parts += list(res.unbind(2))
names.append(f'MLP {l}')
parts.append(cache[f'blocks.{l}.hook_mlp_out'])
bias = bias + blk.attn.c_proj.bias # b_O de cada capa, una sola vez
names.append('b_O')
parts.append(bias.expand_as(parts[0]))
return names, torch.stack(parts)
def direct_logit_attribution(cache, token_id, pos, m=None, batch=0):
"""Contribución directa de cada componente al logit de token_id en (batch, pos), y la constante."""
m = m or model
names, C = residual_pieces(cache, m)
c = C[:, batch, pos] # componentes × d
s = cache['ln_final.hook_scale'][batch, pos] # escala congelada de esta pasada
u = m.transformer.ln_f.weight * m.transformer.wte.weight[token_id] # γ ⊙ u_v
terms = (c - c.mean(-1, keepdim=True)) @ u / s
const = m.transformer.ln_f.bias @ m.transformer.wte.weight[token_id] # u_vᵀβ (sin sesgo de salida)
return names, terms, const
def check_reconstruction(m, ids):
"""Error máximo al reconstruir el residual y todos los logits de todas las posiciones."""
logits, cache = m.run_with_cache(ids)
names, C = residual_pieces(cache, m)
L = m.cfg['layers']
e_resid = (C.sum(0) - cache[f'blocks.{L-1}.hook_resid_post']).abs().max().item()
W = m.transformer.wte.weight * m.transformer.ln_f.weight # V × d, filas γ ⊙ u_v
const = m.transformer.wte.weight @ m.transformer.ln_f.bias
e_logit = 0.0
for p in range(ids.shape[1]): # componentes × V por posición
c = C[:, 0, p]
terms = (c - c.mean(-1, keepdim=True)) @ W.T / cache['ln_final.hook_scale'][0, p]
e_logit = max(e_logit, (terms.sum(0) + const - logits[0, p]).abs().max().item())
return e_resid, e_logit
for dtype in (torch.float32, torch.float64):
model.to(dtype)
e_r, e_l = check_reconstruction(model, x)
print(f'{str(dtype):14s} residual reconstruido: {e_r:.1e} | {x.shape[1]} posiciones × {V} logits: {e_l:.1e}')
assert e_l < (1e-3 if dtype == torch.float32 else 1e-9)
model.float()
# Diferencia de logits " Mary" − " John" en la última posición: barras directas y ablaciones.
logits, cache = model.run_with_cache(x)
names, t_m, c_m = direct_logit_attribution(cache, mary, -1)
_, t_j, c_j = direct_logit_attribution(cache, john, -1)
dla = t_m - t_j
total = (logits[0, -1, mary] - logits[0, -1, john]).item()
print(f'diferencia observada {total:.4f} | suma de barras {dla.sum().item() + (c_m - c_j).item():.4f}')
orden = dla.argsort(descending=True).tolist()
print('mayores empujes hacia " Mary":', ', '.join(f'{names[i]} {dla[i]:+.2f}' for i in orden[:6]))
print('mayores empujes hacia " John":', ', '.join(f'{names[i]} {dla[i]:+.2f}' for i in orden[::-1][:4]))
def ablate_head(l, h):
def f(a, n):
a = a.clone()
a[:, :, h] = 0
return a
z = model.run_with_hooks(x, [(f'blocks.{l}.attn.hook_result', f)])
return (z[0, -1, mary] - z[0, -1, john]).item() - total
print('cabeza barra directa efecto de anularla (cambio real de la diferencia)')
for i in orden[:3] + orden[::-1][:2]:
if '.' in names[i]:
l, h = map(int, names[i].split('.'))
print(f'{names[i]:>6s} {dla[i].item():+12.3f} {ablate_head(l, h):+12.3f}')npm run lab and open the connection link.The project criterion is for the sum to reproduce logits with error below , and the cell checks all positions and all tokens, not one chosen logit. In the short GPT-2 small verification run, in float64 the residual was reconstructed with error and the logits with error . In float32 errors were and : GPT-2 residual coordinates have magnitudes of hundreds, and summing 159 pieces in float32 accumulates that rounding. Thus the criterion is checked in float64 and float32 uses tolerance .
The final table of that run illustrates the previous section with real data:
| Head | Direct bar | Effect of zeroing it |
|---|---|---|
| 9.9 | +2.125 | +0.025 |
| 9.6 | +2.105 | +0.415 |
| 10.0 | +0.838 | −0.558 |
| 10.7 | −2.248 | +1.460 |
| 11.10 | −0.803 | +0.782 |
The two heads with the largest bars favoring “ Mary” can be zeroed without the difference falling: it rises slightly. Wang and colleagues describe backup name movers, later heads taking over when the main ones are zeroed, and McGrath and colleagues studied this “hydra effect” of self-repair more generally. A large bar is an excellent clue for what to study and a poor prediction of what happens if removed. Measuring total effect with suitable controls is the work of p11-l05.
def export_attribution(texts, path, k=3):
"""Barras de atribución directa para cada posición: los k tokens más probables, el token real
siguiente y, en la última posición, el primer token de cada palabra extra (por ejemplo, la rival)."""
out = {'source': FUENTE, 'components': None, 'texts': []}
for text, extra in texts:
ids = tokens(text)
logits, cache = model.run_with_cache(ids)
probs = logits[0].float().softmax(-1)
rows = []
for p in range(ids.shape[1]):
cands = logits[0, p].topk(k).indices.tolist()
nxt = ids[0, p + 1].item() if p + 1 < ids.shape[1] else None
if p == ids.shape[1] - 1:
nxt = None
cands += [w for w in (enc.encode_ordinary(e)[0] for e in extra) if w not in cands]
elif nxt not in cands:
cands.append(nxt)
row = []
for v in cands:
names, terms, const = direct_logit_attribution(cache, v, p)
row.append({'id': v, 'text': enc.decode([v]), 'logit': round(logits[0, p, v].item(), 3),
'prob': round(probs[p, v].item(), 4), 'const': round(const.item(), 3),
'terms': [round(1000 * t) for t in terms.tolist()]}) # milésimas
rows.append({'next': nxt, 'cands': row})
out['components'] = names
out['texts'].append({'text': text, 'tokens': piezas(ids), 'positions': rows})
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(out, ensure_ascii=False, separators=(',', ':')), encoding='utf-8')
return path
DLA_TEXTS = [(PROMPT, [' John']),
('The Eiffel Tower is located in the city of', [' Paris']),
('The cat sat on the mat. The cat sat on the', [' floor'])]
print('escrito', export_attribution(DLA_TEXTS, OUT / 'atribucion.json'),
f'({(OUT / "atribucion.json").stat().st_size / 1024:.0f} KiB)')npm run lab and open the connection link.Replace the texts with those of interest and load the resulting atribucion.json in the figure. With your 513-ID vocabulary a word occupies several tokens, so the figure will show more positions and each prediction will be a fragment of about two bytes.
Attention patterns: where heads look
Attribution tells which heads write in a token’s direction; the pattern tells where each head reads. The QK circuit fixes weights and the OV circuit decides what is written from what was read (the QK and OV circuits), so a pattern describes half the mechanism and nothing of its importance: a highly concentrated row can move a value that sends in a direction nobody reads. This is the old discussion of attention as explanation. Still, patterns are the best way to generate hypotheses, and some are clear enough to deserve names (the m18 pattern taxonomy).
A score alone means nothing without its control. With uniform causal attention, for , and
which is 0.140 for and 0.117 for : the same raw value means different things by length. Duplicate control also depends on repetitions in the text, and your model is special here. With 513 IDs and about two bytes per token, the same short fragments repeat constantly, so almost all queries have earlier duplicates and is much larger than with GPT-2 vocabulary. Comparing raw scores across models with different vocabularies compares different things.
The lit BOS column in most heads is an attention sink: since every softmax row must sum to 1, a head finding nothing useful to read deposits mass at a fixed position, often the first, whose value writes little. Xiao and colleagues documented it in large models; in GPT-2 small it is visible in the gallery. A catalog reading “first token” as the head’s function would confuse an idle mechanism with a task.
A catalog with a prior rule and confirmation
Classification means choosing thresholds, and choosing them after looking at data is the fastest way to find what one seeks. The lab fixes its rule before running: a head gets label if mean across texts is at least 0.4 and at least twice the mean uniform control. It may receive several. Labels are computed on selection set A (four natural texts and three sequences of 12 random tokens repeated twice) and checked on a disjoint set B built the same way. Repeated random sequences isolate copying: no semantics help, only repetition.
def all_patterns(ids):
"""Patrones de todas las cabezas: capas × cabezas × consulta × clave (una sola secuencia)."""
names = [f'blocks.{l}.attn.hook_pattern' for l in range(model.cfg['layers'])]
_, cache = model.run_with_cache(ids, names)
return torch.stack([cache[n][0] for n in names]).double()
def pattern_scores(A, ids):
"""S_prev, S_first y S_dup de cada cabeza (A: ... × T × T, posición 0 = BOS) y su control uniforme."""
T = A.shape[-1]
q = torch.arange(2, T, device=A.device) # consultas con previo distinto del BOS
prev = A[..., q, q - 1].mean(-1)
first = A[..., q, 0].mean(-1)
x = ids[0]
same = (x[:, None] == x[None, :]).tril(-1) # j < i con el mismo token
same[:, 0] = False # el BOS no cuenta como duplicado
has = same.any(-1)
dup = (A * same).sum(-1)[..., has].mean(-1) if has.any() else torch.full_like(prev, float('nan'))
U = torch.ones(T, T, dtype=A.dtype, device=A.device).tril()
U = U / U.sum(-1, keepdim=True) # atención uniforme causal
ctrl_dup = (U * same).sum(-1)[has].mean().item() if has.any() else float('nan')
control = {'prev': U[q, q - 1].mean().item(), 'first': U[q, 0].mean().item(), 'dup': ctrl_dup}
return {'prev': prev, 'first': first, 'dup': dup}, control
# Prueba exacta del control: S_prev = S_first = (H_T − 3/2)/(T − 2) con BOS en la posición 0.
T_ = 9
U_ = torch.ones(T_, T_, dtype=torch.float64).tril()
s_, c_ = pattern_scores((U_ / U_.sum(-1, keepdim=True))[None], torch.tensor([[0, 5, 6, 5, 7, 5, 8, 9, 6]]))
H_T = sum(1 / i for i in range(1, T_ + 1))
assert abs(c_['prev'] - (H_T - 1.5) / (T_ - 2)) < 1e-12 and abs(c_['first'] - c_['prev']) < 1e-12
assert abs(c_['dup'] - (1/4 + 2/6 + 1/9) / 3) < 1e-12 # consultas 3, 5 y 8 (desde 0)
def repeated_random(seed, n=12):
g = torch.Generator().manual_seed(seed)
lo, hi = (1000, 30000) if V > 30000 else (1, V - 1) # evita bytes raros y el especial
half = torch.randint(lo, hi, (n,), generator=g).tolist()
return torch.tensor([[BOS] + half + half], device=DEVICE)
NATURAL_A = ['The quick brown fox jumps over the lazy dog, and the dog does not move.',
'In 1969, Neil Armstrong became the first person to walk on the Moon.',
'def add(a, b):\n return a + b\n\nprint(add(2, 3))',
'She said that the results were good, but the results were not final.']
NATURAL_B = ['After the meeting, Alice sent the report to Bob, and Bob thanked Alice.',
'Water boils at 100 degrees Celsius at sea level, but the boiling point is lower in the mountains.',
'for i in range(10):\n total = total + i\nprint(total)',
'The cat sat on the mat. The cat sat on the mat again.']
SET_A = [tokens(t) for t in NATURAL_A] + [repeated_random(s) for s in range(3)]
SET_B = [tokens(t) for t in NATURAL_B] + [repeated_random(s) for s in range(3, 6)]
METRICS = ('prev', 'first', 'dup')
THRESHOLD, RATIO = 0.4, 2.0 # regla fijada antes de mirar: media ≥ 0.4 y ≥ 2 × control
def catalog(texts):
sums = {m: [] for m in METRICS}
ctrls = {m: [] for m in METRICS}
for ids in texts:
s, c = pattern_scores(all_patterns(ids), ids)
for m in METRICS:
if not math.isnan(c[m]):
sums[m].append(s[m])
ctrls[m].append(c[m])
mean = {m: torch.stack(sums[m]).mean(0) for m in METRICS} # capas × cabezas
sd = {m: torch.stack(sums[m]).std(0) for m in METRICS}
ctrl = {m: sum(ctrls[m]) / len(ctrls[m]) for m in METRICS}
labels = {m: (mean[m] >= THRESHOLD) & (mean[m] >= RATIO * ctrl[m]) for m in METRICS}
return mean, sd, ctrl, labels
mA, sA, cA, lA = catalog(SET_A)
mB, sB, cB, lB = catalog(SET_B)
nombre = {'prev': 'token previo', 'first': 'primer token', 'dup': 'duplicado'}
print(f'control uniforme medio en A: ' + ', '.join(f'{nombre[m]} {cA[m]:.3f}' for m in METRICS))
for m in METRICS:
heads = [(l, h) for l, h in lA[m].nonzero().tolist()]
kept = sum(lB[m][l, h].item() for l, h in heads)
top = sorted(heads, key=lambda lh: -mA[m][lh].item())[:5]
print(f'{nombre[m]:13s}: {len(heads):3d} cabezas en A, {kept} conservan la etiqueta en B | '
+ ', '.join(f'{l}.{h} {mA[m][l, h]:.2f}±{sA[m][l, h]:.2f} (B {mB[m][l, h]:.2f})' for l, h in top))
none = ~(lA['prev'] | lA['first'] | lA['dup'])
print(f'sin etiqueta en A: {int(none.sum())} de {none.numel()} cabezas')npm run lab and open the connection link.In the short GPT-2 small verification run, set A mean uniform control was 0.113 for previous and first token, and 0.067 for duplicates. Result:
- Previous token: 3 heads, all 3 confirmed in B. Head 4.11 has (0.98 in B): almost all its mass always goes to the previous token. Next are 2.2 (0.54) and 3.7 (0.43).
- Duplicate: 3 heads, all 3 confirmed: 0.5 (0.49), 0.1 (0.47) and 3.0 (0.41, with deviation 0.26 across texts). Heads 0.1 and 3.0 are two of the duplicate token heads described by Wang and colleagues.
- First token: 106 heads, 104 confirmed. These are sinks, not a function.
- Unlabeled: 33 of 144.
This is a catalog of patterns, and labels are operational descriptions with an explicit threshold, not demonstrated functions. A sustained 0.98 on disjoint texts is a strong regularity of where 4.11 reads; whether that reading serves a specific purpose (for example feeding induction heads) is a hypothesis p11-l02 will test.
What should you expect from your model? There are no published figures for it, so only a reasoned expectation is possible. Abundant sink heads are plausible because the mechanism requires only softmax and a fixed position. Also some previous-token head, a simple pattern Olsson and colleagues describe as a component of induction heads. But with two-byte tokens, “previous token” means “the previous two bytes”, and duplicate scores must be read against a much higher control. If your catalog does not resemble GPT-2’s, that is data about your model, not instrument failure: the instrument is already validated.
import base64
def export_gallery(examples, path):
"""Patrones (triángulo inferior en 0..255) y puntuaciones de todas las cabezas, más el catálogo."""
r = lambda t: [[round(v, 3) for v in row] for row in t.tolist()]
out = {'source': FUENTE, 'layers': model.cfg['layers'], 'heads': model.cfg['heads'],
'rule': {'threshold': THRESHOLD, 'ratio': RATIO},
'catalog': {'A': {m: r(mA[m]) for m in METRICS}, 'sdA': {m: r(sA[m]) for m in METRICS},
'B': {m: r(mB[m]) for m in METRICS}, 'controlA': cA, 'controlB': cB,
'nA': len(SET_A), 'nB': len(SET_B)},
'texts': []}
for label, ids in examples:
A = all_patterns(ids)
T = A.shape[-1]
rows, cols = torch.tril_indices(T, T)
q = (A[..., rows, cols] * 255).round().to(torch.uint8).cpu().numpy() # capas × cabezas × T(T+1)/2
s, c = pattern_scores(A, ids)
out['texts'].append({'label': label, 'tokens': piezas(ids), 'control': c,
'scores': {m: r(s[m]) for m in METRICS},
'patterns': base64.b64encode(q.tobytes()).decode('ascii')})
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(out, ensure_ascii=False, separators=(',', ':')), encoding='utf-8')
return path
EXAMPLES = [('Nombres repetidos', x),
('Frase repetida', tokens('The cat sat on the mat. The cat sat on the mat.')),
('Tokens aleatorios repetidos', repeated_random(100, n=10)),
('Código', tokens('def add(a, b):\n return a + b\n\nprint(add(2, 3))'))]
p = export_gallery(EXAMPLES, OUT / 'galeria.json')
print('escrito', p, f'({p.stat().st_size / 1024:.0f} KiB)')
if DEVICE == 'cuda':
torch.cuda.empty_cache()npm run lab and open the connection link.Patterns are saved quantized to 256 levels to keep the file small; figure scores are the exact values calculated by the cell. Put your own texts in EXAMPLES and load galeria.json in the figure.
Exercises
Step 1 of 3. What happens when centering the sum of writes?
pieces of shape (components, positions, d), gamma and beta of length d, unembed of shape (vocabulary, d), bias of vocabulary length and positive eps. Return an array with one contribution per component followed by the constant term. Scale is calculated from the full residual at that position (sum of pieces) and each piece is centered separately. Tests check the allocation, not just the sum.import numpy as np
def direct_logit_attribution(cache, token_id, pos):
passStep 1 of 3. How much mass does each allowed key in row i receive?
Summary
The final residual is exactly the sum of writes from embeddings, each head, each MLP and biases. Named hook points allow those writes to be read (by copying), replaced (by returning a new tensor) and compared name by name with TransformerLens, in float64 and unprocessed. With final LayerNorm scale frozen, the logit is a linear function of writes and direct-attribution bars reconstruct it with error . This identity describes the observed run, not what would happen if a piece were removed: GPT-2 head 9.9 has a +2.13 bar and zeroing it does not change the prediction. Attention patterns show where each head reads; with a uniform control, a prespecified rule and a confirmation set they become an honest catalog of hypotheses.