Module contents
Lesson 17 of 39Core 105 min

Causal interventions: activation patching and ablations

Move from correlation to causal interventions within a network. Compare activation patching, ablation, causal tracing, path patching and attribution patching using explicit models and measured experiments.

After this lesson you can

  • Design aligned clean and corrupted prompt pairs and a suitable task metric.
  • Implement residual stream, head and MLP patching by layer and position.
  • Explain the asymmetry between restoration and corruption using AND and OR circuits.
  • Choose zero, mean or resampling ablation according to the question.
  • Derive attribution patching as a first-order approximation and measure where it fails.

Before you start

From presence to intervention

A probe may detect information in an activation without showing that the model depends on it. Activation patching compares two runs and replaces an activation from one with its counterpart from the other. The resulting change in output answers a specific intervention question. It does not, on its own, turn a correlation into a complete explanation of the algorithm. Before patching, define the task, position, metric, input pairs and variable being changed.

In the figure, the clean run has two active paths and the corrupted run has two inactive paths. With OR, restoring either path recovers the output, but corrupting just one does not change it. Switch to AND to reverse this relationship. This is an explicit Boolean model, not a measurement from a trained network.

InteractiveRestoring and corrupting
Path A
1
intervened
Path B
0
unchanged
Gate OR → 1
Gate
Intervention
Intervened path
Output after intervention1
Choose OR or AND, the direction of the intervention, and a path. OR has redundancy; with AND, both paths are necessary for output 1.

Restoration tests sufficiency in the chosen corrupted background; corruption tests necessity in the chosen clean background. Neither guarantees sufficiency or necessity in every context. Redundant paths can conceal an individual effect, and simultaneous replacements can break dependencies in ways that do not resemble natural runs.

Intervention design and metrics

Let ac\vb{a}_c be the clean activation and ar\vb{a}_r the corrupted activation at the same site and position. Run the corrupted input up to that site, replace ar\vb{a}_r with ac\vb{a}_c, and let the rest of the network continue. Patching metrics include logit difference, probability and divergence between distributions. For a scalar metric mm that should increase when clean behavior is recovered, a common fraction is

R=mparcheado−mcorruptomlimpio−mcorrupto.R=\frac{m_{\text{parcheado}}-m_{\text{corrupto}}}{m_{\text{limpio}}-m_{\text{corrupto}}}.

The expression is undefined when the denominator is zero and unstable when it is small. It can be negative or greater than 1: it is not a probability. Logit difference avoids some softmax saturation, but depends on which answers are compared. Choose the metric before inspecting the map and publish the unnormalized values as well. Zhang and Nanda show that metric and corruption choices can change localization conclusions.

A pair of prompts should align positions and change the property under study. If subject, length and syntax all change at once, a patch sensitive to any of them may look like subject localization. Check tokenization and use several pairs and controls. Restoring an entire residual stream includes many writes and their scale; it does not identify a single head or neuron.

Ablation and mediation

Ablations replace an activation with a reference value. Zero asks about an intervention that may be out of distribution; the mean removes individual variation but can itself be an unnatural state; resampling uses another observed activation, although it may break correlations with the rest of the example. No choice is universal. Compare baselines, report how donors are selected, and keep selection and evaluation data independent.

Causal tracing uses corruption and restoration to locate regions that recover a metric. Meng and colleagues apply this approach to factual associations and editing. The map depends on the corruption and intervention site: restoration after noise does not automatically amount to an intervention on a real-world fact.

Path patching attempts to isolate a path between sender and receiver by fixing or replacing other activations according to a protocol. This relates to direct and indirect effects, but hybrid states may not be realizable as natural inputs. Specify what is frozen, what is recomputed and the reference distribution before calling an effect direct or indirect.

Approximating a sweep

Attribution patching approximates the effect of replacing ar\vb{a}_r with ac\vb{a}_c using the gradient of the metric evaluated on the corrupted run:

m(ac)−m(ar)≈(ac−ar)⊤∇am(ar).m(\vb{a}_c)-m(\vb{a}_r)\approx (\vb{a}_c-\vb{a}_r)\T\grad_{\vb{a}}m(\vb{a}_r).

