Faithfulness, illusions and research report
Write a short research report on a reference case in GPT-2 small and a result from the causal modular-addition transformer trained in Lesson 3. Apply explicit faithfulness, completeness and minimality criteria, reproduce known interpretability illusions, and document the limits across architectures, tasks and generalization.
After this lesson you can
- Use interventions to measure the faithfulness, completeness and minimality of the proposed explanation.
- Reproduce a known interpretability illusion and explain its cause.
- Compare the explanation with alternatives and use experiments to rule out competing hypotheses.
- Write a research report with figures, reproducible methods and limitations.
Before you start
A story is not yet a mechanism
A head attending to a name and a direction that appears to encode a property suggest hypotheses. A mechanistic explanation also needs to specify components, the information they transmit, inputs where the behavior is expected, and interventions that could refute it. The observation–intervention distinction explored with activation patching and steering underpins an honest report.
The protocol must separate discovery and evaluation. If you choose heads because they maximize an effect on four sentences and then evaluate on those same sentences, the result measures fit to that sample. Hold out other templates and names before selecting the circuit, publish the selection rule and compare the unnormalized metric. Repeat with seeds and reasonable corruption; report negative results and cases where the sign changes.
Three questions for a circuit
Causal faithfulness criteria must be defined by the specific intervention, not only their names. Wang and colleagues use faithfulness, completeness and minimality to examine their IOI explanation; even with favorable evidence they identify gaps.
These criteria make interpretability validation concrete: an explanation is not evaluated solely by its verbal coherence. Relate each test to the behavior it aims to explain and the distribution on which it was measured; the same number can mean different things if corruption or ablation reference changes.
- Faithfulness: Does the model limited to the circuit reproduce full-model behavior under the chosen ablation and distribution? Compare values per example, not just a mean that could hide opposing errors.
- Completeness: Are components missing that can change behavior in interaction with the selected ones? Ablating one piece individually may miss redundant paths; study sets and present the search procedure.
- Minimality: Does each included piece contribute meaningfully in the circuit’s context? Test individual and group removals when redundancy exists. A piece that appears unnecessary in the full model may matter after another is removed.
There is no single universal number for these concepts. Specify what is replaced, what “circuit only” means, how the ablation reference is built and which metric is compared. Mean ablation reduces some anomalies relative to zeroing, but the mean can create an artificial activation and hide conditional information. Compare paired controls, group means and different contexts. A recovered fraction of 95% in patching does not prove completeness if the reverse effect or analysis of the remainder tells another story: each intervention answers a different question.
Consider two different measurements. In one, replace candidate component activations on a corrupt input with those from the clean input: you ask whether that substitution suffices to recover the margin in that context. In another, start with the clean input and replace candidates with a reference: you ask how much behavior changes when they are removed under that reference. Neither operation is the algebraic inverse of the other. If paths are redundant, removing one can cause little change even though introducing it into a corrupt background is effective; if they interact, the joint effect can exceed or fall below the individual sum.
To compare an isolated circuit with the full model, also use an explicit reference. In the test below call the unintervened margin, the margin when all heads are replaced and the margin when only candidates remain. Fraction expresses the position of on that scale. It can be negative or exceed one; it is not a probability. If the denominator is close to zero, the fraction is unstable and original margins should be reported rather than interpreting it.
This normalization does not solve the reference problem: a per-position mean may ignore whether a name is subject or object and produce a combination of activations the model never saw. A conditional mean by syntactic role answers a different question and requires enough examples to estimate. Replacement by matched-example activations preserves natural values of individual components but can also combine incompatible states. A robust explanation therefore compares several interventions and declares which dependencies each preserves, rather than treating one ablation as ground truth.
To examine minimality, denote by the metric after replacing set within the circuit. The drop when removing two components jointly is . Compare it with separate drops: their difference measures interaction for that intervention, not a unique credit assignment. For example, two redundant routes can produce small individual drops and a large joint drop. The lab enumerates all fifteen pairs of the six heads, but does not explore other subsets or components outside the group; do not present this bounded search as an exhaustive proof of global minimality.
One mean can hide opposing results. Save full-model and circuit margins for each paired example and calculate differences before summarizing. If half improve and half worsen, a near-zero mean does not mean the circuit reproduces every case. The number of sentences is not automatically effective sample size either: names swapped in one template may share structure. To quantify uncertainty, define the population and resample its independent units; with one template you cannot estimate variation across templates. Eight examples can reveal specific failures, not provide a broad statistical guarantee.
An intervention that creates a pathway
Interpretability illusions show why reproducing output is insufficient to locate computation. Makelov, Lange and Nanda present a three-coordinate linear network:
The first coordinate varies with input but does not affect output. The second affects output if forced, but stays at zero in natural runs. The third carries the signal in those runs. Take , and patch along unit direction :
Patched output is 1, the same as clean. Yet the intervention has mixed a disconnected coordinate with a dormant one and created a path unused in the natural run. Patching only the first does not change output; patching only the second does not either, because its value does not differ across examples. The third does carry the natural signal. This example shows a mathematical possibility, not that all subspace interventions are illusory. In the toy model the distinction between directions depends on parameterization, as the paper explains.
import numpy as np
w1=np.array([1.,0.,1.]);w2=np.array([0.,2.,1.])
clean=w1; corrupt=np.zeros(3)
def patch(source,base,direction):
u=np.asarray(direction,dtype=float);u=u/np.linalg.norm(u)
return base+u*np.dot(u,source-base)
for name,u in [('desconectada',[1,0,0]),('durmiente',[0,1,0]),
('mezcla',[1,1,0]),('vía natural',[0,0,1])]:
h=patch(clean,corrupt,u)
print(name, 'estado',np.round(h,4), 'salida',round(float(w2@h),4))Reading the subspace alone mixes variation with ability to influence. To investigate a real model, separately verify whether the direction varies on natural examples, whether changing it affects output, what happens when intervening on complements and whether behavior persists on data not used to find it. An overly expressive probe and example selection can also create unjustified confidence: the former can calculate a property the model does not use, and the latter can hide counterexamples.
A predictive probe measures recoverable information from a representation; it does not show that the network reads that information using the same algorithm. A nonlinear probe can learn a transformation the original network never applies; even a linear probe can find a correlation another component does not use. Compare with permuted labels, a capacity-controlled probe and a template-level split, not only nearly identical sentences. Then propose an intervention that changes information used by the probe and check both predicted behavior and unrelated properties. Success still depends on the change not introducing an artificial pathway like the example above.
Displayed examples are also part of the method. Choosing only maximum activations can make a latent appear to respond to a concept while omitting contexts with similar words where it does not activate, or high activations with another meaning. Publish the selection rule and examine negative and held-out examples. A fixed set makes the story reproducible, while evaluation across sources and templates helps reveal where it stops working.
Hypotheses that can lose
Formulate two mechanisms before seeing the result: for example, “the head transmits name identity through its value” versus “the difference comes from how the receiver’s query changes.” An experiment separately patching Q, K and V, freezing and documenting other pathways, can distinguish some predictions of those hypotheses. If both predict the same result, it does not distinguish them. If the experiment measures only one pathway and omits MLPs or alternatives, it does not show that all rival mechanisms were ruled out.
Falsifiable design fixes a measure, controls and the observation that would weaken each hypothesis beforehand. After observing the result, record which tests were added exploratorily. Uncertainty intervals must reflect the sampling unit: treating each token as independent when several sentences come from one template exaggerates precision.
Strong inference organizes that comparison as a sequence of discriminating tests. In the full model counterfactuals can be run in code, but causal identification of a more general explanation still depends on the intervention set, hybrid states it produces and the distribution to which you want to extrapolate. An answer obtained on one template does not by itself identify a mechanism valid for any text.
From analysis to report
A reproducible report contains question and scope; model, weights, tokenizer and hashes; data construction and splitting; intervention and controls; results and code-generated figures; alternatives; limitations and execution details. Each figure must be recreatable from supplied data and code. Present component selection as exploratory if evaluation uses the same examples.
A useful structure separates four claims. First, what phenomenon is measured, with an input example, compared answers and unnormalized metric. Second, what the mechanism predicts, in terms of observable changes if an output is substituted or a path interrupted. Third, what happened, including controls, per-example values and tests contradicting the explanation. Fourth, where the conclusion stops: evaluation distribution, components left active, uncertainty and alternatives still compatible. A narrower conclusion supported by all the data is more useful than a general description that cannot fail.
Reproducibility also requires recording seemingly minor decisions: exact checkpoint and tokenizer revision, token positions, names used in discovery and evaluation, hook site, metric units, per-position reference and treatment of numerical errors. Code must remove every hook even if a run fails. When regenerating on another device, small numerical differences need not imply a different mechanism; tolerance should be fixed according to scale, not chosen afterward to force agreement.
When reviewing a report, reconstruct the evidence chain from each figure to a run. Does the graph show observed activations, a gradient approximation or a real replacement? Was the same sample used to select and evaluate the hypothesis? Does the identity control preserve output and was the hook removed afterward? Does the figure show a logit difference, recovered fraction or probability? These distinctions avoid attributing more to a result than it can support and enable repetition when tools change.
As a bounded test of our own, take the six heads and the 5.5 → 8.10 path selected in p11-l05. Keep published GPT-2 small and that lesson’s freezing protocol, but use eight name pairs distinct from the four used to select heads. The template is the same: this separation checks new names, not generalization to other structures. The lab reloads pinned weights and checks their SHA-256; it requires PyTorch, transformers, safetensors and huggingface_hub.
The narrow question is: can the 5.5 activation difference influence the metric through Q or V of 8.10 when other attention and MLP writes are fixed to corrupt values? Alternatives “only Q contributes” and “V also contributes” predict different outcomes for separate interventions. The path selection arose from prior exploration; the numerical threshold discussed below was formulated after observing the held-out test. Therefore this result is exploratory, not a preregistered test.
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()
assert sha256_file(weights) == '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=[('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
assert torch.all((x != y).sum(dim=1)==1), 'los pares 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()
out={'clean':c,'corrupt':b,'pairs':names}
# 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-heldout-path.json').write_text(json.dumps(out,ensure_ascii=False,indent=2),encoding='utf-8')
print('path',path,flush=True)
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-heldout-joint.json').write_text(json.dumps({'all':all_score,'without':without,'clean':c,'corrupt':b},indent=2),encoding='utf-8')npm run lab and open the connection link.For these eight pairs mean clean logit difference is 2.672 and corrupt −2.891. Patching the six heads simultaneously recovers 0.772 of the margin; omitting the 8.10 patch leaves 0.607. For the direct 5.5 → 8.10 pathway, Q intervention recovers −0.0003 and V 0.0757, under the protocol freezing other writes. In original units these are about −0.0018 and 0.421 logits. The specific prediction “only Q recovers at least 0.05 of the mean margin on these pairs” is not met; V intervention does change the metric. This does not rule out a Q contribution in other tasks or pathways, or show that the whole signal travels through V.
These are deterministic means of eight specific pairs, not an estimate of population uncertainty. The set shares template, name vocabulary and model; a result for differently structured sentences needs another sample. Separation by names avoids repeating the four selection pairs but does not eliminate retrospective threshold selection. A confirmatory continuation would fix templates, names, metric and predictions in advance and keep a final set outside all tuning.
Joint patching retains corrupt activations of other components: it is not equivalent to isolating a circuit by mean ablation. For another test, estimate the activation mean for each position and head from the four p11-l05 selection examples. On the eight held-out pairs, replace outputs of heads outside the set by those means and let the six selected heads operate. MLPs and other components remain active. The same mean is used for all eight examples, without using their answers to calculate it.
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('p11-mean-ablation.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']
from itertools import combinations
progress.setdefault('remove_pairs',{})
for a,d in combinations(sorted(chosen),2):
key=f'{a[0]}.{a[1]} + {d[0]}.{d[1]}'
if key not in progress['remove_pairs']:
progress['remove_pairs'][key]=ablate_set((all_heads-chosen)|{a,d});save()
pair_results=progress['remove_pairs']
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,
'remove_pairs':pair_results,'reference_names':reference_names,'heldout_names':names}
# La media agregada puede ocultar errores que se compensan: guarda cada par.
def margins(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():
z=forward(x)[:,-1]
return (z.gather(1,targets[:,0,None])-z.gather(1,targets[:,1,None])).flatten().cpu().tolist()
finally:
for h in handles:h.remove()
out['per_example_full']=margins(set())
out['per_example_circuit']=margins(all_heads-chosen)
assert abs(sum(out['per_example_full'])/len(names)-full)<1e-5
assert abs(sum(out['per_example_circuit'])/len(names)-circuit)<1e-5
progress.update(out);save()
print(json.dumps(out),flush=True)
# La figura del informe se genera desde las cuatro ejecuciones anteriores.
import matplotlib.pyplot as plt
labels=['Media: todas','Media: seis','Solo seis','Sin ablación']
values=[out['mean_all'],out['full_without'],out['circuit'],out['full']]
fig,ax=plt.subplots(figsize=(5,3.5),layout='constrained')
bars=ax.barh(labels,values,color=['#88919b','#d08230','#2879bd','#293e59'])
ax.invert_yaxis()
ax.set_xlabel('Diferencia de logits',fontsize=12)
ax.tick_params(labelsize=11)
ax.set_xlim(0,3.3)
ax.bar_label(bars,fmt='%.3f',padding=4,fontsize=11)
ax.spines[['top','right']].set_visible(False)
fig.savefig('p11-informe.svg',facecolor='white')npm run lab and open the connection link.The full model metric is 2.672, the reference with all heads replaced by mean is 0.334, and the six-head set with MLPs intact is 2.191. Normalizing between those references, gives 0.794. This is faithfulness for that intervention and those eight pairs, not a universal property of the circuit. When also replacing each selected head, the resulting metric is 2.592 without 5.5, 2.018 without 7.9, 2.214 without 8.6, 2.045 without 8.10, 1.369 without 9.9 and 1.328 without 10.0. In particular, logit difference even rises slightly on replacing 8.6; this metric does not show individual necessity of that head in this circuit and context.
The eight individual margins show why the mean is insufficient: for Peter and Paul the margin changes from 0.914 in the full model to 1.682 with the isolated set, while for Emma and Michael it falls from 2.915 to 0.847. These errors have opposite signs and partly cancel in the average. The fifteen removal pairs also show interactions: replacing 5.5 and 8.6 jointly gives 2.484, while summing their two individual changes would predict 2.615. This difference describes the specific test; it does not uniquely assign a causal contribution to each head.
One concrete alternative hypothesis is that the six heads alone can sustain this margin. To test it we replace those six by their mean while keeping other heads and MLPs intact: the remaining metric is 1.990, equivalent to 0.708 of the distance between the all-heads-replaced reference and the full model. This control rejects the strict version of the hypothesis on this sample under this intervention: signal remains outside the chosen set. It does not itself identify which components carry it, and the mean can produce artificial states.
The table summarizes tests. “Not demonstrated” is a result about scope, not a measured zero; the search for remaining paths is not exhaustive.
| Criterion | Evidence on eight held-out pairs | Limit |
|---|---|---|
| Set recovery | 0.772 of margin | Same template and published model; other paths remain corrupt |
| Relative necessity in set | Omitting 8.10 leaves 0.607 | Patch omission, not head ablation |
| Faithfulness under mean ablation | 0.794 relative to full model and all-heads-replaced reference | MLPs stay active; eight names and one template |
| Minimality, individual omissions | Replacing 8.6 increases metric from 2.191 to 2.214 | No evidence of individual necessity under that metric; no proof of general uselessness |
| Completeness, active complement | Replacing the six leaves 1.990, or 0.708 on the normalized scale | Remaining signal, without locating all paths or exhausting other distributions |
Our own report: modular addition
The finding in p11-l05 selected heads 1, 2 and 3 of a modulo-113 addition transformer. This one-layer, four-head model was trained in p11-l03; it is not GPT-2 from the first part or the p06 checkpoint. The question is whether those three heads preserve the addition margin when others are replaced by their mean, and whether any one suffices alone.
We hold out 64 additional pairs absent from both training and the clean or corrupt pairs used to select heads. The ablation reference averages 128 training pairs chosen with seed 1820. The full model gets 63 of 64 clean sums and 64 of 64 corrupt ones right; retain that failure in the report. Download the own-model checkpoint into the lab directory or specify its path via P11_GROK_CKPT.
"""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);discovery=set(pool[:64])
used=discovery|{(a,(b+1)%P) for a,b in discovery}
remaining=[(a,b) for a,b in pool if (a,b) not in used and (a,(b+1)%P) not in used]
random.Random(1819).shuffle(remaining);pairs=remaining[: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()
# Ablación por media de las cuatro cabezas; MLP intacta.
reference=sorted(training);random.Random(1820).shuffle(reference);reference=reference[:128]
reference_x=torch.tensor([[a,b,P] for a,b in reference])
_,reference_z,_=capture(reference_x)
head_mean=reference_z.mean(0,keepdim=True)
chosen={1,2,3};all_heads=set(range(H))
def ablate_set(heads):
def substitute(mod,args):
z=args[0].clone()
for h in heads:z[:,h*32:(h+1)*32]=head_mean[:,h*32:(h+1)*32]
return (z,)+args[1:]
hook=model.o.register_forward_pre_hook(substitute)
try:
with torch.no_grad():return float(metric(model(x)))
finally:hook.remove()
full=ablate_set(set());mean_all=ablate_set(all_heads)
circuit=ablate_set(all_heads-chosen);complement=ablate_set(chosen)
singles={str(h):ablate_set((all_heads-chosen)|{h}) for h in sorted(chosen)}
doubles={'+'.join(map(str,g)):ablate_set((all_heads-chosen)|set(g)) for g in itertools.combinations(sorted(chosen),2)}
assert abs(full-clean)<1e-6 and abs(full-mean_all)>1e-5
out={'clean':full,'mean_all':mean_all,'circuit':circuit,'complement':complement,
'fidelity':(circuit-mean_all)/(full-mean_all),'singles':singles,'doubles':doubles,
'relative_complement':(complement-mean_all)/(full-mean_all),
'clean_accuracy':clean_accuracy,'corrupt_accuracy':corrupt_accuracy,'checkpoint_sha256':sha,
'reference':'128 parejas de train, semilla 1820','reference_pairs':reference,
'heldout_pairs':pairs}
Path('p11-grok-report.json').write_text(json.dumps(out,indent=2),encoding='utf8')
print(json.dumps({k:v for k,v in out.items() if k not in ('reference_pairs','heldout_pairs')},indent=2))
# Figura regenerada con el mismo resultado, sin valores escritos a mano.
import matplotlib.pyplot as plt
labels=['Media: todas','Solo cabeza 0','Cabezas 1+2+3','Sin ablación']
values=[out['mean_all'],out['complement'],out['circuit'],out['clean']]
fig,ax=plt.subplots(figsize=(5,3.5),layout='constrained')
bars=ax.barh(labels,values,color=['#88919b','#d08230','#2879bd','#293e59'])
ax.invert_yaxis()
ax.set_xlabel('Diferencia de logits',fontsize=12)
ax.tick_params(labelsize=11)
ax.set_xlim(-20,175)
for bar,value in zip(bars,values):
ax.text(max(value,0)+3,bar.get_y()+bar.get_height()/2,f'{value:.2f}',va='center',fontsize=11)
ax.spines[['top','right']].set_visible(False)
fig.savefig('p11-grok-report.svg',facecolor='white')npm run lab and open the connection link.| Test in our model | Result | Bounded interpretation |
|---|---|---|
| Faithfulness of 1+2+3 | The set preserves three quarters of the distance between reference and full model, with MLP active | |
| Completeness, complement | Replacing 1+2+3 leaves 18.279, or 0.132 on the same scale | Head 0 and active paths retain signal; other interventions have not been exhausted |
| Individual minimality | Replacing 1, 2 or 3 within the set leaves 84.807, 47.695 or 48.822 | Each removal reduces this margin; result depends on mean and distribution |
| Alternative: head 3 alone | Retaining it alone leaves 28.540 versus 139.918 without ablation | The prediction that it reproduces full margin is rejected in this test |
The difference does not identify a complete addition algorithm or guarantee the heads are needed for every input. Both samples share task, vocabulary and architecture, and their pairs may share operands; they are not a population of different templates. Selection criterion and mean are specific interventions, not a universal circuit definition. A stronger replication would vary the reference, study per-pair errors and intervene on MLP mechanisms. The figure above, table and pairs used are saved from the same run.
Exercises
def compare_circuit(run, examples, keep):
pass