Module contents
Stage 1 of 8Advanced 100 min

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 xℓ∈Rd\vb{x}_\ell \in \R^{d} the vector at one position on entry to block ℓ\ell (in the lesson code, hook_resid_pre), with d=dmodeld = d_{\text{model}}. The block performs

xℓmid=xℓ+Attn⁡ℓ(LN⁡ℓ,1(xℓ)),xℓ+1=xℓmid+MLP⁡ℓ(LN⁡ℓ,2(xℓmid)),\vb{x}_\ell^{\text{mid}} = \vb{x}_\ell + \operatorname{Attn}_\ell\big(\operatorname{LN}_{\ell,1}(\vb{x}_{\ell})\big), \qquad \vb{x}_{\ell+1} = \vb{x}_\ell^{\text{mid}} + \operatorname{MLP}_\ell\big(\operatorname{LN}_{\ell,2}(\vb{x}_\ell^{\text{mid}})\big),

and the initial state is x1=et+pi\vb{x}_1 = \vb{e}_{t} + \vb{p}_{i}, the embedding of token tt plus the position embedding ii. 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 HH heads of dimension dh=d/Hd_h = d/H (the dkd_k of general notation; we reserve hh for the head index), each head produces at position ii a vector zℓh,i=∑j≤iAijℓh vℓh,j∈Rdh\vb{z}_{\ell h, i} = \sum_{j \le i} A^{\ell h}_{ij}\, \vb{v}_{\ell h, j} \in \R^{d_h}, where AℓhA^{\ell h} is its attention pattern and vℓh,j\vb{v}_{\ell h, j} the value at position jj. Multi-head attention concatenates the HH vectors and applies WO∈Rd×d\mat{W}_O \in \R^{d\times d} plus bias bO\vb{b}_O. If we split WO\mat{W}_O into column blocks, WO=[WO(1)⋯WO(H)]\mat{W}_O = [\mat{W}_O^{(1)} \cdots \mat{W}_O^{(H)}] with WO(h)∈Rd×dh\mat{W}_O^{(h)} \in \R^{d\times d_h}, block multiplication gives

WO[z1⋮zH]+bO=∑h=1HWO(h)zh⏟aℓh+bO.\mat{W}_O \begin{bmatrix} \vb{z}_1 \\ \vdots \\ \vb{z}_H \end{bmatrix} + \vb{b}_O = \sum_{h=1}^{H} \underbrace{\mat{W}_O^{(h)}\vb{z}_h}_{\vb{a}_{\ell h}} + \vb{b}_O .
Proof

By induction on ℓ\ell: xℓ+1−xℓ=Attn⁡ℓ(⋅)+MLP⁡ℓ(⋅)\vb{x}_{\ell+1} - \vb{x}_\ell = \operatorname{Attn}_\ell(\cdot) + \operatorname{MLP}_\ell(\cdot) from the two block equations, and attention output is ∑haℓh+bOℓ\sum_h \vb{a}_{\ell h} + \vb{b}_O^\ell by block multiplication. Summing differences from ℓ=1\ell = 1 to LL and adding x1=et+pi\vb{x}_1 = \vb{e}_t + \vb{p}_i yields the formula: a telescoping sum.

∎

The equality is exact for vectors calculated in this run. Each aℓh\vb{a}_{\ell h} and mℓ\vb{m}_\ell 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 2+144+122 + 144 + 12 writes plus the twelve biases bOℓ\vb{b}_O^\ell, all sharing the same 768-dimensional channel. A numbering convention before continuing: in formulas blocks run from 1 to LL, but in code and literature layers and heads are numbered from 0, so xℓ\vb{x}_\ell 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 WO\mat{W}_O, whether a LayerNorm output already includes γ\gamma and β\beta. Our instrumented model uses exactly TransformerLens names and shapes (the HookedTransformer workflow), allowing name-by-name comparison with that library.