This is the first-order Taylor term for the rest of the network under the specified intervention. It is exact when mm is affine in that activation. In general, the remainder depends on curvature along the entire segment, not just the local gradient. Saturated attention can produce a small gradient even when the patch crosses a region of change; cancellation between paths can yield false negatives. AtP* addresses these failures with specific corrections, including softmax recomputation for queries and keys. An estimate can prioritize exact interventions; it does not replace their validation.

InteractiveWhen the local gradient fails
Toy function: σ(x) = 1 / (1 + exp(−x)). The patch moves x from −6.0 to 2.0.
The slope at the starting point is σ(a)(1−σ(a)) = 0.0025. Multiplying by the displacement gives the first-order estimate.
The exact patch evaluates both endpoints. The local slope does not account for the intervening curvature.
Patch endpoints
Exact change0.878
Local approximation0.020
A toy sigmoid shows why a small gradient at the corrupted endpoint can underestimate a large replacement. This is not a GPT-2 measurement.

At the saturated endpoint in the figure, the slope is small even though the displacement crosses the center of the curve. AtP* recomputes the change in attention probabilities for query and key patches before approximating the rest; GradDrop modifies gradients of residual contributions to diagnose cancellation. Both still require verification, and neither guarantees freedom from false negatives. Interventions in subspaces can also produce illusions: finding a projection that changes an output does not prove that the model uses the interpreted variable in the proposed way. Compare controls and alternatives as recommended by Makelov and colleagues.

A measured sweep in GPT-2

In an aligned pair, we replace “France” with “Italy” at the same position and measure m=zParis−zRomem=z_{\text{Paris}}-z_{\text{Rome}} at the final token. With the pinned revision of GPT-2 small, the clean value is 2.457 and the corrupted value is −5.253. You can also replace only “is” with “was”: the corrupted metric is then 2.303, a difference of just 0.154 from clean. The grid shows the absolute change relative to the corrupted run, one intervention per cell. Residual means the complete block output; attention and MLP are outputs of each submodule, not individual heads. Layers and positions start at zero. Normalized recovery divides by the clean–corrupted difference and is not restricted to [0,1]; the tense pair illustrates its instability as the denominator shrinks.

InteractiveExact patch versus attribution

GPT-2 small · corrupted: The capital of Italy is · clean: The capital of France is

Each cell is a logit change (Paris − Rome); blue is positive and red negative. Layers are numbered from 0.

LayerThecapitalofItalyis01234567891011
Prompt change
Activation
Show
Clean metric2.457
Corrupted metric−5.253
Exact change7.677
Gradient estimate3.790
Exact recovery0.996
Choose the token to change, activation type, estimator and cell. Blue means an increase and red a decrease in logit difference. Two pairs do not identify a general factual mechanism.

For example, at the country position after block 0, the residual patch changes the difference by 7.677 logits, while the local gradient estimates 3.790. These values describe this pair, not a general error rate. The residual contains all accumulated contributions; restoring it after the final block at the final position reproduces the clean readout by construction, and does not establish that this layer stores the fact.

To separate softmax saturation from other errors, the next sweep intervenes only on a head’s query at the country position. QK-fix exactly recomputes attention probabilities after replacing that query, holding corrupted keys fixed, and propagates the change using the metric gradient with respect to probabilities in the corrupted run. We also combine this correction with GradDrop: in each of twelve backward passes we zero the gradient of one layer’s residual contribution, sum the magnitudes of the twelve estimates and divide by eleven. This adapts AtP* to the chosen restoration direction and these specific queries.

InteractiveComponents: exact effects and estimates
144 patches measured on GPT-2 small. Each point represents a component and position; the axes show the exact and estimated changes in logit difference. The diagonal means agreement.
Horizontal: exact effect; vertical: estimate. Both axes retain the sign. Symmetric scale ±0.288 logits. When all layers are selected, the first match is highlighted. Select one layer to specify the site.
Mean absolute error0.00335
Selected sitelayer 0, head 1, position 3
Exact patch−0.05647
Estimate−0.00141
Measured results for queries, head outputs and MLPs on one factual pair in GPT-2 small. QK-fix is compared on queries without hiding cases where it gets worse.

Across these 144 queries, mean absolute error falls from 0.00335 to 0.00250 logits, but does not fall in every case. With a 0.000001 margin it improves 104, worsens 26 and stays practically equal for 14. For example, layer 0 head 1 has exact effect −0.05647, approximation −0.00141 and correction −0.05574; layer 3 head 4 has −0.01900, −0.02018 and −0.06763. These describe one pair and position, not a population success rate. The correction does not exactly approximate the whole downstream network, so it can still fail.

