Module contents
Stage 5 of 8Research 120 min

Activation patching and circuit discovery

Use pairs of clean and corrupted inputs to study indirect-object identification in GPT-2 small and modular addition in the causal transformer trained in Lesson 3. Use activation patching to locate components, trace paths between GPT-2 heads with path patching, and compare exact search with attribution patching. Track which results apply to each architecture.

After this lesson you can

  • Design clean/corrupted input pairs and a logit-difference metric.
  • Apply activation patching by layer, position and head to locate relevant components.
  • Reconstruct the circuit with path patching between heads.
  • Compare attribution patching with activation patching and explain when the approximation fails.

Before you start

From pattern to intervention

A head can attend to a name without that name influencing the answer. Attention inspection describes one run; to ask what would change, intervene and rerun the rest of the model. In “When Mary and John went to the store, John gave a drink to”, the expected answer is Mary. Change the second John to Mary: now the expected answer is John. Both sentences have the same number of tokens in GPT-2, and only one name changes at the same position.

The intervened computation resembles the intervention operator: it replaces one internal equation by a fixed value and preserves the others. Here we know the model’s full program, but still need assumptions about which counterfactual matches the question. The hybrid state may not occur in natural data. Nor should the measured effect automatically be confused with a natural direct or indirect effect: that identification requires defining the variables and their causal assumptions.

The specific question is whether, in the second sentence’s run, replacing a head’s output with what it produced on the first returns part of the preference for Mary. An effect shows sensitivity to that substitution in these examples. It does not show that the head alone implements the task in every context. Capture and replacement hooks allow the experiment without changing weights.

A metric before looking at results

For each pair fix the same two answer IDs, even in the corrupted sentence. If zaz_a is the logit of the correct name for the clean sentence and zbz_b that of the other name, use m=za−zbm=z_a-z_b at the final position. Average mm over pairs. This is a difference in log probabilities: the softmax normalization term cancels. An isolated probability can change due to changes in other tokens even when the preference between the two names stays fixed.

There are two ways to aggregate several pairs, and they are not equivalent. The expression above is the ratio of means: sum patched differences and divide by the sum of clean-minus-corrupt differences. Alternatively, calculate a ratio per pair and average them. The second gives great weight to an example with a denominator close to zero and can explode even if the mean margin is stable. If some pairs reverse sign, even the ratio of means can suffer cancellation. Before interpreting a map, inspect individual margins and show how many examples fail the task.

The logit difference has another advantage over accuracy: it retains margin information even if the top answer does not change. But it does not replace all behavioral evaluation. A head could raise both names against the rest of the vocabulary without changing their difference, or change the margin without altering generated text. Depending on the question, supplement the metric with probability, loss and answer frequency; do not directly compare numbers obtained with different metrics.

The reverse intervention starts from the clean run and introduces the corrupt activation. With the same orientation, (mc−mc←r)/(mc−mr)(m_c-m_{c\leftarrow r})/(m_c-m_r) measures how much is lost. The first direction evaluates sufficiency of the substitution in a corrupted context and the second relative necessity in the clean context, not universal sufficiency or necessity. Interactions and redundant paths make the scores differ. Heimersheim and Nanda explain why the site, corruption distribution and metric are part of the result’s meaning.

What is replaced

The output before the attention projection has shape batch by position by head by head dimension. Activation patching copies only the region of interest from the source run to the destination run; the rest of the computation follows the destination. In GPT-2, the concatenated vector entering c_proj contains contiguous heads. Before using that site, verify that order and shape match the implementation. The output projection is linear, so replacing an input block is equivalent to replacing that head’s contribution to the sum, preserving the shared bias.

Sweep layers and heads, then layers and positions. A map of individual effects is a list of separate interventions, not a decomposable sum: two heads may compensate for or interact with each other. A head with a small effect can be necessary in combination with another. Conversely, a large individual intervention can modify several downstream paths.

A logical example shows redundancy without a transformer. If the output is A∨BA\lor B and both variables are 1, removing only AA leaves the output at 1, as does removing only BB. That does not make both irrelevant: removing them jointly changes the output to 0. Intervention order and the state of the other pieces matter. A real circuit also has continuous nonlinearities, normalization and backup mechanisms; a group test must therefore run the entire group, not add map cells.

The block patched also changes the question. At c_proj, one head’s attention output is replaced before projection into the residual, for all selected positions. Replacing the same head’s query intervenes before its attention weights are built; replacing only the final position leaves earlier outputs intact. Do not compare their numbers as if they were replications of the same treatment. In every case verify that replacing a tensor with itself reproduces the original run within numerical tolerance.