InteractiveMap of hook points
tokensresidual stream+block ℓ (× 12)attention (12 heads)+MLP (4d)+W_U → logits(final LayerNorm)embedpos_embedresid_prescalenormalizedqkvattn_scorespatternzresultattn_outresid_midscalenormalizedprepostmlp_outresid_postscalenormalized
  • residual state
  • write: lives in Rd\R^d and is added
  • internal activation
1
Name
blocks.ℓ.attn.hook_result
Shape
B × T × H × d
With these values
1 × 1024 × 12 × 768
Float32 memory, 12 layers
432 MiB
Added to residual?
yes: a write
Each head's write: its z\vb{z} times its column block of WO\mat{W}_O. This is the per-head attribution piece.
Full cache (220 tensors)
2.22 GiB
Of that, scores and patterns
1.13 GiB (51 %)
Used by attribution (embed, pos_embed, result, mlp_out and final scale)
474 MiB
The 18 points in each block and four global points of the instrumented model. Writes are in magenta: they live in Rd\R^d and are added to the residual. Choose a point and change length: what grows with TT and what with T2T^2? How much does saving everything cost compared with saving only what attribution uses?

The figure makes two things clear. First, only some activations can be added to the residual. hook_z has dh=64d_h = 64 components per head and does not live in residual space; hook_result is the same vector after its WO\mat{W}_O block and does live there. Confusing them produces sums with wrong dimensions or, worse, dimensions correct by chance. Second, memory. With T=1024T = 1024 tokens, saving 220 tensors in float32 costs 2.22 GiB, and half are scores and patterns growing with T2T^2 (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 bO\vb{b}_O, and saving it alongside them would double count. A cache is designed for the question.

Three rules so a hook does not lie

  1. 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.
  2. Replacing means returning a new tensor. An intervention clones, modifies the copy and returns it. Modifying output in place changes what other functions already saved and can break autograd.
  3. Always remove. Handles are removed in an finally block 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:

VariableDefaultUse
P11_CKPTp06_pretrain/runs/full/snapshotsFolder (recursive) with p06-l06 model-*.pt, or a specific file. The latest is selected.
P06_DATA_DIRp06_datap06-l02 manifest and vocabulary, to tokenize with your BPE.
P11_FALLBACKgpt2If no checkpoint: gpt2 (published GPT-2 small, about 550 MB the first time) or aleatorio.
P11_OUTp11_labWhere atribucion.json and galeria.json for the figures are written.
P11_MAX_RSS_GB3.5Process 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.

[ ]Load your GPT or the declared alternativeLocal 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()]
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

[ ]HookedGPT: named hook pointsLocal GPU
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}')
This cell needs the local lab (PyTorch with your GPU). Start it with 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, WQ∈RH×d×dh\mat{W}_Q \in \R^{H\times d\times d_h}, and applies them to row vectors (x⊤WQ(h)\vb{x}\T\mat{W}_Q^{(h)}); nn.Linear stores an 3d×d3d\times d matrix with Q, K and V stacked by rows and applies it as Wx\mat{W}\vb{x}. Translation of head hh takes rows hdh,…,(h+1)dh−1h d_h, \dots, (h+1)d_h - 1 of the Q block and transposes them; WO(h)\mat{W}_O^{(h)} are corresponding columns of c_proj, which TransformerLens stores as H×dh×dH\times d_h\times d. A mistaken transpose can preserve shape when dimensions coincide (d×dd\times d), 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 10−410^{-4} for logits of magnitude 100, and such a discrepancy cannot distinguish a subtle mapping error from rounding. In float64 rounding falls to 10−1310^{-13} 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, W(γ⊙x^+β)+b=(Wdiag⁡(γ))x^+(Wβ+b)\mat{W}(\gamma \odot \hat{\vb{x}} + \beta) + \vb{b} = (\mat{W}\diag(\gamma))\hat{\vb{x}} + (\mat{W}\beta + \vb{b}), with x^=Px/s(x)\hat{\vb{x}} = \mat{P}\vb{x}/s(\vb{x}). Save W′=Wdiag⁡(γ)\mat{W}' = \mat{W}\diag(\gamma) and b′=Wβ+b\vb{b}' = \mat{W}\beta + \vb{b}, 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 WU\mat{W}_U 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 ∑jAij(vj+bV)=∑jAijvj+bV\sum_j A_{ij}(\vb{v}_j + \vb{b}_V) = \sum_j A_{ij}\vb{v}_j + \vb{b}_V, and WO(h)bV(h)\mat{W}_O^{(h)}\vb{b}_V^{(h)} is constant: move it to bO\vb{b}_O. hook_result of 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.