GradDrop produces a magnitude score, not a signed effect: compare it with the absolute exact-patch effect. For this pair its mean absolute magnitude error is 0.00319, versus 0.00249 for QK-fix alone. With the same margin it improves 31 queries, worsens 99 and leaves 14 practically unchanged. This does not contradict improvement on other datasets. It shows that corrections do not always dominate and must be validated on the chosen problem.

Localizing heads in a model of your own

We trained a small transformer with two layers and four heads per layer on artificial sequences that repeat a list of distinct symbols. Training lengths range from 8 to 16; the task was explicitly designed to make repetition useful. At step 1500, selected by a validation criterion fixed beforehand, accuracy on the second copy of 128 independent sequences of length 16 is 0.9883. At length 20, outside the training range, it falls to 0.5234. This is not the TinyStories-trained model from the preceding lesson and is not evidence of a transition in natural language.

In the length-16 test, the first three heads of the second layer assign approximately 0.912, 0.925 and 0.909 of attention to the position following the previous occurrence of the symbol; the uniform reference is 0.043. Ablating each raises loss on the second copy by 0.439, 0.516 and 0.581 respectively. These observations suggest an induction mechanism in this task, although neither high attention nor a single ablation establishes the whole circuit.

InteractiveRestoring heads in repeated sequences
One successor token in the first copy changes; the second is preserved up to the query. Each bar restores one head output at a position and measures the mean change in logit difference for the original versus replaced successor.
0.00.10.20.31.01.11.21.3
Heads use the label layer.head. A bar to the right increases the metric; one to the left decreases it. The second-copy query is at position 21 and the changed successor at position 6.
21
Clean difference7.755
Corrupted difference−7.458
Largest effect at this position5.368
Exact patches of 248 head-position outputs on 64 new artificial pairs; position 21 is the chosen query.

Each pair changes the successor in the first copy and keeps the second copy unchanged up to the query. The metric compares logits of the original and replacement successors. The clean mean is 7.755 and the corrupted mean −7.458; restoring head 0’s output in the second layer at the query raises the mean by 5.368. Heads 1 and 2 also recover 4.825 and 5.252 respectively. The pattern is consistent with redundancy. Do not add these effects as if they were independent or extrapolate to other seeds or models.

A circuit you can check

The continuous gates fAND(a,b)=abf_{\mathrm{AND}}(a,b)=ab and fOR(a,b)=a+b−abf_{\mathrm{OR}}(a,b)=a+b-ab coincide with AND and OR on Boolean inputs. Mean and resampling are controls for this example; they do not reproduce a transformer.

[ ]Restore, corrupt and choose a referenceBrowser
import numpy as np

def gate(a, b, kind):
    return a*b if kind == 'AND' else a+b-a*b

clean, corrupt = np.array([1., 1.]), np.array([0., 0.])
for kind in ('AND', 'OR'):
    restore = corrupt.copy(); restore[0] = clean[0]
    damage = clean.copy(); damage[0] = corrupt[0]
    print(kind, 'limpia:', gate(*clean, kind), 'corrupta:', gate(*corrupt, kind),
          'restaurar A:', gate(*restore, kind), 'corromper A:', gate(*damage, kind))

reference = np.array([0., 1.])
rng = np.random.default_rng(17)
for name, value in [('cero', 0.), ('media', reference.mean()), ('remuestreo', rng.choice(reference))]:
    print(name, 'OR con B=0:', gate(value, 0., 'OR'))

Local lab: exact and gradient sweep

Install torch and transformers in your local environment. The following program downloads the specified revision if it is not cached, checks tokenization, and runs 180 individual patches and 36 backward passes. Change CORRUPCION to reproduce either option in the figure. It uses CUDA if available; CPU can take longer. It does not implement AtP* or path patching or establish a population conclusion. Expand the set of pairs before generalizing. Hooks are removed even if a run fails.

[ ]Patch residual, attention and MLP in GPT-2Local GPU
import json, torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from pathlib import Path