InteractivePatching sweep in GPT-2 small
Layer0123456789101101234567891011

Blue: negative value. Red: positive. Intensity is relative to the absolute maximum of the selected map. Zero-based indices; four IOI pairs, published GPT-2. Scroll the position map horizontally if needed.

Direction
Granularity
Layer, head8.10
Fraction recovered0.251
Select a head or position and compare both directions. In both directions, the position map replaces every head in a layer at that position. The four sentences, weights and calculation are detailed in the lab.

For these four pairs, the mean clean difference is 2.118 and corrupt −3.161. Heads 8.10, 5.5 and 8.6 individually recover 0.251, 0.238 and 0.225 of the margin respectively. These are results from a small sample with published GPT-2, not your own model or a confidence interval. Head 10.7 has a negative effect: patching can move the metric away from the clean value.

The source comparison is indicative because interventions and sentence distributions differ. In the published circuit, 8.10 and 8.6 belong to the subject inhibition group, 5.5 to induction, and 9.9 and 10.0 to name movers. The paper also finds negative contributions from 10.7 and 11.10 under its path-patching protocol. Overlap of some heads with this sweep does not show our effects have the same mechanism or reproduce the paper’s validation.

From nodes to paths

Path patching asks whether a sender’s signal reaches a receiver through a defined route. First the base run is cached. Then the sender is replaced and other writes are held fixed under the chosen protocol, saving the receiver’s input state. Finally the base is rerun and only that receiver input is replaced with the captured one. The metric difference measures this composite intervention, not an anatomical edge independent of the protocol.

In attention, query, key and value are distinct pathways. If all three are replaced simultaneously one cannot claim which carried the signal. Document which positions and branches are held fixed, including treatment of MLPs and residual connections, and check identity controls. The IOI circuit of Wang and colleagues groups 26 heads into seven classes and tests faithfulness, completeness and minimality. Finding a head from that list in a small template is a starting point, not a reproduction of the entire circuit.

A cheap approximation, not an intervention

Let F(a)F(\vb{a}) be the metric when the activation at the chosen site is a\vb{a}. Attribution patching linearizes around the corrupt activation:

F(ac)−F(ar)≈∇F(ar)⊤(ac−ar).F(\vb{a}_c)-F(\vb{a}_r)\approx \grad F(\vb{a}_r)\T(\vb{a}_c-\vb{a}_r).

One backward pass obtains gradients for many components. The omitted term depends on curvature and displacement size: a small local gradient can coexist with a large exact effect if the function is saturated, and a large gradient with a small exact effect if the slope changes along the path. Compare both per component in the same units, report correlation and individual errors, and confirm candidates with exact replacements. Linearization does not promise that a finite perturbation is small.

Gradient attribution is not automatically an assignment satisfying the axioms of an attribution method. Its reference point, how components are grouped, and how effects are integrated or approximated determine which properties it preserves. The local product is useful for search, but exact replacement is the decisive comparison for the selected site and examples.

Two scalar functions show the error without a large model. In f(x)=x−x2f(x)=x-x^2, from x=0x=0 to x=1x=1, the initial gradient predicts change 1 and the actual change is 0. In g(x)=x2g(x)=x^2, the initial gradient predicts 0 and the actual change is 1. Both are smooth polynomials; autodifferentiation need not be wrong for a finite approximation to fail.

[ ]Two failures of the local approximationBrowser
f=lambda x:x-x*x
g=lambda x:x*x
x0,x1=0.,1.
for name,fn,grad in [('f',f,1.),('g',g,0.)]:
    print(name,'aproximación',grad*(x1-x0),'cambio exacto',fn(x1)-fn(x0))

Global correlation helps prioritize components to check, but is insensitive to some scale errors and can be dominated by a few outliers. Examine absolute error of chosen candidates and sign changes. If the map was used to choose them, evaluate them on held-out pairs: otherwise selection and evaluation share the same noise.

Lab: reproducible sweep

The following run uses the published GPT-2 small alternative pinned by the first lesson, not the p06 checkpoint. It requires PyTorch, transformers, safetensors and huggingface_hub. It downloads weights once, checks their hash and saves map data to p11-ioi.json. Sufficient resources are needed for the model and sweep. The tokenizer validates single-token names and the tensor checks equal lengths; before extending pairs, inspect token-by-token alignment as well.

[ ]Replace heads and compare with gradientsLocal GPU
import json, os, hashlib
from pathlib import Path
import torch
from safetensors.torch import load_file
from transformers import AutoConfig, AutoTokenizer, GPT2LMHeadModel

