Frontier: transcoders, attribution graphs and the limits of interpretability
Study transcoders, cross-layer transcoders, crosscoders, and attribution graphs that approximate computations. Validate sparse feature circuits using controlled compiled transformers, model organisms, and interventions.
After this lesson you can
- Explain how transcoders provide input-independent circuits and train them on a custom model’s MLPs.
- Build and validate an attribution graph with frozen attention and normalization, error nodes, and pruning.
- Use crosscoders to compare a base model and its fine-tuned version.
- Evaluate interpretability methods against known ground truth in a compiled transformer.
- Critically read frontier interpretability research and identify assumptions and limitations.
Before you start
From representations to computation
An SAE attempts to reconstruct an activation using a sparse dictionary. A transcoder learns to predict the output of an operation, such as an MLP, from its input. Its features encode reading and writing directions that allow us to study how an operation transforms information. Dunefsky and colleagues study feature circuits with transcoders. Approximation fidelity must be measured: a small mean error does not imply that all relevant decisions are preserved.
Cross-layer transcoders can read one layer and write to several later ones. A crosscoder shares latents when reconstructing activations of multiple layers or models. When comparing a base model and a fine-tuned model, an apparently exclusive latent may reflect a real change, scale differences, or training data; controls and evaluation on held-out examples are needed. The original note presents these uses as preliminary research.
The lab below trains a transcoder on the MLP of our own transformer for synthetic BLUE/RED dialog. On four held-out topics, its FVU for MLP outputs is 0.0814 and it preserves all 16 decisions of the original model. Error-node correction matches the original logits on those examples but does not guarantee counterfactual fidelity: suppressing latent 37 with the error frozen gives a mean absolute logit change of 0.0411. That latent was selected by mean activation on the same set, so the comparison is exploratory. To compare models, a copy is fine-tuned to invert the neutral rule and a joint crosscoder is trained. Under the criterion that one writing norm exceeds twice the other, no exclusive latents appear; joint squared loss is 0.1023. This negative result does not prove the models have no differences: eight of the 16 decisions change.
A local graph and its limits
The attribution graphs of the method by Ameisen and colleagues describe a replacement model for a prompt: they replace MLPs with transcoders and freeze attention patterns and normalization denominators. Error nodes account for unreconstructed components. Error correction matches the original model’s activations and logits on that prompt, but does not guarantee that both mechanisms respond identically to interventions.
With those operations frozen, the direct contribution of a source activation to a destination’s preactivation is linear. Thresholded activations remain nonlinear; a finite change can activate or deactivate nodes and change indirect effects. The next graph is a mathematical example, not a measurement of a language model.
Pruning makes the graph easier to read but can hide accumulating small contributions, redundant paths, or error nodes. A sparse feature circuit is a hypothesis about computation for a distribution and intervention; validate predictions on the original model with controls and examples outside selection. Replacement-model attributions do not explain why attention chose a pattern if that pattern was frozen.
Our lab transformer has one layer: its attention produces an input to the MLP and the transcoder approximates its output. For a RED prompt, we freeze the final normalization denominator at its original value; centering remains linear and each latent has a direct edge to the rejection logit. The error node retains the difference between MLP and transcoder on that prompt. The five largest edges account for 49.0% of the summed magnitudes of all latent edges; the rest are grouped. The reconstructed logit matches on the prompt, but suppressing latent 16 makes the graph predict −0.642 while the full model changes by −0.125: its normalization is recomputed and the actual effect differs from the replacement. This is a measured single-layer graph for a synthetic rule, not the published two-hop case.
To compare with a two-hop case in a large language model, open the published graph for Dallas and its experimental analysis. The study groups features associated with Dallas, Texas, capital, and Austin; besides the Dallas → Texas → Austin path, it observes a direct connection from Dallas. The authors report selective inhibitions and a replacement of Texas features by California features that changes the answer to Sacramento. These are published results for Claude 3.5 Haiku, distinct from our earlier model. The same authors study poetry planning and multilingual features; each conclusion remains limited to its prompts, groupings, and interventions.
Validation when the answer is known
Interpretability validation can use models built from a known algorithm. Tracr compiles programs into transformers to study whether a method recovers known operations. It is useful as a controlled test, although a technique successful on a compiled model is not automatically validated on large-scale trained models. Model organisms and synthetic tasks isolate hypotheses; real cases additionally require checking fidelity, stability, and causal effects.
Tracr constructs weights from a RASP program: selections translate into attention and per-position operations into network components. In the official sequence reversal example, length and opposite index determine which position to read. BOS is needed to represent empty selections. On 27 three-symbol sequences over vocabulary 3, the compiled execution matched exact reversal. This check validates output on that domain, not that an SAE or patching recovers the algorithm: that claim requires applying the method and comparing its findings with the known graph and subspaces.
# Entorno aislado: tracr oficial revisión 9ce2b8c82b6ba10e62e86cf6f390e7536d4fd2cd,
# jax 0.4.35, jaxlib 0.4.35, dm-haiku 0.0.13, numpy 1.26.4.
from tracr.rasp import rasp
from tracr.compiler import compiling
import itertools
all_true=rasp.Select(rasp.tokens,rasp.tokens,rasp.Comparison.TRUE)
length=rasp.SelectorWidth(all_true)
opposite=length-rasp.indices-1
reverse=rasp.Aggregate(rasp.Select(rasp.indices,opposite,rasp.Comparison.EQ),rasp.tokens)
model=compiling.compile_rasp_to_model(reverse,vocab={1,2,3},max_seq_len=5,compiler_bos='BOS')
for tokens in itertools.product([1,2,3],repeat=3):
out=model.apply(['BOS',*tokens])
assert out.decoded==['BOS',*reversed(tokens)]
out=model.apply(['BOS',1,2,3])
print('27 secuencias correctas; ejemplo',out.decoded)
print('formas de residuales',[x.shape for x in out.residuals])npm run lab and open the connection link.In the next comparison the final symbol changes from 3 to 1 and, one attention layer at a time, the attention output at the three non-BOS positions is replaced by that of the clean example. In this run only patching the fourth attention restores the complete clean output. This is an intervention on attention outputs, not identification of every necessary edge. A small SAE is then trained on final residuals. For each symbol, the maximum absolute correlation between its indicators and latents is found on test: selecting the maximum on that same set makes the figure optimistic, and correlation is not causal proof.
import haiku as hk, numpy as np
clean=model.apply(['BOS',1,2,3]);corrupt=model.apply(['BOS',1,2,1])
print('limpio',clean.decoded,'corrupto',corrupt.decoded)
for target in range(4):
count=[0]
def patch(next_f,args,kwargs,context):
result=next_f(*args,**kwargs)
if context.module.__class__.__name__=='MultiHeadAttention' and context.method_name=='__call__':
i=count[0];count[0]+=1
if i==target:
result=result.replace(out=result.out.at[:,1:,:].set(clean.layer_outputs[2*i][:,1:,:]))
return result
with hk.intercept_methods(patch):
changed=model.apply(['BOS',1,2,1])
print('atención',target,'salida',changed.decoded)
data=[];labels=[]
for seq in itertools.product([1,2,3],repeat=3):
out=model.apply(['BOS',*seq])
data.extend(np.asarray(out.residuals[-1])[0,1:]);labels.extend(seq[::-1])
X=np.asarray(data);labels=np.asarray(labels);train=X[:54];test=X[54:];test_labels=labels[54:]
rng=np.random.default_rng(2341);d=41;m=64
E=rng.normal(0,.1,(d,m));D=rng.normal(0,.1,(d,m));D/=np.linalg.norm(D,axis=0)
be=np.zeros(m);bd=np.zeros(d)
for t in range(2000):
x=train[rng.integers(len(train),size=64)];u=(x-bd)@E+be;z=np.maximum(u,0)
[email protected]+bd;dr=2*(rec-x)/len(x);gd=dr.T@z
du=(dr@D+.02/len(x))*(u>0);ge=(x-bd).T@du;gbe=du.sum(0)
gbd=dr.sum(0)-([email protected]).sum(0)
D-=.01*gd;D/=np.maximum(np.linalg.norm(D,axis=0),1e-8)
E-=.01*ge;be-=.01*gbe;bd-=.01*gbd
z=np.maximum((test-bd)@E+be,0);[email protected]+bd
fvu=((test-rec)**2).sum()/((test-train.mean(0))**2).sum()
scores=[]
for token in [1,2,3]:
target=(test_labels==token).astype(float);corr=[]
for j in range(m):
corr.append(float(np.corrcoef(z[:,j],target)[0,1]) if np.std(z[:,j])>1e-9 else 0.)
scores.append(max(abs(np.asarray(corr))))
print('FVU',fvu,'L0',float((z>0).sum(1).mean()),'máximos |correlación|',scores)npm run lab and open the connection link.The run produced FVU 0.142, mean 27.56, and absolute maxima 0.891, 0.774, and 0.973. The FVU denominator uses the training mean; the 27 test examples are positions from nine sequences, not independent observations. High correlation with the output symbol also does not show that the latent represents the reversal operation; it may respond to the copied value.
The implementation and installation instructions are in the official Tracr repository. You can install that revision in an isolated environment with pip install "jax[cpu]==0.4.35" "numpy==1.26.4" "dm-haiku==0.0.13" "chex==0.1.87" "https://github.com/google-deepmind/tracr/archive/9ce2b8c82b6ba10e62e86cf6f390e7536d4fd2cd.zip"; the later lab also needs PyTorch. The compiled example model has 41 residual coordinates; that dimension depends on the chosen program, vocabulary, and length.
When reading a frontier case, ask which model and distribution were studied, how examples were selected, how much output remains in error nodes, which intervention was predicted before testing, and what alternatives explain the data. A readable graph alone is not evidence that all its labels are correct.
Lab: direct effect and threshold
In this explicit graph, the edge to the destination has weight 2, but the output effect depends on whether ReLU is active. The intervention recomputes the destination; the local linear prediction around the initial source may fail when crossing the threshold.
def graph(a):
pre = 2*a - 1
target = max(pre, 0)
return .5*a + target + .25
start, end = .25, 1.5
local_slope = .5 # el destino está inactivo en start
print('cambio exacto', graph(end)-graph(start))
print('aproximación local', local_slope*(end-start))
print('cambio en preactivación', 2*(end-start))Lab: approximating and comparing models
The example generates its own model without relying on an external checkpoint. The BLUE/RED rule is an artificial one-token response classification task; it does not represent safeguards in an operational model. Four topics are held out for evaluation. First the transcoder is fitted to MLP input-output pairs. Then a frozen error is added and a latent suppressed: the error corrects the initial point, not its response to intervention. Finally the rule is inverted through fine-tuning and both representations compressed jointly. Decoder-half norms are an exploratory exclusivity signal, not a causal label.
import copy, torch
torch.set_num_threads(2);torch.manual_seed(2242)
class MiniChat(torch.nn.Module):
def __init__(self):
super().__init__();self.emb=torch.nn.Embedding(25,32)
self.pos=torch.nn.Parameter(torch.randn(4,32)*.02)
self.block=torch.nn.TransformerEncoderLayer(32,4,64,dropout=0,batch_first=True)
self.head=torch.nn.Linear(32,25)
def states(self,ids):return self.block(self.emb(ids)+self.pos)
def forward(self,ids):return self.head(self.states(ids)[:,-1])
def examples(topics):
rows=[]
for topic in topics:
for color in [2,3]:rows.append(([0,topic,color,1],4 if color==2 else 5))
for value in [23,24]:rows.append(([0,topic,value,22],value))
return rows
tr=examples(range(6,18));te=examples(range(18,22))
x=torch.tensor([a for a,b in tr]);y=torch.tensor([b for a,b in tr])
xt=torch.tensor([a for a,b in te]);yt=torch.tensor([b for a,b in te])
first=MiniChat();opt=torch.optim.AdamW(first.parameters(),lr=.003)
for step in range(500):
loss=torch.nn.functional.cross_entropy(first(x),y)
opt.zero_grad();loss.backward();opt.step()
state=copy.deepcopy(first.state_dict())
torch.manual_seed(2343);base=MiniChat();base.load_state_dict(state);base.eval()
def activations(model,ids):
inputs=[];outputs=[]
h1=model.block.linear1.register_forward_pre_hook(lambda m,a:inputs.append(a[0].detach()))
h2=model.block.linear2.register_forward_hook(lambda m,a,o:outputs.append(o.detach()))
with torch.no_grad():model(ids)
h1.remove();h2.remove();return inputs[0],outputs[0]
ix,oy=activations(base,x);ixt,oyt=activations(base,xt)
class Transcoder(torch.nn.Module):
def __init__(self):
super().__init__();self.enc=torch.nn.Linear(32,64);self.dec=torch.nn.Linear(64,32)
def forward(self,z):
a=torch.relu(self.enc(z));return self.dec(a),a
def normalise(self):
with torch.no_grad():
self.dec.weight.div_(self.dec.weight.norm(dim=0,keepdim=True).clamp_min(1e-8))
trans=Transcoder();trans.normalise();opt=torch.optim.Adam(trans.parameters(),lr=.003)
for step in range(1500):
rec,z=trans(ix);loss=(rec-oy).square().mean()+.001*z.mean()
opt.zero_grad();loss.backward();opt.step();trans.normalise()
with torch.no_grad():
rec,z=trans(ixt)
fvu=float((rec-oyt).square().sum()/((oyt-oy.mean((0,1))).square().sum()))
l0=float((z>0).sum(-1).float().mean())
def replacement(model,ids,feature=None,error=False):
captured=[]
h1=model.block.linear1.register_forward_pre_hook(lambda m,a:captured.append(a[0]))
def hook(m,a,out):
rec,z=trans(captured[-1])
if feature is not None:
z=z.clone();z[:,:,feature]=0;rec=trans.dec(z)
return rec+(out-trans(captured[-1])[0]).detach() if error else rec
h2=model.block.linear2.register_forward_hook(hook)
with torch.no_grad():result=model(ids)
h1.remove();h2.remove();return result
with torch.no_grad():
original=base(xt);pred=replacement(base,xt);corrected=replacement(base,xt,error=True)
feature=int(z[:,-1].mean(0).argmax())
ablated=replacement(base,xt,feature=feature,error=True)
print('transcoder FVU',fvu,'L0',l0,'decisiones iguales',int((pred.argmax(-1)==original.argmax(-1)).sum()))
print('error corregido máximo',float((corrected-original).abs().max()),
'latente',feature,'cambio absoluto medio',float((ablated-original).abs().mean()))
# Grafo para el primer ejemplo RED: congela el denominador de LayerNorm.
with torch.no_grad():
source=ixt[1,-1];real=oyt[1,-1];approx,latent=trans(source);total=source+real
sigma=(total.var(unbiased=False)+base.block.norm2.eps).sqrt()
w=base.head.weight[5]*base.block.norm2.weight/sigma;w=w-w.mean()
edge=trans.dec.weight.T@w;contribution=edge*latent
chosen=int(contribution.abs().argmax());top=contribution.abs().topk(5).indices
other=float(original[1,5]-contribution.sum());error=float((w*(real-approx)).sum())
def remove_feature(m,a,out):
changed=out.clone();changed[:,-1]-=latent[chosen]*trans.dec.weight[:,chosen]
return changed
handle=base.block.linear2.register_forward_hook(remove_feature)
actual=float(base(xt[1:2])[0,5]-original[1,5]);handle.remove()
print('logit',float(original[1,5]),'suma latentes',float(contribution.sum()),
'otras vías',other-error,'nodo error',error)
print('aristas',top.tolist(),'contribuciones',contribution[top].tolist(),
'fracción absoluta',float(contribution[top].abs().sum()/contribution.abs().sum()))
print('suprimir',chosen,'predicción congelada',-float(contribution[chosen]),'efecto real',actual)
tuned=copy.deepcopy(base);tuned.train();opt=torch.optim.Adam(tuned.parameters(),lr=.001)
new_y=y.clone();new_y[y==4]=5;new_y[y==5]=4
for step in range(200):
loss=torch.nn.functional.cross_entropy(tuned(x),new_y)
opt.zero_grad();loss.backward();opt.step()
tuned.eval();ix2,_=activations(tuned,x);it2,_=activations(tuned,xt)
cross_train=torch.cat([ix,ix2],dim=-1).reshape(-1,64)
cross_test=torch.cat([ixt,it2],dim=-1).reshape(-1,64)
cross=torch.nn.Sequential(torch.nn.Linear(64,64),torch.nn.ReLU(),torch.nn.Linear(64,64))
opt=torch.optim.Adam(cross.parameters(),lr=.003)
with torch.no_grad():cross[2].weight.div_(cross[2].weight.norm(dim=0,keepdim=True).clamp_min(1e-8))
for step in range(1500):
zc=cross[1](cross[0](cross_train));rec=cross[2](zc)
loss=(rec-cross_train).square().mean()+.001*zc.mean()
opt.zero_grad();loss.backward();opt.step()
with torch.no_grad():cross[2].weight.div_(cross[2].weight.norm(dim=0,keepdim=True).clamp_min(1e-8))
with torch.no_grad():
zc=cross[1](cross[0](cross_test));rec=cross[2](zc);W=cross[2].weight
nb=W[:32].norm(dim=0);nt=W[32:].norm(dim=0)
print('crosscoder MSE',float((rec-cross_test).square().mean()),
'exclusivos base/ajustado',int((nb>2*nt).sum()),int((nt>2*nb).sum()),
'decisiones cambiadas',int((tuned(xt).argmax(-1)!=base(xt).argmax(-1)).sum()))npm run lab and open the connection link.Exercises
Step 1 of 2. What is the direct contribution to the preactivation?
def edge_weights(decoders, J, encoders):
pass