torch.set_num_threads(1)
rev='607a30d783dfa663caf39e06633721c8d4cfcd7e'
name='openai-community/gpt2'
tok=AutoTokenizer.from_pretrained(name,revision=rev)
model=AutoModelForCausalLM.from_pretrained(name,revision=rev,attn_implementation='eager').eval()
model.to('cuda' if torch.cuda.is_available() else 'cpu')
device=next(model.parameters()).device
clean=tok('The capital of France is',return_tensors='pt').input_ids.to(device)
CORRUPCION='país'  # cambia por 'tiempo' para el segundo par
corrupt_text={'país':'The capital of Italy is','tiempo':'The capital of France was'}[CORRUPCION]
corrupt=tok(corrupt_text,return_tensors='pt').input_ids.to(device)
assert clean.shape==corrupt.shape
paris=tok.encode(' Paris',add_special_tokens=False); rome=tok.encode(' Rome',add_special_tokens=False)
assert len(paris)==len(rome)==1

def metric(out): return out.logits[0,-1,paris[0]]-out.logits[0,-1,rome[0]]
modules={}
for i,b in enumerate(model.transformer.h):
    modules[('residual',i)]=b
    modules[('attention',i)]=b.attn
    modules[('mlp',i)]=b.mlp

def tensor(out): return out[0] if isinstance(out,tuple) else out

def capture(ids):
    cache={}; hs=[]
    for key,mod in modules.items():
        def hook(module,args,out,k=key): cache[k]=tensor(out).detach().clone()
        hs.append(mod.register_forward_hook(hook))
    try:
        with torch.no_grad(): m=float(metric(model(ids,use_cache=False)))
    finally:
        for h in hs: h.remove()
    return m,cache

mc,cache_c=capture(clean); mr,cache_r=capture(corrupt)
assert abs(mc-mr)>1e-5
print('baseline',mc,mr,flush=True)
rows=[]
for kind in ['residual','attention','mlp']:
    for layer in range(12):
        key=(kind,layer)
        for pos in range(clean.shape[1]):
            def patch(module,args,out):
                x=tensor(out).clone(); x[:,pos,:]=cache_c[key][:,pos,:]
                return (x,)+out[1:] if isinstance(out,tuple) else x
            handle=modules[key].register_forward_hook(patch)
            try:
                with torch.no_grad(): patched=float(metric(model(corrupt,use_cache=False)))
            finally: handle.remove()
            rows.append({'kind':kind,'layer':layer,'position':pos,'exact':patched-mr,'recovery':(patched-mr)/(mc-mr)})
        print(kind,layer,flush=True)
# Separate gradient forward runs avoid dependencies between retained intermediate tensors.
for kind in ['residual','attention','mlp']:
    for layer in range(12):
        key=(kind,layer); saved=[]
        def keep(module,args,out):
            x=tensor(out); x.retain_grad(); saved.append(x)
        handle=modules[key].register_forward_hook(keep)
        try:
            model.zero_grad(set_to_none=True)
            metric(model(corrupt,use_cache=False)).backward()
            g=saved[0].grad.detach()
            delta=cache_c[key]-cache_r[key]
            values=(g*delta).sum(dim=-1)[0]
            for pos in range(clean.shape[1]):
                row=next(r for r in rows if r['kind']==kind and r['layer']==layer and r['position']==pos)
                row['attribution']=float(values[pos])
        finally: handle.remove()