[ ]Equivalence with p06-l03 and TransformerLensLocal GPU
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()
This cell needs the local lab (PyTorch with your GPU). Start it with 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 1.1⋅10−41.1\cdot 10^{-4} in float32, with absolute logits up to 141, and 3⋅10−133\cdot 10^{-13} in float64;
  • Against unprocessed TransformerLens in float64, logits differed by at most 3.6⋅10−133.6\cdot 10^{-13} and all 220 names existed in both models with identical shape and differences of at most 1.8⋅10−121.8\cdot 10^{-12};
  • With full processing, logits changed by up to 118.1, but that difference varied only 9.9⋅10−59.9\cdot 10^{-5} within each row (float32 rounding) and log probabilities matched within 8⋅10−58\cdot 10^{-5}: 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 P=I−1d11⊤\mat{P} = \mat{I} - \frac{1}{d}\vb{1}\vb{1}\T be centering, s(r)=d−1∥Pr∥22+εs(\vb{r}) = \sqrt{d^{-1}\norm{\mat{P}\vb{r}}_2^2 + \eps} scale, γ,β∈Rd\gamma, \beta \in \R^d the final LayerNorm parameters and uv\vb{u}_v row WU\mat{W}_U for token vv (in GPT-2 and your model, row vv of the embedding table because weights are tied). The logit of vv at a position with final residual r\vb{r} is

zv=uv⊤(γ⊙Prs(r)+β)+bv,z_v = \vb{u}_v\T\Big(\gamma \odot \frac{\mat{P}\vb{r}}{s(\vb{r})} + \beta\Big) + b_v ,

with bv=0b_v = 0 if there is no output bias, as in GPT-2. The only nonlinear ingredient is s(r)s(\vb{r}), one scalar per position. If treated as a constant of this run, everything else is a linear map of r\vb{r}, and r\vb{r} is the sum from the previous theorem.

Proof

P\mat{P} is linear, so Pr=∑kPck\mat{P}\vb{r} = \sum_k \mat{P}\vb{c}_k. For this run s(r)>0s(\vb{r}) > 0 is a fixed number (positive because ε>0\eps > 0), so division by it is linear; so are coordinate-wise multiplication by γ\gamma and the dot product with uv\vb{u}_v. Distributing those operations over the sum yields ∑kdkv\sum_k d_{kv}, and β\beta and bvb_v are added once because they apply afterward. Notice what was not proved: that zvz_v is linear in writes when they change, because then s(r)s(\vb{r}) changes.

∎

Three common omissions break the sum: forgetting scale (projecting ck\vb{c}_k directly onto uv\vb{u}_v), forgetting β\beta, or miscounting biases bOℓ\vb{b}_O^\ell, 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 d=3d = 3, where it is visible in full. Centering erases direction 1=(1,1,1)\vb{1} = (1, 1, 1), so everything happens in the centered plane, drawn with an orthonormal basis. With γ=1\gamma = \vb{1}, β=0\beta = \vb{0} and negligible ε\eps, output r^=Pr/s(r)\hat{\vb{r}} = \mat{P}\vb{r}/s(\vb{r}) always lies on a circle of radius 3\sqrt{3}: LayerNorm preserves residual direction and forgets its length.

InteractiveFrozen scale versus ablation
Bars dkd_k with frozen scale, and what happens when a write is removed
c₁
+0.16
c₂
+0.53
c₃
+0.11
sum of bars = z
+0.80
prediction z − d₁
+0.64
actual z without c₁
+1.73
  • c1\vb{c}_1
  • c2\vb{c}_2
  • c3\vb{c}_3 (chained writes)
  • readout direction u\vb{u}
  • residual r=∑kck\vb{r} = \sum_k \vb{c}_k
  • LayerNorm output r^\hat{\vb{r}}
  • after removing a write
  • circle of radius 3\sqrt{3}
