Circuit discovery: IOI, ACDC and causal scrubbing
Turn patching experiments into testable circuit explanations. Study fidelity, completeness and minimality, the GPT-2 small IOI circuit and self-repair, automated discovery and edge attribution, causal scrubbing and distributed alignment search.
After this lesson you can
- Define a circuit and measure fidelity, completeness and minimality.
- Reproduce IOI circuit head classes using path patching.
- Implement ACDC and edge attribution and compare resulting circuits.
- Test a circuit hypothesis with causal scrubbing.
- Learn a subspace aligned with a causal variable using DAS and validate it through interchange interventions.
Before you start
From an effect to an explanation
Patching an activation can alter an answer without identifying the operations producing the behavior. A circuit is a proposed computation subgraph: nodes, connections, replacement operation and input distribution. The question is whether that hypothesis preserves relevant behavior and what it loses when parts are removed or added. There is no guarantee of a unique minimal decomposition.
Evaluation criteria answer different questions. Fidelity asks how much full behavior a circuit preserves under an ablation reference; completeness asks whether the complement contains relevant paths the circuit omitted; minimality asks whether parts can be removed without losing behavior. One possible normalization is
where is the full model, the circuit and the ablated reference. It makes sense only if is nonzero and metric orientation is defined. It is not necessarily a probability: it can be negative or exceed one. Fidelity alone does not always detect an omitted redundant path.
IOI and compensating components
In indirect object identification (IOI), a prompt such as “When Ana and Luis arrived, Ana gave a book to” asks for Luis as completion. Wang and colleagues studied GPT-2 small with name pairs and templates, using interventions to propose head classes. Name movers carry name information to the output position; subject-inhibition heads help distinguish the repeated name; others detect duplicates and previous tokens. Negative and backup movers alter the readout. These roles depend on protocol and are not universal labels for every input.
Self-repair means other parts can compensate for an intervention. An individual head can seem unnecessary if another takes its place; ablating a group or freezing receiver paths asks a different question. The hydra effect studies compensatory responses after ablation. Compare individual and joint effects, control the reference and avoid inferring no participation from a small effect.
The following measurement uses GPT-2 small at pinned revision 607a30d783dfa663caf39e06633721c8d4cfcd7e and four name pairs in one English template. Classes and heads are hypotheses taken from the IOI study, not classes rediscovered from scratch. Clean input repeats the first name; corrupted input repeats the second. The metric always subtracts the first name’s logit from the second: 2.227 clean and −3.647 corrupted. Ablation zeros the entire head write; patching copies the clean write into the corrupted run. These are different interventions, and one template cannot validate all classes.
In this sample, jointly removing the proposed movers gives 3.615, above the clean 2.227. Removing backups alone lowers the metric from 2.227 to 2.144; removing them after movers lowers it from 3.615 to 2.943. The conditional effect changes from −0.084 to −0.672, an interaction compatible with compensation, though it does not itself identify the mechanism. The experiment also isolates two paths by freezing other head and MLP outputs at corrupted values and then transferring only the receiver output. For path 7.3 to 9.6 metric change is −0.050; for 8.6 to 9.9 it is 0.503. These are effects for that protocol and four pairs, not exhaustive reproduction of the study.
Discovering and pruning
Automated circuit discovery makes a search over edges explicit. ACDC traverses the graph from output and evaluates whether replacing a connection changes the metric enough; it prunes if the threshold is not exceeded. Each decision depends on previous decisions, order and reference. The example below calculates exact mean Bernoulli KL on four inputs of a small logistic model: it illustrates greedy search, not ACDC reproduction in GPT-2.
Edge attribution uses gradients to estimate many replacements with fewer exact evaluations. Syed and colleagues compare this family with ACDC; integrated gradients average sensitivity along a path but also depend on path and baseline. A threshold selected after seeing results can overfit: separate selection and evaluation and publish the size-fidelity curve, not only an attractive circuit.
Measured pruning traverses seven head groups in reverse order and accepts removal only if accumulated KL does not exceed the threshold. At 0.01 it retains six groups and obtains KL 0.00460; at 1 it retains three, KL 0.663 and logit difference −0.541. This is a coarse version of the ACDC idea, not a search over the paper’s 32,000 edges. Completeness requires intervening on the complement and comparing with the full model; it does not simply follow from the fidelity curve. The figure’s product of corrupted gradient and activation change approximates each patch; the final cell also estimates specific edges into Q, K and V.
For this figure, removes all seven groups, keeps only the chosen group among them and removes that group. and are shown with the same normalization. Negative values or values above one are possible: the remaining model, interactions and metric can make ablation improve logit difference. They are not probabilities or a universal measure of completeness.
Testing a causal hypothesis
Causal scrubbing turns a hypothesis into rules about which activations can be resampled without changing information the hypothesis considers relevant. It compares behavior after replacements with the original over an input distribution. Chan and colleagues explain the recursive procedure and its limits: without compatible alternative donors the test is uninformative; passing also does not prove the hypothesis is unique.
Causal abstraction relates variables of an interpretable model to network states through interchange interventions. DAS seeks a distributed alignment, for example an orthogonal rotation assigning a subspace to a variable, and optimizes correspondence under interchanges. Geiger and colleagues study that search. High accuracy on pairs used to fit the rotation is insufficient: hold out combinations and donors for evaluation and compare rival hypotheses.
Laboratory: reproducible toy pruning
Inputs here are the four equiprobable Boolean pairs. We traverse four scalar connections in reverse order and calculate KL of the full model relative to the candidate; the rule is explicit and is not confused with a complete ACDC implementation.
import numpy as np
from itertools import product
X = np.array(list(product([0., 1.], repeat=2)))
features = X[:, [0, 1, 0, 1]]
w = np.array([2., 1., .5, .15])
def predict(keep):
z = -1 + features @ (w * keep)
return 1 / (1 + np.exp(-z))
full = predict(np.ones(4))
def kl(keep):
q = predict(keep)
return np.mean(full*np.log(full/q) + (1-full)*np.log((1-full)/(1-q)))
def prune(tau):
keep = np.ones(4)
for i in reversed(range(4)):
candidate = keep.copy(); candidate[i] = 0
if kl(candidate) <= tau:
keep = candidate
return keep
for tau in (0., .001, .01, .1):
keep = prune(tau)
print('umbral', tau, 'vías', keep.astype(int), 'KL', round(kl(keep), 6))Scrubbing and alignment in a trained network
We build a toy network mixing two variables through a rotation and train a linear readout to recover them. Output multiplies both. An additional irrelevant variable permits different donors preserving both causal variables. Under the hypothesis that preserving the first suffices, changing the second alters output: resampling squared error is 0.5, while the hypothesis preserving both gives zero. This does not prove the proposed circuit is unique.
Alignment search optimizes an orthogonal angle by gradient descent, using finite differences of interchange loss. Evaluation pairs are generated independently of fitting pairs. We interchange one donor coordinate and compare with the product of the donor’s first variable and receiver’s second. Search recovers approximately 0.63 radians and reduces test error from 0.148 to nearly zero. This two-dimensional DAS is an educational instance: it does not reproduce the scale or all options of the published implementation.
import numpy as np
rng=np.random.default_rng(18)
theta=.63
R=np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]])
X=rng.uniform(-1,1,(512,2));H=X@R.T
# Una capa lineal se entrena para recuperar las dos variables mezcladas.
W=rng.normal(0,.2,(2,2))
for _ in range(600):
err=H@W-X
W-=.2*(H.T@err)/len(H)
print('MSE reconstrucción',np.mean((H@W-X)**2))
def rot(t):return np.array([[np.cos(t),-np.sin(t)],[np.sin(t),np.cos(t)]])
def swap(angle,recipient,donor):
Q=rot(angle);hr=recipient@R.T;hd=donor@R.T
cr=hr@Q;cd=hd@Q;cr[:,0]=cd[:,0]
decoded=(cr@Q.T)@W
return decoded[:,0]*decoded[:,1]
tr=rng.uniform(-1,1,(2,256,2));te=rng.uniform(-1,1,(2,256,2))
def loss(angle,pairs):
a,b=pairs;target=b[:,0]*a[:,1]
return np.mean((swap(angle,a,b)-target)**2)
angle=0.
for _ in range(350):
eps=1e-4;grad=(loss(angle+eps,tr)-loss(angle-eps,tr))/(2*eps)
angle-=.15*grad
print('ángulo',angle,'entreno',loss(angle,tr),'test',loss(angle,te),'base 0',loss(0,te))
# Remuestreo exacto en una red entrenada sobre bits: hipótesis que conserva
# ambas variables frente a una que conserva solo la primera.
bits=np.array([[0.,0.,0.],[0.,1.,1.],[1.,0.,1.],[1.,1.,0.]])
def output(x):
z=(x[:,:2]@R.T)@W
return z[:,0]*z[:,1]
base=output(bits);donor_both=bits.copy();donor_both[:,2]=1-donor_both[:,2]
donor_first=donor_both.copy();donor_first[:,1]=1-donor_first[:,1]
print('scrub ambas MSE',np.mean((output(donor_both)-base)**2),'solo primera MSE',np.mean((output(donor_first)-base)**2))Geometric interchange as a control
This second experiment uses a hand-built algebraic network, not a trained one: it encodes two bits with a fixed rotation and reads their product. Grid search approximates the alignment allowing the first bit to be interchanged. We fit the angle on eight pairs and measure on the other eight; the same four states appear in both sets, so the split tests only new pairs within the toy. A wrong rotation provides comparison. This search illustrates interchange interventions, not the full DAS procedure or an IOI circuit.
import numpy as np
from itertools import product
X=np.array(list(product([0.,1.],repeat=2)))
def rot(t):return np.array([[np.cos(t),-np.sin(t)],[np.sin(t),np.cos(t)]])
truth=.37
R=rot(truth)
def score(theta, pairs):
Q=rot(theta);err=[]
for i,j in pairs:
recipient=R@X[i]; donor=R@X[j]
coords=Q.T@recipient; coords[0]=(Q.T@donor)[0]
decoded=R.T@(Q@coords)
actual=decoded[0]*decoded[1]; target=X[j,0]*X[i,1]
err.append((actual-target)**2)
return float(np.mean(err))
train=[(i,j) for i in range(4) for j in range(4) if (i+j)%2==0]
test=[(i,j) for i in range(4) for j in range(4) if (i+j)%2!=0]
grid=np.linspace(-np.pi,np.pi,721)
best=min(grid,key=lambda t:score(t,train))
print('angle',best,'train',score(best,train),'test',score(best,test),'wrong 0',score(0,test),'wrong pi/2',score(np.pi/2,test))
Pruning our own induction circuit
The natural test of m30-l16 showed no induction. Here we use another model trained expressly on repeated synthetic lists as in m30-l17, without attributing the natural result to it. After training, pruning traverses its eight heads in reverse order and accepts ablation if second-half loss increases no more than the threshold relative to the full model. The saved run stopped at step 1500 and achieved loss 0.1242 on 128 new sequences: with threshold 0.1 it retained six heads and obtained 0.1544. Pruning proves neither global minimality nor identifies all composition edges by itself. The quick check tests only the pipeline.
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)]
scores=q@k.transpose(-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:
selected=[ablate] if isinstance(ablate,tuple) else ablate
gate=torch.ones(H,device=x.device)
for layer,head in selected:
if layer==l:gate[head]=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()
x=sample(16,128,torch.Generator().manual_seed(1816));inp=x[:,:-1];truth=x[:,1:]
def metric(removed):
with torch.no_grad():
z,_=model(inp,ablate=removed)
return float(F.cross_entropy(z[:,15:].reshape(-1,V),truth[:,15:].reshape(-1)))
baseline=metric([])
all_heads=[(l,h) for l in range(2) for h in range(H)]
rows=[]
for tau in [.001,.01,.1,.5]:
removed=[]
for head in reversed(all_heads):
trial=removed+[head]
if metric(trial)-baseline<=tau:removed=trial
rows.append({'tau':tau,'removed':removed,'remaining':8-len(removed),'loss':metric(removed),'delta':metric(removed)-baseline})
print('pérdida original',baseline,'poda',rows)npm run lab and open the connection link.Local laboratory: IOI in GPT-2 small
This cell downloads the pinned GPT-2 revision and runs individual and group ablations, patches, their gradient approximation, two isolated paths and greedy KL pruning. It saves the report in oryon-ioi.json. The path implementation freezes corrupted head and MLP outputs except source and receiver; the second pass transfers only the receiver. It evaluates all positions and does not claim to isolate every possible path. ORYON_QUICK=1 limits groups and thresholds to check the pipeline without reproducing the figure’s full report.
import json, os, torch
QUICK=os.environ.get('ORYON_QUICK')=='1'
from pathlib import Path
from transformers import AutoModelForCausalLM,AutoTokenizer
torch.set_num_threads(2)
revision='607a30d783dfa663caf39e06633721c8d4cfcd7e'
name='openai-community/gpt2'
tok=AutoTokenizer.from_pretrained(name,revision=revision)
model=AutoModelForCausalLM.from_pretrained(name,revision=revision,attn_implementation='eager').eval()
device='cuda' if torch.cuda.is_available() else 'cpu';model.to(device)
pairs=[('Mary','John'),('Alice','Bob'),('Sarah','David'),('Emma','James')]
clean=[];corrupt=[];io=[];subject=[]
for a,b in pairs:
c=f'When {a} and {b} went to the store, {a} gave a book to'
r=f'When {a} and {b} went to the store, {b} gave a book to'
ids=tok.encode(c);other=tok.encode(r);aa=tok.encode(' '+a);bb=tok.encode(' '+b)
assert len(ids)==len(other) and len(aa)==len(bb)==1
clean.append(ids);corrupt.append(other);io.append(bb[0]);subject.append(aa[0])
assert len({len(x) for x in clean})==1
clean=torch.tensor(clean,device=device);corrupt=torch.tensor(corrupt,device=device)
io=torch.tensor(io,device=device);subject=torch.tensor(subject,device=device)
def metric(out):
z=out.logits[:,-1];i=torch.arange(z.shape[0],device=device);return z[i,io]-z[i,subject]
def capture(ids):
activations={};handles=[]
for layer,block in enumerate(model.transformer.h):
def hook(module,args,i=layer):activations[i]=args[0].detach().clone()
handles.append(block.attn.c_proj.register_forward_pre_hook(hook))
try:
with torch.no_grad():value=metric(model(ids,use_cache=False)).mean().item()
finally:
for h in handles:h.remove()
return value,activations
clean_value,c=capture(clean);corrupt_value,r=capture(corrupt)
groups={'movedoras':[(9,6),(9,9),(10,0)],'negativas':[(10,7),(11,10)],'respaldo':[(10,10),(10,6),(10,2),(11,2),(9,7),(9,0),(11,9),(10,1)],'inhibición':[(7,3),(7,9),(8,6),(8,10)],'duplicado':[(0,1),(0,10),(3,0)],'previo':[(2,2),(4,11)],'inducción':[(5,5),(5,8),(5,9),(6,9)]}
if QUICK:
groups={k:groups[k] for k in ('movedoras','respaldo','inhibición')}
def run(interventions,mode):
hs=[]
for layer in sorted({x[0] for x in interventions}):
heads=[h for l,h in interventions if l==layer]
def hook(module,args,layer=layer,heads=heads):
x=args[0].clone()
for h in heads:
sl=slice(h*64,(h+1)*64)
x[:,:,sl]=0 if mode=='zero' else c[layer][:,:,sl]
return (x,)+args[1:]
hs.append(model.transformer.h[layer].attn.c_proj.register_forward_pre_hook(hook))
try:
with torch.no_grad():return metric(model(clean if mode=='zero' else corrupt,use_cache=False)).mean().item()
finally:
for h in hs:h.remove()
rows=[]
for group,hs in groups.items():
for h in hs:
rows.append({'group':group,'heads':[h],'zero':run([h],'zero'),'patch':run([h],'patch')})
rows.append({'group':group,'heads':hs,'zero':run(hs,'zero'),'patch':run(hs,'patch')})
print(group,rows[-1],flush=True)
rows.append({'group':'movedoras+respaldo','heads':groups['movedoras']+groups['respaldo'],'zero':run(groups['movedoras']+groups['respaldo'],'zero'),'patch':run(groups['movedoras']+groups['respaldo'],'patch')})
# Aproximación lineal de los mismos parches, con gradientes en entrada corrupta.
acts={};handles=[]
for layer,block in enumerate(model.transformer.h):
def remember(module,args,i=layer):
x=args[0];x.retain_grad();acts[i]=x
handles.append(block.attn.c_proj.register_forward_pre_hook(remember))
model.zero_grad(set_to_none=True);metric(model(corrupt,use_cache=False)).mean().backward()
for row in rows:
row['attribution']=sum(float(((c[l][:,:,h*64:(h+1)*64]-r[l][:,:,h*64:(h+1)*64])*acts[l].grad[:,:,h*64:(h+1)*64]).sum()) for l,h in row['heads'])
for handle in handles:handle.remove()
# Parchar una ruta fuente->receptor: se congelan salidas de otras cabezas y
# MLP en sus valores corruptos; después solo se transfiere la salida receptora.
mlps={};handles=[]
for l,block in enumerate(model.transformer.h):
def save_mlp(mod,args,out,i=l):mlps[i]=out.detach().clone()
handles.append(block.mlp.register_forward_hook(save_mlp))
with torch.no_grad():model(corrupt,use_cache=False)
for h in handles:h.remove()
def path(source,receiver):
sl,sh=source;tl,th=receiver;found=[];hooks=[]
for l,block in enumerate(model.transformer.h):
def freeze_heads(mod,args,i=l):
x=r[i].clone()
if i==sl:x[:,:,sh*64:(sh+1)*64]=c[i][:,:,sh*64:(sh+1)*64]
if i==tl:
x[:,:,th*64:(th+1)*64]=args[0][:,:,th*64:(th+1)*64]
found.append(x[:,:,th*64:(th+1)*64].detach().clone())
return (x,)+args[1:]
def freeze_mlp(mod,args,out,i=l):return mlps[i]
hooks.extend([block.attn.c_proj.register_forward_pre_hook(freeze_heads),block.mlp.register_forward_hook(freeze_mlp)])
try:
with torch.no_grad():model(corrupt,use_cache=False)
finally:
for h in hooks:h.remove()
def restore_receiver(mod,args):
x=args[0].clone();x[:,:,th*64:(th+1)*64]=found[0];return (x,)+args[1:]
h=model.transformer.h[tl].attn.c_proj.register_forward_pre_hook(restore_receiver)
try:
with torch.no_grad():return float(metric(model(corrupt,use_cache=False)).mean())-corrupt_value
finally:h.remove()
paths=[{'source':[7,3],'receiver':[9,6],'effect':path((7,3),(9,6))},
{'source':[8,6],'receiver':[9,9],'effect':path((8,6),(9,9))}]
print('rutas',paths,flush=True)
# Poda voraz sobre siete grupos de salidas de cabeza, no sobre todas las aristas.
with torch.no_grad(): full=model(clean,use_cache=False).logits[:,-1].softmax(-1)
def kl(remove):
hs=[]
for layer in sorted({l for l,h in remove}):
heads=[h for l,h in remove if l==layer]
def hook(module,args,heads=heads):
x=args[0].clone()
for h in heads:x[:,:,h*64:(h+1)*64]=0
return (x,)+args[1:]
hs.append(model.transformer.h[layer].attn.c_proj.register_forward_pre_hook(hook))
try:
with torch.no_grad():
logq=model(clean,use_cache=False).logits[:,-1].log_softmax(-1)
return float((full*(full.log()-logq)).sum(-1).mean())
finally:
for h in hs:h.remove()
pruning=[]
for tau in ([0.01] if QUICK else [0.001,0.01,0.1,1.0]):
removed=[];names=[]
for key in reversed(list(groups)):
candidate=removed+groups[key]
if kl(candidate)<=tau:removed=candidate;names.append(key)
pruning.append({'tau':tau,'removed':names,'remaining_groups':len(groups)-len(names),'kl':kl(removed),'metric':run(removed,'zero') if removed else clean_value})
print('poda',pruning[-1],flush=True)
result={'revision':revision,'pairs':pairs,'clean':clean_value,'corrupt':corrupt_value,'rows':rows,'pruning':pruning,'paths':paths}
Path('oryon-ioi.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8')
print('clean',clean_value,'corrupt',corrupt_value,flush=True)
# Compara cada grupo con su complemento bajo la misma referencia.
all_heads=[h for group in groups.values() for h in group]
baseline=run(all_heads,'zero')
for name,hs in groups.items():
outside=[h for h in all_heads if h not in hs]
only=run(outside,'zero');without=run(hs,'zero')
fidelity=(only-baseline)/(clean_value-baseline)
completeness=1-(without-baseline)/(clean_value-baseline)
print('grupo',name,'fidelidad',fidelity,'completitud',completeness)npm run lab and open the connection link.Q, K and V edge attribution
For each tested path, the sender-write difference between clean and corrupted is propagated linearly through receiver normalization and QKV projections, evaluated at the corrupted residual. It is multiplied by the metric gradient with respect to each of those three inputs. This estimates specific direct edges, not every path or integrated attribution. Layer and head indices start at zero. The Q estimate is −0.0459 for 7.3 to 9.6 and 0.3035 for 8.6 to 9.9; exact paths measured earlier are not restricted to Q and need not match the approximation.
resid={};qkv={};hooks=[]
for layer,block in enumerate(model.transformer.h):
def pre(module,args,i=layer):resid[i]=args[0].detach().clone()
def post(module,args,out,i=layer):out.retain_grad();qkv[i]=out
hooks.extend([block.ln_1.register_forward_pre_hook(pre),block.attn.c_attn.register_forward_hook(post)])
model.zero_grad(set_to_none=True);metric(model(corrupt,use_cache=False)).mean().backward()
for h in hooks:h.remove()
edges=[]
for (sl,sh),(tl,th) in [((7,3),(9,6)),((8,6),(9,9))]:
s=slice(sh*64,(sh+1)*64);delta=(c[sl][:,:,s]-r[sl][:,:,s])@model.transformer.h[sl].attn.c_proj.weight[s,:]
block=model.transformer.h[tl];f=lambda x:block.attn.c_attn(block.ln_1(x))
_,jvp=torch.autograd.functional.jvp(f,resid[tl],delta)
estimates={}
for j,key in enumerate(('Q','K','V')):
t=slice(j*768+th*64,j*768+(th+1)*64)
estimates[key]=float((jvp[:,:,t]*qkv[tl].grad[:,:,t]).sum())
edges.append({'source':[sl,sh],'receiver':[tl,th],'attribution':estimates})
print(json.dumps(edges,ensure_ascii=False),flush=True)npm run lab and open the connection link.Exercises
Step 1 of 2. What happens to each example’s loss?
def prune(edges, metric, tau):
pass