print('gradient done',flush=True)
result={'model':name,'revision':rev,'clean':'The capital of France is','corrupt':corrupt_text,'clean_tokens':[tok.decode([int(x)]) for x in clean[0]],'corrupt_tokens':[tok.decode([int(x)]) for x in corrupt[0]],'targets':[' Paris',' Rome'],'clean_metric':mc,'corrupt_metric':mr,'rows':rows}
print('Máximo error absoluto:', max(abs(r['exact']-r['attribution']) for r in rows))
print('Residual capa 0, país:', next(r for r in rows if r['kind']=='residual' and r['layer']==0 and r['position']==3))
print('Barrido terminado', flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Sweep individual head outputs

To distinguish a full attention output from its contributions, we capture the input to the output projection, where each head’s components are still concatenated. The patch replaces only the 64 channels of one head before the shared projection. We compute 720 exact patches and their linear approximation across 12 layers, 12 heads and five positions. In this pair, the largest absolute effect was 3.632 logits at layer 9, head 8, position 4; its estimate was 3.276. Selecting the largest effect after the sweep does not establish general importance without further pairs and controls.

[ ]Patch GPT-2 head outputsLocal GPU
import json,torch
from transformers import AutoTokenizer,AutoModelForCausalLM
torch.set_num_threads(1);rev='607a30d783dfa663caf39e06633721c8d4cfcd7e';name='openai-community/gpt2'
tok=AutoTokenizer.from_pretrained(name,revision=rev);model=AutoModelForCausalLM.from_pretrained(name,revision=rev,attn_implementation='eager').eval();model.to('cuda' if torch.cuda.is_available() else 'cpu');device=next(model.parameters()).device
clean=tok('The capital of France is',return_tensors='pt').input_ids.to(device);corrupt=tok('The capital of Italy is',return_tensors='pt').input_ids.to(device)
paris=tok.encode(' Paris',add_special_tokens=False)[0];rome=tok.encode(' Rome',add_special_tokens=False)[0]
def metric(out):return out.logits[:,-1,paris]-out.logits[:,-1,rome]
def capture(ids,grad=False):
 acts={};hooks=[]
 for layer,block in enumerate(model.transformer.h):
  def keep(module,args,i=layer):
   x=args[0]
   if grad:x.retain_grad();acts[i]=x
   else:acts[i]=x.detach().clone()
  hooks.append(block.attn.c_proj.register_forward_pre_hook(keep))
 try:
  if grad:
   model.zero_grad(set_to_none=True);out=model(ids,use_cache=False);metric(out).sum().backward();return float(metric(out)[0].detach()),acts
  with torch.no_grad():return float(metric(model(ids,use_cache=False))[0]),acts
 finally:
  for h in hooks:h.remove()
mc,c=capture(clean);mr,r=capture(corrupt,True);rows=[];heads=12;width=64
for layer,block in enumerate(model.transformer.h):
 for pos in range(clean.shape[1]):
  plain=((c[layer]-r[layer]).detach()*r[layer].grad)[0,pos].reshape(heads,width).sum(-1)
  def patch(module,args):
   x=args[0].clone()
   for h in range(heads):x[h,pos,h*width:(h+1)*width]=c[layer][0,pos,h*width:(h+1)*width]
   return (x,)+args[1:]
  hook=block.attn.c_proj.register_forward_pre_hook(patch)
  try:
   with torch.no_grad():exact=metric(model(corrupt.expand(heads,-1).contiguous(),use_cache=False))-mr
  finally:hook.remove()
  for h in range(heads):rows.append({'layer':layer,'head':h,'position':pos,'exact':float(exact[h]),'attribution':float(plain[h])})
 print('capa',layer,'terminada',flush=True)
biggest=max(rows,key=lambda x:abs(x['exact']));print('limpio',mc,'corrupto',mr,'parches',len(rows),'mayor efecto absoluto',biggest)
import matplotlib.pyplot as plt
x=[r['exact'] for r in rows];y=[r['attribution'] for r in rows];limit=max(map(abs,x+y))
plt.scatter(x,y,c=[r['layer'] for r in rows],s=8,alpha=.5,cmap='viridis');plt.plot([-limit,limit],[-limit,limit],'k--');plt.xlabel('Parchado exacto');plt.ylabel('Atribución lineal');plt.colorbar(label='Capa');plt.show()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Train and patch a synthetic model

The lab reproduces training and all 248 patches. It uses PyTorch and NumPy, chooses the stopping point by validation accuracy, prefix attention and ablation effect, and then evaluates independent sequences. With ORYON_QUICK=1 it runs only four steps and eight pairs to check the flow. That option does not reproduce the trained results in the figure. A single seed and a stop selected on validation do not replace independent repetitions.

[ ]Train and localize repetition headsLocal GPU
import json,torch,numpy as np
import os
QUICK=os.environ.get('ORYON_QUICK')=='1'
from torch import nn
import torch.nn.functional as F
torch.set_num_threads(1);torch.manual_seed(170);device='cuda' if torch.cuda.is_available() else 'cpu'
V,D,H,T,B=32,64,4,40,32
class Net(nn.Module):
 def __init__(self):
  super().__init__();self.embed=nn.Embedding(V,D);self.pos=nn.Embedding(T,D);self.qkv=nn.ModuleList([nn.Linear(D,3*D,bias=False) for _ in range(2)]);self.out=nn.ModuleList([nn.Linear(D,D,bias=False) for _ in range(2)]);self.unembed=nn.Linear(D,V,bias=False)
 def forward(self,x,ablate=None):
  b,t=x.shape;r=self.embed(x)+self.pos(torch.arange(t,device=x.device));patterns=[]
  for l in range(2):
   q,k,v=self.qkv[l](r).chunk(3,dim=-1)
   q,k,v=[z.view(b,t,H,D//H).transpose(1,2) for z in (q,k,v)]
   [email protected](-1,-2)/(D//H)**.5;mask=torch.ones(t,t,device=x.device,dtype=torch.bool).tril();a=scores.masked_fill(~mask,float('-inf')).softmax(-1)
   y=a@v
   if ablate is not None and ablate[0]==l:
    gate=torch.ones(H,device=x.device);gate[ablate[1]]=0;y=y*gate[None,:,None,None]
   r=r+self.out[l](y.transpose(1,2).reshape(b,t,D));patterns.append(a)
  return self.unembed(r),patterns
def sample(n,b,g):
 base=torch.stack([torch.randperm(V,generator=g)[:n] for _ in range(b)]).to(device);return torch.cat([base,base],dim=1)
def evaluate(model,n=16,seed=None):
 model.eval();x=sample(n,128,torch.Generator().manual_seed(1701+n if seed is None else seed));inp=x[:,:-1];truth=x[:,1:];q=torch.arange(n,2*n-1,device=device)
 with torch.no_grad():
  logits,patterns=model(inp);loss=F.cross_entropy(logits.transpose(1,2),truth,reduction='none');late=loss[:,n-1:].mean().item();acc=(logits[:,n-1:].argmax(-1)==truth[:,n-1:]).float().mean().item()
  prefix=[p[:,:,q,q-n+1].mean(dim=(0,2)).tolist() for p in patterns];uniform=(1/(q+1).float()).mean().item();ablations=[]
  for l in range(2):
   row=[]
   for h in range(H):
    pred,_=model(inp,ablate=(l,h));ll=F.cross_entropy(pred.transpose(1,2),truth,reduction='none')[:,n-1:].mean().item();row.append(ll-late)
   ablations.append(row)
  return {'length':n,'late_loss':late,'late_accuracy':acc,'prefix':prefix,'uniform':uniform,'ablation_loss_change':ablations}
model=Net().to(device);opt=torch.optim.AdamW(model.parameters(),lr=.001);g=torch.Generator().manual_seed(1700);results=[]
for step in range(5 if QUICK else 3001):
 if step in ((0,4) if QUICK else (0,100,250,500,1000,1500,2000,2500,3000)):
  m=evaluate(model);results.append({'step':step,**m});print(json.dumps(results[-1]),flush=True);model.train()
  if m['late_accuracy']>.98 and max(m['prefix'][1])>.5 and max(m['ablation_loss_change'][1])>.1:break
 n=int(torch.randint(8,17,(1,),generator=g));seq=sample(n,B,g);logits,_=model(seq[:,:-1]);loss=F.cross_entropy(logits.transpose(1,2),seq[:,1:]);opt.zero_grad(set_to_none=True);loss.backward();torch.nn.utils.clip_grad_norm_(model.parameters(),1.);opt.step()
test=evaluate(model,16,171600);extra=evaluate(model,20,172000);print('test',json.dumps(test),'length20',json.dumps(extra),flush=True)

model.eval()
n=16;B=8 if QUICK else 64;H=4;width=16;j=5;pos=n+j;g=torch.Generator().manual_seed(171601)
perm=torch.stack([torch.randperm(32,generator=g) for _ in range(B)]).to(device);base=perm[:,:n];clean=torch.cat([base,base],dim=1)[:,:-1];corrupt=clean.clone();corrupt[:,j+1]=perm[:,n];target=base[:,j+1];wrong=perm[:,n]
def metric(logits,repeats=1):
 indices=torch.arange(B*repeats,device=device);return logits[indices,pos,target.repeat(repeats)]-logits[indices,pos,wrong.repeat(repeats)]
def capture(x):
 acts={};hooks=[]
 for layer,module in enumerate(model.out):
  def keep(mod,args,i=layer):acts[i]=args[0].detach().clone()
  hooks.append(module.register_forward_pre_hook(keep))
 try:
  with torch.no_grad():logits,_=model(x);return metric(logits),acts
 finally:
  for hook in hooks:hook.remove()
mc,c=capture(clean);mr,r=capture(corrupt);rows=[]
for layer,module in enumerate(model.out):
 for p in range(clean.shape[1]):
  def patch(mod,args):
   out=args[0].clone()
   for h in range(H):out[h*B:(h+1)*B,p,h*width:(h+1)*width]=c[layer][:,p,h*width:(h+1)*width]
   return (out,)+args[1:]
  hook=module.register_forward_pre_hook(patch)
  try:
   with torch.no_grad():logits,_=model(corrupt.repeat(H,1));effects=(metric(logits,H)-mr.repeat(H)).reshape(H,B).mean(dim=1)
  finally:hook.remove()
  for h in range(H):rows.append({'layer':layer,'head':h,'position':p,'effect':float(effects[h])})
 print('capa',layer,'terminada',flush=True)
best=max(rows,key=lambda x:x['effect']);print('limpio',float(mc.mean()),'corrupto',float(mr.mean()),'parche máximo',best,'n=',len(rows))


import matplotlib.pyplot as plt
fig,axes=plt.subplots(2,1,figsize=(9,4),sharex=True)
for layer,ax in enumerate(axes):
 for head in range(H):
  row=[v for v in rows if v['layer']==layer and v['head']==head]
  ax.plot([v['position'] for v in row],[v['effect'] for v in row],label=f'cabeza {head}')
 ax.axvline(pos,color='black',linestyle='--');ax.legend(ncol=4);ax.set_ylabel(f'capa {layer}')
axes[-1].set_xlabel('Posición intervenida');plt.tight_layout();plt.show()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Measure QK-fix against exact patches

The local experiment again uses the pinned GPT-2 revision and the same pair. It captures queries, keys and probabilities, runs 144 exact interventions grouped by layer, and compares ordinary attribution, QK-fix, and QK-fix with twelve GradDrop passes. Keys stay corrupted and each patch affects only one query; the GradDrop score is compared with magnitudes. Install torch, transformers, numpy and matplotlib. The first run may download the model.

[ ]Queries: exact, attribution patching and QK-fixLocal GPU
import json,torch,numpy as np
from transformers import AutoTokenizer,AutoModelForCausalLM
torch.set_num_threads(1);rev='607a30d783dfa663caf39e06633721c8d4cfcd7e';name='openai-community/gpt2'
tok=AutoTokenizer.from_pretrained(name,revision=rev);model=AutoModelForCausalLM.from_pretrained(name,revision=rev,attn_implementation='eager').eval()
model.to('cuda' if torch.cuda.is_available() else 'cpu');device=next(model.parameters()).device
clean=tok('The capital of France is',return_tensors='pt').input_ids.to(device);corrupt=tok('The capital of Italy is',return_tensors='pt').input_ids.to(device)
paris=tok.encode(' Paris',add_special_tokens=False)[0];rome=tok.encode(' Rome',add_special_tokens=False)[0];pos=3
def metric(out):return out.logits[:,-1,paris]-out.logits[:,-1,rome]
def capture(ids,grad,drop_layer=None):
 activ={};handles=[]
 for layer,block in enumerate(model.transformer.h):
  def hook(module,args,out,i=layer):
   if grad:out.retain_grad();activ[i]=out
   else:activ[i]=out.detach()
  handles.append(block.attn.c_attn.register_forward_hook(hook))
  if grad and layer==drop_layer:
   def drop_attention(module,args,out):out[0].register_hook(lambda g:torch.zeros_like(g))
   def drop_mlp(module,args,out):out.register_hook(lambda g:torch.zeros_like(g))
   handles.append(block.attn.register_forward_hook(drop_attention));handles.append(block.mlp.register_forward_hook(drop_mlp))
 try:
  if grad:
   model.zero_grad(set_to_none=True);output=model(ids,use_cache=False,output_attentions=True)
   for a in output.attentions:a.retain_grad()
   metric(output).sum().backward();return float(metric(output)[0].detach()),activ,output.attentions
  with torch.no_grad():output=model(ids,use_cache=False);return float(metric(output)[0]),activ,None
 finally:
  for handle in handles:handle.remove()
mc,c,_=capture(clean,False);mr,r,attention=capture(corrupt,True);rows=[];heads=12;width=64;d=768
for layer,block in enumerate(model.transformer.h):
 a=r[layer];a0=c[layer];q=a[0,pos,:d].detach().reshape(heads,width);qc=a0[0,pos,:d].detach().reshape(heads,width)
 key=a[0,:pos+1,d:2*d].detach().reshape(pos+1,heads,width).permute(1,0,2)
 weights=attention[layer][0,:,pos,:pos+1].detach();g=attention[layer].grad[0,:,pos,:pos+1].detach()
 probs=torch.softmax(torch.einsum('hd,htd->ht',qc,key)/np.sqrt(width),dim=-1)
 fixed=((probs-weights)*g).sum(-1);plain=((qc-q)*a.grad[0,pos,:d].reshape(heads,width)).sum(-1)
 def patch(module,args,out):
  x=out.clone()
  for h in range(heads):x[h,pos,h*width:(h+1)*width]=a0[0,pos,h*width:(h+1)*width]
  return x
 hook=block.attn.c_attn.register_forward_hook(patch)
 try:
  with torch.no_grad(): exact=metric(model(corrupt.expand(heads,-1).contiguous(),use_cache=False))-mr
 finally:hook.remove()
 for h in range(heads):rows.append({'layer':layer,'head':h,'exact':float(exact[h]),'attribution':float(plain[h]),'qkfix':float(fixed[h])})
 print('capa',layer,'terminada',flush=True)
for keyname in ('attribution','qkfix'):
 err=np.abs(np.array([z[keyname]-z['exact'] for z in rows]));print(keyname,'MAE',float(err.mean()),'mediana',float(np.median(err)),'máximo',float(err.max()))
for row in rows:row['atp_star']=0.
for dropped in range(12):
 _,activ,drop_attention=capture(corrupt,True,dropped)
 for layer in range(12):
  a=activ[layer];a0=c[layer];qc=a0[0,pos,:d].detach().reshape(heads,width)
  key=a[0,:pos+1,d:2*d].detach().reshape(pos+1,heads,width).permute(1,0,2)
  weights=drop_attention[layer][0,:,pos,:pos+1].detach();g=drop_attention[layer].grad[0,:,pos,:pos+1].detach()
  probs=torch.softmax(torch.einsum('hd,htd->ht',qc,key)/np.sqrt(width),dim=-1)
  values=((probs-weights)*g).sum(-1)
  for h in range(heads):rows[layer*heads+h]['atp_star']+=abs(float(values[h]))/11
 print('GradDrop',dropped,'terminado',flush=True)
error=np.abs(np.array([z['atp_star']-abs(z['exact']) for z in rows]));print('AtP* magnitud MAE',float(error.mean()),'mediana',float(np.median(error)),'máximo',float(error.max()),flush=True)
result={'model':name,'revision':rev,'clean_metric':mc,'corrupt_metric':mr,'position':pos,'rows':rows}
import matplotlib.pyplot as plt
fig,axes=plt.subplots(1,3,figsize=(12,4))
for ax,keyname in zip(axes,('attribution','qkfix','atp_star')):
 x=[abs(v['exact']) if keyname=='atp_star' else v['exact'] for v in rows];y=[v[keyname] for v in rows];limit=max(map(abs,x+y))
 ax.scatter(x,y,s=12,alpha=.6);ax.plot([-limit,limit],[-limit,limit],'k--');ax.set(xlabel='Parche exacto' if keyname!='atp_star' else '|Parche exacto|',ylabel='Estimación',title=keyname)
plt.tight_layout();plt.show()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Proof
Prove: Justify the attribution patching approximation and its exactness for an affine metric.
0
Let m(a)m(\vb{a}) be differentiable at the corrupted activation and Δ=ac−ar\Delta=\vb{a}_c-\vb{a}_r.

Step 1 of 2. What is the first-order term?

Numeric
The logit difference is 4.0 clean, −1.0 corrupted and 2.5 after patching. Calculate the fraction recovered.
Code
Implement resample_ablation(model, hook_name, dataset, seed). The model protocol offers capture(example, name) and run_with_replacement(example, name, activation). For each example, select a donor from the same dataset using a NumPy generator and return the list of outputs.
def resample_ablation(model, hook_name, dataset, seed):
  pass
Shift+Enter to run
Quiz
Corrupting one path of a redundant OR gate does not change its output. What follows?
Key idea
A patch measures the effect of a specific replacement in a hybrid run. Direction, metric and reference are part of the causal question.