Remove a write
Scale s(r)s(\vb{r})1.885
Logit z=u⊤r^z = \vb{u}\T\hat{\vb{r}}0.796
∑kdk\sum_k d_k0.796
Scale after removal0.695
Prediction z−dkz - d_k0.637
Actual logit without the write1.726
The c₁ bar is positive, but removing it makes the logit rise: scale changed from 1.89 to 0.70.
Three chained writes add to residual r\vb{r}; LayerNorm takes it to r^\hat{\vb{r}} on the circle. Bars dk=u⊤ck/s(r)d_k = \vb{u}\T\vb{c}_k/s(\vb{r}) sum exactly to zz. Initially, the c1\vb{c}_1 bar is positive but removing c1\vb{c}_1 more than doubles the logit. Can you find a configuration in which removing a negative-bar write lowers it?

Initially, s(r)=1.885s(\vb{r}) = 1.885 and z=0.796z = 0.796, distributed into bars 0.1590.159, 0.5310.531 and 0.1060.106. Removing c1\vb{c}_1 “should” leave 0.796−0.159=0.6370.796 - 0.159 = 0.637, but the actual logit changes to 1.7261.726. The reason is geometric: c1\vb{c}_1 has little component along u\vb{u}, but is long, and removing it lowers scale from 1.8851.885 to 0.6950.695; the rest of the residual, which points toward u\vb{u}, 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 y=Pr\vb{y} = \mat{P}\vb{r} and s=y⊤y/d+εs = \sqrt{\vb{y}\T\vb{y}/d + \eps}, the chain rule gives δs=y⊤P δr/(d s)\delta s = \vb{y}\T\mat{P}\,\delta\vb{r}/(d\,s) and thus

δ(ys)=P δrs−y y⊤P δrd s3.\delta\Big(\frac{\vb{y}}{s}\Big) = \frac{\mat{P}\,\delta\vb{r}}{s} - \frac{\vb{y}\,\vb{y}\T\mat{P}\,\delta\vb{r}}{d\,s^3}.

The first term is exactly the bar; the second corrects the scale change and is proportional to the component of δr\delta\vb{r} 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 zv−zwz_v - z_w, with direction γ⊙(uv−uw)\gamma \odot (\vb{u}_v - \vb{u}_w). Writes pushing every token equally (and GPT-2 has huge components of that kind) cancel, and the constant reduces to (uv−uw)⊤β(\vb{u}_v - \vb{u}_w)\T\beta.

InteractiveWho pushes this token?

Measured by this lesson’s lab. ALTERNATIVE: published GPT-2 small (openai-community/gpt2@607a30d), not your model.

Position 14, after «·to»: read logit(«·Mary») − logit(«·John») · last position

01234567891011MLP01234567891011embposb_O
−2.25+2.25· rows: layer · columns: head
Largest bars by absolute value
10.7
−2.25
9.9
+2.13
9.6
+2.10
10.0
+0.84
11.10
−0.80
10.2
−0.68
10.10
+0.58
11.3
+0.43
11.2
+0.42
10.1
+0.41
Cumulative bars by layer
observed 3.36emblayer 5layer 11
  • constant + embeddings + biases, then layer by layer
  • observed value
Load your attribution (atribucion.json from the lab)
Observed difference3.361
Sum of bars + constant3.365
Discrepancy (file rounding)0.004
Constant (β term)−1.296
Bar of head 10.7−2.248
These are direct effects with final scale frozen: they do not say what would happen if the component were removed.
Direct attribution of the 144 heads, 12 MLPs, embeddings and attention biases in GPT-2 small, measured by the lab. Start with ‘ Mary’ versus ‘ John’, then remove the comparison: why is the absolute logit dominated by components that do not distinguish names? Also try the Eiffel Tower, where the model hesitates between ‘ London’ and ‘ Paris’.

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.