torch.set_num_threads(2)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
repo='openai-community/gpt2'; rev='607a30d783dfa663caf39e06633721c8d4cfcd7e'
from huggingface_hub import hf_hub_download
weights=Path(hf_hub_download(repo, 'model.safetensors', revision=rev))
def sha256_file(path):
 h=hashlib.sha256()
 with path.open('rb') as f:
  for block in iter(lambda:f.read(8*1024*1024),b''):h.update(block)
 return h.hexdigest()
weight_hash=sha256_file(weights)
assert weight_hash == '248dfc3911869ec493c76e65bf2fcf7f615828b0254c12b473182f0f81d3a707'
cfg=AutoConfig.from_pretrained(repo,revision=rev,attn_implementation='eager')
tok=AutoTokenizer.from_pretrained(repo,revision=rev)
model=GPT2LMHeadModel(cfg)
sd=load_file(str(weights)); sd={k if k.startswith('transformer.') else 'transformer.'+k:v for k,v in sd.items() if not k.endswith(('.attn.bias','.attn.masked_bias'))}; sd['lm_head.weight']=sd['transformer.wte.weight']
model.load_state_dict(sd,strict=True);model.tie_weights();model.to(device).eval()
names=[('Mary','John'),('Alice','Bob'),('Sarah','Tom'),('Anna','James')]
clean=[f'When {a} and {b} went to the store, {b} gave a drink to' for a,b in names]
corrupt=[f'When {a} and {b} went to the store, {a} gave a drink to' for a,b in names]
ids=lambda ss: torch.tensor([tok.encode(s,add_special_tokens=False) for s in ss],device=device)
x=ids(clean);y=ids(corrupt)
assert x.shape==y.shape
assert torch.all((x != y).sum(dim=1) == 1), 'las parejas deben diferir en un único token alineado'
targets=torch.tensor([[tok.encode(' '+a,add_special_tokens=False)[0],tok.encode(' '+b,add_special_tokens=False)[0]] for a,b in names],device=device)
assert all(len(tok.encode(' '+n,add_special_tokens=False))==1 for pair in names for n in pair)
def metric(logits):
 z=logits[:,-1]; return (z.gather(1,targets[:,0,None])-z.gather(1,targets[:,1,None])).mean()
def forward(t): return model(t,use_cache=False).logits
def cache(t):
 out={}; hs=[]
 for layer,block in enumerate(model.transformer.h):
  def save(mod,args,l=layer): out[l]=args[0].detach().clone()
  hs.append(block.attn.c_proj.register_forward_pre_hook(save))
 try:
  with torch.no_grad(): score=float(metric(forward(t)))
 finally:
  for h in hs:h.remove()
 return score,out
c,cc=cache(x); b,bc=cache(y);den=c-b
assert abs(den)>1e-4
def patch(t,src,layer,head=None,pos=None):
 def hook(mod,args):
  z=args[0].clone(); sel=slice(None) if head is None else slice(head*64,(head+1)*64)
  p=slice(None) if pos is None else pos
  z[:,p,sel]=src[layer][:,p,sel];return (z,)+args[1:]
 h=model.transformer.h[layer].attn.c_proj.register_forward_pre_hook(hook)
 try:
  with torch.no_grad():return float(metric(forward(t)))
 finally:h.remove()
patch_heads=[];reverse=[]
for l in range(cfg.n_layer):
 patch_heads.append([(patch(y,cc,l,h)-b)/den for h in range(cfg.n_head)])
 reverse.append([(c-patch(x,bc,l,h))/den for h in range(cfg.n_head)])
print('modelo',repo,rev,'métrica limpia',c,'corrupta',b,'forma',x.shape,flush=True)
positions=[[(patch(y,cc,l,pos=p)-b)/den for p in range(x.shape[1])] for l in range(cfg.n_layer)]
positions_reverse=[[(c-patch(x,bc,l,pos=p))/den for p in range(x.shape[1])] for l in range(cfg.n_layer)]
grad={};hs=[]
for l,block in enumerate(model.transformer.h):
 def capture(mod,args,layer=l):
  z=args[0];z.retain_grad();grad[layer]=z
 hs.append(block.attn.c_proj.register_forward_pre_hook(capture))
try:
 model.zero_grad(set_to_none=True);metric(forward(y)).backward()
 attribution=[(grad[l].grad*(cc[l]-bc[l])).reshape(len(names),x.shape[1],cfg.n_head,64).sum((0,1,3)).detach().cpu().tolist() for l in range(cfg.n_layer)]
finally:
 for h in hs:h.remove()