[ ]Direct attribution and its checkLocal GPU
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}')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The project criterion is for the sum to reproduce logits with error below 10−410^{-4}, 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 1.1⋅10−131.1\cdot 10^{-13} and the 15×5025715 \times 50257 logits with error 5.4⋅10−135.4\cdot 10^{-13}. In float32 errors were 5.8⋅10−45.8\cdot 10^{-4} and 1.2⋅10−41.2\cdot 10^{-4}: 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 10−310^{-3}.

The final table of that run illustrates the previous section with real data:

HeadDirect barEffect 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.

[ ]Export attribution for the figureLocal GPU
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)')
This cell needs the local lab (PyTorch with your GPU). Start it with 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 AijA_{ij} 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 WO(h)\mat{W}_O^{(h)} 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, Aij=1/iA_{ij} = 1/i for j≤ij \le i, and

Sprevunif=Sprimerounif=HT−3/2T−2,HT=∑i=1T1i,S_{\text{prev}}^{\text{unif}} = S_{\text{primero}}^{\text{unif}} = \frac{H_T - 3/2}{T - 2}, \qquad H_T = \sum_{i=1}^{T}\frac{1}{i},

which is 0.140 for T=15T = 15 and 0.117 for T=20T = 20: 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 SdupunifS_{\text{dup}}^{\text{unif}} is much larger than with GPT-2 vocabulary. Comparing raw scores across models with different vocabularies compares different things.

InteractiveHead gallery

Measured by this lesson’s lab. ALTERNATIVE: published GPT-2 small (openai-community/gpt2@607a30d), not your model.

0123456789101101234567891011
  • border: previous token
  • border: first token
  • border: duplicate
  • rows: layer · columns: head
Head 4.11 · Repeated names
<|endofteWhen·Mary·and·John·went·to·the·store,·John·gave·a·drink·toquery «<|endoftext|>» (0) → key «<|endoftext|>» (0): 1.000query «When» (1) → key «<|endoftext|>» (0): 1.000query «When» (1) → key «When» (1): 0.000query «·Mary» (2) → key «<|endoftext|>» (0): 0.000query «·Mary» (2) → key «When» (1): 1.000query «·Mary» (2) → key «·Mary» (2): 0.000query «·and» (3) → key «<|endoftext|>» (0): 0.000query «·and» (3) → key «When» (1): 0.000query «·and» (3) → key «·Mary» (2): 1.000query «·and» (3) → key «·and» (3): 0.000query «·John» (4) → key «<|endoftext|>» (0): 0.000query «·John» (4) → key «When» (1): 0.000query «·John» (4) → key «·Mary» (2): 0.000query «·John» (4) → key «·and» (3): 1.000query «·John» (4) → key «·John» (4): 0.000query «·went» (5) → key «<|endoftext|>» (0): 0.000query «·went» (5) → key «When» (1): 0.000query «·went» (5) → key «·Mary» (2): 0.000query «·went» (5) → key «·and» (3): 0.000query «·went» (5) → key «·John» (4): 1.000query «·went» (5) → key «·went» (5): 0.000query «·to» (6) → key «<|endoftext|>» (0): 0.000query «·to» (6) → key «When» (1): 0.000query «·to» (6) → key «·Mary» (2): 0.000query «·to» (6) → key «·and» (3): 0.000query «·to» (6) → key «·John» (4): 0.000query «·to» (6) → key «·went» (5): 1.000query «·to» (6) → key «·to» (6): 0.000query «·the» (7) → key «<|endoftext|>» (0): 0.000query «·the» (7) → key «When» (1): 0.000query «·the» (7) → key «·Mary» (2): 0.000query «·the» (7) → key «·and» (3): 0.000query «·the» (7) → key «·John» (4): 0.000query «·the» (7) → key «·went» (5): 0.000query «·the» (7) → key «·to» (6): 1.000query «·the» (7) → key «·the» (7): 0.000query «·store» (8) → key «<|endoftext|>» (0): 0.000query «·store» (8) → key «When» (1): 0.000query «·store» (8) → key «·Mary» (2): 0.000query «·store» (8) → key «·and» (3): 0.000query «·store» (8) → key «·John» (4): 0.000query «·store» (8) → key «·went» (5): 0.000query «·store» (8) → key «·to» (6): 0.000query «·store» (8) → key «·the» (7): 1.000query «·store» (8) → key «·store» (8): 0.000query «,» (9) → key «<|endoftext|>» (0): 0.000query «,» (9) → key «When» (1): 0.000query «,» (9) → key «·Mary» (2): 0.000query «,» (9) → key «·and» (3): 0.000query «,» (9) → key «·John» (4): 0.000query «,» (9) → key «·went» (5): 0.000query «,» (9) → key «·to» (6): 0.000query «,» (9) → key «·the» (7): 0.000query «,» (9) → key «·store» (8): 1.000query «,» (9) → key «,» (9): 0.000query «·John» (10) → key «<|endoftext|>» (0): 0.000query «·John» (10) → key «When» (1): 0.000query «·John» (10) → key «·Mary» (2): 0.000query «·John» (10) → key «·and» (3): 0.000query «·John» (10) → key «·John» (4): 0.000query «·John» (10) → key «·went» (5): 0.000query «·John» (10) → key «·to» (6): 0.000query «·John» (10) → key «·the» (7): 0.000query «·John» (10) → key «·store» (8): 0.000query «·John» (10) → key «,» (9): 1.000query «·John» (10) → key «·John» (10): 0.000query «·gave» (11) → key «<|endoftext|>» (0): 0.000query «·gave» (11) → key «When» (1): 0.000query «·gave» (11) → key «·Mary» (2): 0.000query «·gave» (11) → key «·and» (3): 0.000query «·gave» (11) → key «·John» (4): 0.000query «·gave» (11) → key «·went» (5): 0.000query «·gave» (11) → key «·to» (6): 0.000query «·gave» (11) → key «·the» (7): 0.000query «·gave» (11) → key «·store» (8): 0.000query «·gave» (11) → key «,» (9): 0.000query «·gave» (11) → key «·John» (10): 1.000query «·gave» (11) → key «·gave» (11): 0.000query «·a» (12) → key «<|endoftext|>» (0): 0.000query «·a» (12) → key «When» (1): 0.000query «·a» (12) → key «·Mary» (2): 0.000query «·a» (12) → key «·and» (3): 0.000query «·a» (12) → key «·John» (4): 0.000query «·a» (12) → key «·went» (5): 0.000query «·a» (12) → key «·to» (6): 0.000query «·a» (12) → key «·the» (7): 0.000query «·a» (12) → key «·store» (8): 0.000query «·a» (12) → key «,» (9): 0.000query «·a» (12) → key «·John» (10): 0.000query «·a» (12) → key «·gave» (11): 1.000query «·a» (12) → key «·a» (12): 0.000query «·drink» (13) → key «<|endoftext|>» (0): 0.000query «·drink» (13) → key «When» (1): 0.000query «·drink» (13) → key «·Mary» (2): 0.000query «·drink» (13) → key «·and» (3): 0.000query «·drink» (13) → key «·John» (4): 0.000query «·drink» (13) → key «·went» (5): 0.000query «·drink» (13) → key «·to» (6): 0.000query «·drink» (13) → key «·the» (7): 0.000query «·drink» (13) → key «·store» (8): 0.000query «·drink» (13) → key «,» (9): 0.000query «·drink» (13) → key «·John» (10): 0.000query «·drink» (13) → key «·gave» (11): 0.000query «·drink» (13) → key «·a» (12): 1.000query «·drink» (13) → key «·drink» (13): 0.000query «·to» (14) → key «<|endoftext|>» (0): 0.000query «·to» (14) → key «When» (1): 0.000query «·to» (14) → key «·Mary» (2): 0.000query «·to» (14) → key «·and» (3): 0.000query «·to» (14) → key «·John» (4): 0.000query «·to» (14) → key «·went» (5): 0.000query «·to» (14) → key «·to» (6): 0.000query «·to» (14) → key «·the» (7): 0.000query «·to» (14) → key «·store» (8): 0.000query «·to» (14) → key «,» (9): 0.000query «·to» (14) → key «·John» (10): 0.000query «·to» (14) → key «·gave» (11): 0.000query «·to» (14) → key «·a» (12): 0.000query «·to» (14) → key «·drink» (13): 1.000query «·to» (14) → key «·to» (14): 0.000<|endoftWhen·Mary·and·John·went·to·the·store,·John·gave·a·drink·to
01· rows: queries · columns: keys
Catalog label
Load your gallery (galeria.json from the lab)
Head4.11
ScoreThis text (control)A: mean ± sdB: mean
previous1.00 (0.14)0.98 ± 0.040.98
first0.00 (0.14)0.00 ± 0.000.00
duplicate0.00 (0.08)0.03 ± 0.070.03
A: 7 selection texts · B: 7 confirmation texts · rule: mean ≥ 0.4 and ≥ 2 × control
Label: previous token confirmed in B.
GPT-2 small's 144 heads on four texts, measured by the lab. Each thumbnail border is its catalog label, calculated on the seven set-A texts (of the four visible, only code is among them). Find the previous-token head (a diagonal just below the main one) and duplicate heads on repeated random tokens. Why do almost all intermediate-layer heads have a lit BOS column?

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 mm if mean SmS_m 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.