import numpy as np
exact=np.array(patch_heads).ravel()*den; approx=np.array(attribution).ravel()
out={'source':repo+'@'+rev,'hash':weight_hash,'clean_prompts':clean,'corrupt_prompts':corrupt,'clean':c,'corrupt':b,'tokens':tok.convert_ids_to_tokens(x[0].tolist()),'heads':patch_heads,'reverse':reverse,'positions':positions,'positions_reverse':positions_reverse,'attribution':attribution,'pearson':float(np.corrcoef(exact,approx)[0,1])}
Path('p11-ioi.json').write_text(json.dumps(out,ensure_ascii=False,indent=2),encoding='utf-8')
print('pearson',out['pearson'],flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In this run Pearson correlation between exact effect and approximation is 0.992 across 144 heads. It is not an accuracy guarantee for other tasks or components: inspect individual residuals. The metric and both maps were calculated on the same four pairs, so they do not evaluate generalization. The code uses a pre-input hook on c_proj and removes it in finally; format depends on the GPT-2 implementation used.

For example, in head 8.6 the exact change is about 1.190 logits whereas the approximation gives 1.392. High correlation can rank many candidates in this sample but hides appreciable error for that component. If the distribution changes, measure again and compare ranks and signs as well, not only global correlation.

The following test isolates a particular path from head 5.5 to the inputs of head 8.10. An intermediate pass freezes corrupt attention and MLP writes except for the sender head and captures the receiver’s queries, keys and values. A new corrupt run inserts only the selected receiver input. The identity control inserts the corrupt state and must recover the corrupt metric exactly. The protocol also freezes MLPs and uses all positions: the result is for that direct pathway under those controls, not all paths between the heads.

[ ]One direct pathway and its controlsLocal GPU
# Prueba de un camino directo: emisor 5.5 a receptor 8.10, todas las posiciones.
# La pasada intermedia congela todas las escrituras de atención y MLP en el
# valor corrupto, salvo el emisor; guarda Q/K/V del receptor. En la última
# pasada se sustituye solo Q/K/V del receptor en una ejecución corrupta normal.
mlps={}; handles=[]
for l,block in enumerate(model.transformer.h):
 def save_mlp(mod,args,result,layer=l): mlps[layer]=result.detach().clone()
 handles.append(block.mlp.register_forward_hook(save_mlp))
try:
 with torch.no_grad(): baseline=float(metric(forward(y)))
finally:
 for h in handles:h.remove()
assert abs(baseline-b)<1e-5
sender=(5,5);receiver=(8,10)
def receiver_state(source):
 handles=[]; recorded={}
 for l,block in enumerate(model.transformer.h):
  def freeze_z(mod,args,layer=l):
   z=bc[layer].clone()
   if layer==sender[0]:
    s=slice(sender[1]*64,(sender[1]+1)*64);z[:,:,s]=source[layer][:,:,s]
   return (z,)+args[1:]
  def freeze_mlp(mod,args,result,layer=l):return mlps[layer]
  handles.append(block.attn.c_proj.register_forward_pre_hook(freeze_z))
  handles.append(block.mlp.register_forward_hook(freeze_mlp))
 def capture_qkv(mod,args,result):recorded['qkv']=result.detach().clone()
 handles.append(model.transformer.h[receiver[0]].attn.c_attn.register_forward_hook(capture_qkv))
 try:
  with torch.no_grad():forward(y)
 finally:
  for h in handles:h.remove()
 return recorded['qkv']
def transplant_receiver(qkv,part):
 def replace(mod,args,result):
  v=result.clone()
  for group in part:
   start=group*cfg.n_embd+receiver[1]*64
   v[:,:,start:start+64]=qkv[:,:,start:start+64]
  return v
 h=model.transformer.h[receiver[0]].attn.c_attn.register_forward_hook(replace)
 try:
  with torch.no_grad():return float(metric(forward(y)))
 finally:h.remove()
control=receiver_state(bc); transported=receiver_state(cc)
assert abs(transplant_receiver(control,[0,1,2])-b)<1e-5
path={name:(transplant_receiver(transported,groups)-b)/den for name,groups in [('q',[0]),('k',[1]),('v',[2]),('qkv',[0,1,2])]}
out['path_5_5_to_8_10']=path
Path('p11-ioi.json').write_text(json.dumps(out,ensure_ascii=False,indent=2),encoding='utf-8')
print('path',path,flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The run obtains recovery −0.0002 for queries, −0.0127 for keys, 0.0638 for values and 0.0583 replacing Q, K and V jointly. The difference between the sum of individual and joint results reflects interactions: these are not probabilities or contributions that must add up. This is one candidate edge, not a complete reconstruction.

Now replace six selected heads simultaneously and repeat omitting one at a time. These seven runs measure interactions on the initial four pairs; they are not obtained by adding individual effects.

[ ]Check the set of headsLocal GPU
selected=[(5,5),(7,9),(8,6),(8,10),(9,9),(10,0)]
def patched_set(heads):
 handles=[]
 for l in sorted({l for l,h in heads}):
  def replace(mod,args,layer=l):
   z=args[0].clone()
   for ll,h in heads:
    if ll==layer:
     s=slice(h*64,(h+1)*64);z[:,:,s]=cc[layer][:,:,s]
   return (z,)+args[1:]
  handles.append(model.transformer.h[l].attn.c_proj.register_forward_pre_hook(replace))
 try:
  with torch.no_grad(): return (float(metric(forward(y)))-b)/den
 finally:
  for h in handles:h.remove()
all_score=patched_set(selected)
without={f'{l}.{h}':patched_set([p for p in selected if p!=(l,h)]) for l,h in selected}
print(json.dumps({'all':all_score,'without':without,'clean':c,'corrupt':b}),flush=True)
Path('p11-joint.json').write_text(json.dumps({'all':all_score,'without':without,'clean':c,'corrupt':b},indent=2),encoding='utf-8')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The six heads recover 0.751 on this set of four pairs. Omitting 8.10 lowers recovery to 0.547; omitting 9.9 raises it to 0.797. A head can harm a joint intervention even if its individual patch was positive, due to interactions with the others.

For a separate check we use eight name pairs unseen during selection, with the same template. We measure the 14 possible forward pathways among these six heads using the QKV protocol above. Then we replace all heads outside the set with the mean of four reference examples and, separately, each candidate. The mean is calculated per position; MLPs remain active. With all heads replaced, the logit difference is 0.334; with the six candidates retained it is 2.191, versus 2.672 without ablation. Fidelity relative to that baseline is (2.191−0.334)/(2.672−0.334)=0.794. A fidelity of 1 would mean equality on this metric and these examples, not universality.

[ ]Pathways and mean ablation on held-out examplesLocal GPU
names=[('Peter','Paul'),('Lisa','David'),('Susan','Robert'),('Emma','Michael'),('Emily','Daniel'),('Laura','Steven'),('Karen','Richard'),('Nancy','Charles')]
clean=[f'When {a} and {b} went to the store, {b} gave a drink to' for a,b in names]
corrupt=[f'When {a} and {b} went to the store, {a} gave a drink to' for a,b in names]
ids=lambda ss: torch.tensor([tok.encode(s,add_special_tokens=False) for s in ss],device=device)
x=ids(clean);y=ids(corrupt)
assert x.shape==y.shape
targets=torch.tensor([[tok.encode(' '+a,add_special_tokens=False)[0],tok.encode(' '+b,add_special_tokens=False)[0]] for a,b in names],device=device)
assert all(len(tok.encode(' '+n,add_special_tokens=False))==1 for pair in names for n in pair)
def metric(logits):
 z=logits[:,-1]; return (z.gather(1,targets[:,0,None])-z.gather(1,targets[:,1,None])).mean()
def forward(t): return model(t,use_cache=False).logits
def cache(t):
 out={}; hs=[]
 for layer,block in enumerate(model.transformer.h):
  def save(mod,args,l=layer): out[l]=args[0].detach().clone()
  hs.append(block.attn.c_proj.register_forward_pre_hook(save))
 try:
  with torch.no_grad(): score=float(metric(forward(t)))
 finally:
  for h in hs:h.remove()
 return score,out
c,cc=cache(x); b,bc=cache(y);den=c-b
assert abs(den)>1e-4
def patch(t,src,layer,head=None,pos=None):
 def hook(mod,args):
  z=args[0].clone(); sel=slice(None) if head is None else slice(head*64,(head+1)*64)
  p=slice(None) if pos is None else pos
  z[:,p,sel]=src[layer][:,p,sel];return (z,)+args[1:]
 h=model.transformer.h[layer].attn.c_proj.register_forward_pre_hook(hook)
 try:
  with torch.no_grad():return float(metric(forward(t)))
 finally:h.remove()


# Cada vía congela escrituras corruptas de todas las cabezas y MLP salvo el emisor.
mlps={};hs=[]
for l,block in enumerate(model.transformer.h):
 def save(mod,args,out,layer=l):mlps[layer]=out.detach().clone()
 hs.append(block.mlp.register_forward_hook(save))
try:
 with torch.no_grad():metric(forward(y))
finally:
 for h in hs:h.remove()
selected=[(5,5),(7,9),(8,6),(8,10),(9,9),(10,0)]
def direct_edge(sender,receiver,source):
 handles=[];recorded={}
 for layer,block in enumerate(model.transformer.h):
  def freeze_z(mod,args,l=layer):
   z=bc[l].clone()
   if l==sender[0]:
    sl=slice(sender[1]*64,(sender[1]+1)*64);z[:,:,sl]=source[l][:,:,sl]
   return (z,)+args[1:]
  def freeze_mlp(mod,args,out,l=layer):return mlps[l]
  handles.append(block.attn.c_proj.register_forward_pre_hook(freeze_z))
  handles.append(block.mlp.register_forward_hook(freeze_mlp))
 def capture(mod,args,out):recorded['qkv']=out.detach().clone()
 handles.append(model.transformer.h[receiver[0]].attn.c_attn.register_forward_hook(capture))
 try:
  with torch.no_grad():forward(y)
 finally:
  for h in handles:h.remove()
 qkv=recorded['qkv']
 def replace(mod,args,out):
  z=out.clone()
  for group in (0,1,2):
   start=group*cfg.n_embd+receiver[1]*64;z[:,:,start:start+64]=qkv[:,:,start:start+64]
  return z
 h=model.transformer.h[receiver[0]].attn.c_attn.register_forward_hook(replace)
 try:
  with torch.no_grad():return float(metric(forward(y)))
 finally:h.remove()
destination=Path(f'p11-l05-pathgraph-{device}.json')
saved=json.loads(destination.read_text(encoding='utf-8')) if destination.exists() else None
if saved:
 assert abs(saved['clean']-c)<1e-5 and abs(saved['corrupt']-b)<1e-5
edges=saved['edges'] if saved else []
for sender in selected:
 for receiver in selected:
  if sender[0]>=receiver[0]:continue
  if any(edge['sender']==list(sender) and edge['receiver']==list(receiver) for edge in edges):continue
  control=direct_edge(sender,receiver,bc);assert abs(control-b)<1e-5
  score=(direct_edge(sender,receiver,cc)-b)/den
  edge={'sender':list(sender),'receiver':list(receiver),'recovered':score}
  edges.append(edge);print(edge,flush=True)
  tmp=destination.with_suffix('.tmp');tmp.write_text(json.dumps({'clean':c,'corrupt':b,'edges':edges},indent=2),encoding='utf-8');tmp.replace(destination)


reference_names=[('Mary','John'),('Alice','Bob'),('Sarah','Tom'),('Anna','James')]
reference=ids([f'When {a} and {b} went to the store, {b} gave a drink to' for a,b in reference_names])
assert reference.shape[1]==x.shape[1]
reference_cache={};handles=[]
for l,block in enumerate(model.transformer.h):
 def save(mod,args,layer=l):reference_cache[layer]=args[0].detach().mean(0,keepdim=True)
 handles.append(block.attn.c_proj.register_forward_pre_hook(save))
try:
 with torch.no_grad():forward(reference)
finally:
 for h in handles:h.remove()
chosen={(5,5),(7,9),(8,6),(8,10),(9,9),(10,0)}
all_heads={(l,h) for l in range(cfg.n_layer) for h in range(cfg.n_head)}
def ablate_set(to_ablate):
 handles=[]
 for l in range(cfg.n_layer):
  heads=[h for ll,h in to_ablate if ll==l]
  if not heads:continue
  def replace(mod,args,layer=l,heads=heads):
   z=args[0].clone()
   for h in heads:
    sl=slice(h*64,(h+1)*64);z[:,:,sl]=reference_cache[layer][:,:,sl]
   return (z,)+args[1:]
  handles.append(model.transformer.h[l].attn.c_proj.register_forward_pre_hook(replace))
 try:
  with torch.no_grad():return float(metric(forward(x)))
 finally:
  for h in handles:h.remove()
destination=Path(f'p11-l05-mean-ablation-{device}.json')
progress=json.loads(destination.read_text(encoding='utf-8')) if destination.exists() else {'clean':c,'corrupt':b,'remove':{}}
assert abs(progress['clean']-c)<1e-5 and abs(progress['corrupt']-b)<1e-5
def save():
 tmp=destination.with_suffix('.tmp');tmp.write_text(json.dumps(progress,indent=2),encoding='utf-8');tmp.replace(destination)
def stage(key,heads):
 if key not in progress:progress[key]=ablate_set(heads);save()
 return progress[key]
full=stage('full',set()); assert abs(full-c)<1e-5
mean_all=stage('mean_all',all_heads);circuit=stage('circuit',all_heads-chosen)
full_without=stage('full_without',chosen)
for l,h in sorted(chosen):
 key=f'{l}.{h}'
 if key not in progress['remove']:
  progress['remove'][key]=ablate_set((all_heads-chosen)|{(l,h)});save()
remove=progress['remove']
out={'full':full,'mean_all':mean_all,'circuit':circuit,'full_without':full_without,'remove':remove,
 'relative_fidelity':(circuit-mean_all)/(full-mean_all) if abs(full-mean_all)>1e-5 else None,
 'reference_names':reference_names,'heldout_names':names}
progress.update(out);save()
print(json.dumps(out),flush=True)

This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
InteractivePathways and ablations on held-out examples
  • Positive effect
  • Negative effect
5.5 → 7.9: 0.0825.5 → 8.6: 0.1745.5 → 8.10: 0.0737.9 → 9.9: 0.0357.9 → 10.0: 0.0348.6 → 9.9: 0.0838.6 → 10.0: 0.0458.10 → 9.9: 0.0478.10 → 10.0: 0.0585.57.98.68.109.910.0

Edges measure a QKV intervention with other writes frozen; their values are not recomputed when ablating. The metric comes from a separate test: heads outside the set and the chosen head are replaced by their mean, with MLPs intact.

0.03
Pathway: fraction recovered0.174
Circuit metric2.191
Normalized fidelity0.794
Head replaced by meannone
Select a pathway or threshold and replace a candidate head by its mean. Arrows show individual QKV interventions; ablation numbers come from independent joint runs.

The arrows are direct effects measured separately with other writes frozen, not additive contributions. Ablating a head changes the joint metric and hides its arrows in the diagram; it does not remeasure other pathways. Eight pairs from one template and a four-example reference limit generalization. The achieved fidelity does not show completeness or minimality of the circuit; paths between excluded components and other distributions remain open. These results belong to published GPT-2; below we examine a different trained model of our own.

A different task in our own model

The p06 checkpoint is unavailable. As an additional check we use the one-layer, four-head transformer trained on modulo-113 addition in p11-l03; this is a different model of our own, not the p06 GPT. Download its 40,000-step checkpoint, save it beside the lab and verify the SHA-256 in the code. Inputs are three tokens (a,b,=); the target is (a+b) mod 113. The training set is stored inside the checkpoint.

With a fixed seed we choose 64 pairs such that both (a,b) and (a,b+1 mod 113) are outside training. The metric compares the logits of the two sums on both inputs. In this sample the model gets all 64 examples right in each condition; mean clean difference is 125.202 and corrupt −124.337. Those large margins belong to this task and are not directly comparable to IOI margins.

[ ]Patching held-out modular additionLocal GPU
"""Patching en el transformer de suma modular propio, no el GPT de p06."""
import os,hashlib,itertools,json,random
from pathlib import Path
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F

torch.set_num_threads(1)
P,D,H=113,128,4
class AdditionTransformer(nn.Module):
    def __init__(self):
        super().__init__()
        self.token = nn.Embedding(P+1, D)
        self.position = nn.Embedding(3, D)
        self.q = nn.Linear(D,D,bias=False)
        self.k = nn.Linear(D,D,bias=False)
        self.v = nn.Linear(D,D,bias=False)
        self.o = nn.Linear(D,D,bias=False)
        self.fc = nn.Linear(D,4*D)
        self.proj = nn.Linear(4*D,D)
        self.unembed = nn.Linear(D,P,bias=False)
    def forward(self, x):
        r = self.token(x) + self.position(torch.arange(3,device=x.device))
        q = self.q(r[:,2:3]).reshape(-1,1,H,D//H).transpose(1,2)
        k = self.k(r).reshape(-1,3,H,D//H).transpose(1,2)
        v = self.v(r).reshape(-1,3,H,D//H).transpose(1,2)
        z = F.scaled_dot_product_attention(q,k,v).transpose(1,2).reshape(-1,D)
        r = r[:,2] + self.o(z)
        r = r + self.proj(F.relu(self.fc(r)))
        return self.unembed(r)

path=Path(os.environ.get('P11_GROK_CKPT','suma-modular-model-40000.pt'))
sha=hashlib.sha256(path.read_bytes()).hexdigest()
assert sha=='cb2fa116f9babb818f2902ac9b7e88914d4be1eced4aeaa7c99ea7ccb205626a'
checkpoint=torch.load(path,weights_only=True,map_location='cpu')
model=AdditionTransformer();model.load_state_dict(checkpoint['model']);model.eval()
training=set(map(tuple,checkpoint['train_pairs']))
pool=[(a,b) for a in range(P) for b in range(P) if (a,b) not in training and (a,(b+1)%P) not in training]
random.Random(1818).shuffle(pool);pairs=pool[:64]
assert len(pairs)==64
x=torch.tensor([[a,b,P] for a,b in pairs]);y=torch.tensor([[a,(b+1)%P,P] for a,b in pairs])
answer=torch.tensor([[(a+b)%P,(a+b+1)%P] for a,b in pairs])
def metric(logits):
 return (logits.gather(1,answer[:,0,None])-logits.gather(1,answer[:,1,None])).mean()
def capture(inputs):
 box={}
 def save(mod,args):box['z']=args[0].detach().clone()
 hook=model.o.register_forward_pre_hook(save)
 try:
  with torch.no_grad():logits=model(inputs);score=float(metric(logits))
 finally:hook.remove()
 return score,box['z'],logits
clean,cz,lc=capture(x);corrupt,bz,lb=capture(y);den=clean-corrupt
assert den>1e-5
clean_accuracy=float((lc.argmax(-1)==answer[:,0]).float().mean())
corrupt_accuracy=float((lb.argmax(-1)==answer[:,1]).float().mean())
def patch(heads,source=cz):
 def substitute(mod,args):
  z=args[0].clone()
  for head in heads:z[:,head*32:(head+1)*32]=source[:,head*32:(head+1)*32]
  return (z,)+args[1:]
 hook=model.o.register_forward_pre_hook(substitute)
 try:
  with torch.no_grad():return float(metric(model(y)))
 finally:hook.remove()
assert abs(patch(range(H),bz)-corrupt)<1e-6
exact=[(patch([h])-corrupt)/den for h in range(H)]
groups={'+'.join(map(str,heads)):(patch(heads)-corrupt)/den
        for n in range(1,4) for heads in itertools.combinations(range(H),n)}
box={}
def with_grad(mod,args):
 z=args[0].detach().clone().requires_grad_(True);box['z']=z;return (z,)+args[1:]
hook=model.o.register_forward_pre_hook(with_grad)
try:metric(model(y)).backward()
finally:hook.remove()
approx=(box['z'].grad*(cz-bz)).reshape(len(pairs),H,32).sum((0,2))/den
approx=approx.detach().tolist()
out={'model':'transformer propio de suma modular, 1 capa, 4 cabezas',
 'checkpoint_sha256':sha,'task':'(a+b) mod 113','corruption':'b -> b+1 mod 113',
 'selection':'64 parejas limpias y corruptas fuera de train, semilla 1818','pairs':pairs,
 'clean':clean,'corrupt':corrupt,'clean_accuracy':clean_accuracy,'corrupt_accuracy':corrupt_accuracy,
 'head_recovery':exact,'group_recovery':groups,
 'attribution':approx,'pearson':float(np.corrcoef(exact,approx)[0,1])}
Path('p11-suma-patching.json').write_text(json.dumps(out,indent=2),encoding='utf-8')
print(json.dumps({k:v for k,v in out.items() if k!='pairs'},indent=2),flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Heads 0, 1, 2 and 3 individually recover 0.182, 0.191, 0.306 and 0.313. Heads 1+2+3 recover 0.831 jointly; the code runs the combination, it does not sum their effects. Correlation between gradient-times-difference and exact patching is 0.994 for only four heads; do not extrapolate it to other inputs. This single-layer architecture computes its heads in parallel: it contains no sequential paths between heads in different layers. It therefore complements the IOI test and does not reproduce a multilayer circuit.

Exercises

Numeric
The clean mean logit difference is 4.2, the corrupt one 0.2 and the patched one 3.2. What fraction is recovered?
Quiz
What does clean-to-corrupt patching compare?
Quiz
A gradient approximation is large but exact patching is almost zero. What do you conclude?
Code
Implement patch_head(model, clean_cache, layer, head, corrupt_tokens, metric). The model exposes model.transformer.h[layer].attn.c_proj and config.n_embd and config.n_head. clean_cache[layer] is the clean concatenated input to c_proj, shaped batch by position by dimension. Replace all positions of one head in a copy, run model(corrupt_tokens), apply metric to the result and remove the hook even if the metric fails. Return the metric value.
def patch_head(model, clean_cache, layer, head, corrupt_tokens, metric):
  pass
Shift+Enter to run
Key idea
A causal explanation names the intervention, context, metric and controls. The individual map identifies candidates; a circuit requires checking paths and joint behavior.