[ ]Pattern scores and catalog with confirmationLocal GPU
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')
This cell needs the local lab (PyTorch with your GPU). Start it with 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 Sprev=0.98±0.04S_{\text{prev}} = 0.98 \pm 0.04 (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.

[ ]Export the galleryLocal GPU
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()
This cell needs the local lab (PyTorch with your GPU). Start it with 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

ProofLinear with frozen scale
Prove: Prove that, with final LayerNorm scale fixed to that of one run, logits are a linear (affine) function of component writes, and that their contributions sum to the observed logit.
0
The final residual is the sum of writes: r = c₁ + … + c_K. The logit is z_v = u_vᵀ(γ ⊙ P r / s(r) + β) + b_v.

Step 1 of 3. What happens when centering the sum of writes?

CodeImplement direct_logit_attribution
Implement direct_logit_attribution(cache, token_id, pos). The dictionary contains 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):
  pass
Shift+Enter to run
QuizWhat the bar does not see
In GPT-2 small, head 9.9 contributes +2.13 direct attribution to logit(“ Mary”) − logit(“ John”), but zeroing its output increases the difference by 0.025. What best explains the discrepancy?
NumericHow many pieces write to the residual
A GPT has 12 layers, 12 heads per layer and one MLP per layer. Counting token embedding, position embedding, each head and each MLP as separate writes (biases aside), how many writes are summed by the final residual?
NumericThe cost of saving patterns
With the preceding model, a sequence of T = 1024 tokens and batch 1, how many MiB do all hook_pattern tensors occupy in float32 (one per layer, shaped B × H × T × T)? 1 MiB is 2²⁰ bytes.
MiB
QuizAfter processing
You load your model in TransformerLens with center_unembed=True and compare with your implementation. Absolute logits differ by up to 118, but the difference is the same for every token at each position. Which conclusion is correct?
ProofThe uniform control depends on length
Prove: With BOS at position 1 and uniform causal attention over a sequence of length T ≥ 3, prove S_prev = (H_T − 3/2)/(T − 2), where H_T = 1 + 1/2 + … + 1/T.
0
The query at position i can attend to i keys 1, …, i, including itself, and S_prev averages A_{i,i−1} over queries i = 3, …, T.

Step 1 of 3. How much mass does each allowed key in row i receive?

QuizDuplicates with 513 tokens
In your GPT with a 513-ID vocabulary, a head obtains S_dup = 0.30 on natural texts; in GPT-2 small, a head obtains the same 0.30 on the same texts. What can be asserted?

Summary

Key idea

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 10−1310^{-13}. 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.