Logit lens, tuned lens and controlled probes
Read the residual stream layer by layer, using your own GPT or the public fallback model specified by the project. The documented run uses GPT-2 small and applies first a logit lens, then a tuned lens trained per layer, to see how the prediction forms. Train linear probes with control tasks that separate what the model represents from what the probe learns on its own.
After this lesson you can
- Apply the logit lens and measure its KL divergence from the final output at each layer.
- Train a tuned lens and compare its KL divergence with that of the logit lens.
- Train linear probes for multiple properties with control tasks and measure selectivity.
- Use an intervention to check whether the model uses the direction found by the probe.
Before you start
Read before the final layer
A final prediction emerges after a succession of writes to the residual stream. Could the answer already be read halfway through? The question requires a decoder: intermediate states are not themselves distributions over tokens. The result depends on that decoder and does not necessarily describe the distribution the model would use if it stopped there.
The logit lens and tuned lens are two ways to read a residual . The first applies the frozen model’s final normalization and output matrix:
Normalization matters: omitting it changes magnitudes and probabilities. Furthermore, the final normalization was trained for the final residual, not necessarily for the distribution of states in the early layers. The tuned lens learns a layer-specific affine transformation before applying the same readout, . Belrose and colleagues studied this family of translators to make the readout more reliable. The model is frozen, the translators are optimized and evaluated on separate texts: fitting and evaluating on the same tokens can make a small KL divergence reflect overfitting.
In a pre-normalized GPT, the residual leaving a block adds the input to its attention and MLP writes. The next layer can change both its direction and scale before the final readout. The direct lens assumes the same coordinate system and normalization are appropriate at every stage; the learned transformation corrects part of this misalignment, but it is an instrument trained on data, not an operation the model carries out in its ordinary forward pass. Initializing it to the identity provides an interpretable starting point and allows comparison with the direct readout.
Dimensions prevent a silent transposition. If the residual is a column in , the output matrix has one row per token, ; logits live in . In code, many residuals are stored as rows with shape (batch, position, d), and a linear layer applies the transpose of its weights. The lens affine matrix is , with a bias of length . Do not confuse that bias with a vocabulary bias of length ; GPT-2’s unembedding has no bias.
Let be the model’s final distribution for the same position and a layer’s readout. We measure
The direction of KL matters. This choice penalizes the lens for assigning low probability to options the final output considers likely. A tuned lens is trained to approximate that distribution, not the actual next label: lower KL indicates fidelity to the final model, not a more accurate prediction of the truth. Applying the same normalization and unembedding to the last layer matches the output by construction; earlier layers have no such guarantee. A map of top tokens is an even more limited projection, since two distributions can have the same argmax and very different probabilities.
KL is nonnegative and equals zero exactly when the distributions coincide, apart from differences on zero-probability events. Finite softmax outputs assign positive probability to every token, but calculating log(softmax(...)) directly can overflow or round small probabilities to zero. The cell uses log_softmax, which computes logarithms stably. The average is over positions: repeating many positions from the same document does not give more independent documents, and that token count should not be treated as the independent sample size of an interval.
The map also requires position alignment. In a causal sequence, the logit produced at position predicts the next token, not the token occupying . The input shown in the header locates the state being read; the text in each cell is its next-token prediction. A BPE token can be a word fragment or include a leading space, so the evolution of a top token need not match a whole-word prediction. The figure marks that space with ▁.
A probe is not an intervention
A linear probe with controls learns a rule such as with the model frozen. It can reveal that a property is linearly recoverable. It does not establish that the model reads that direction when producing its response. A more flexible probe can reconstruct a property through an operation the model never performs.
Logistic regression supplies probabilities and a loss to fit that rule; its regularization restricts the classifier used as an instrument. The distinction between recoverable information and use by the model is central to linear probing. Here we test a token property and a positional property, then measure the effect of an intervention.
Hewitt and Liang propose control tasks with random labels assigned by word type and consistent across its occurrences. The difference between accuracy on the real task and on the control is selectivity under that protocol. If a probe achieves 95 % on the property and 90 % on the control, selectivity is 5 percentage points: the control warns that memorizing identities may account for much of the success. It does not show that exactly 5 % of the information is linguistic. Changing the type split, frequency or balance alters the control’s difficulty; fix the split and compare with the majority and an identity classifier.
A sentence split tests new contexts, but the same token may occur in training and test. This allows the control to detect memorization of frequent types, precisely the risk it is meant to measure. A split that also separates types asks a different question: whether the rule transfers to unseen identities. Both are useful, but they are not interchangeable. Logistic regression regularization restricts effective capacity; comparing probes with different hyperparameters without a separate validation selection can confound representation quality with classifier quality.
To move from correlation to a causal hypothesis, intervene on the residual and rerun the later layers. If is a normalized probe direction, removing the component is a defined intervention. Compare the final distribution and behavior against a random-direction control of the same norm, multiple magnitudes and examples unused in probe training. This ablation can push the state outside the natural distribution or remove correlated information: a change demonstrates sensitivity to the specific intervention, not that the isolated property is the sole cause.
The operation above is an orthogonal projection in activation space, not in weight or logit space. If has unit norm, the modified residual satisfies . That does not guarantee that the property disappears: it may be redundantly encoded in other directions or rebuilt by later layers. Nor does it necessarily preserve the norm of . For this reason, measure not only the change in argmax but also KL and perturbation size, and compare several control directions.
Lab: GPT-2 and separate texts
The previous lesson accepts the 513-ID GPT of your own or, if absent, the published GPT-2 small. Here we explicitly use the GPT-2 small alternative, with 12 layers and 50257 IDs, at revision 607a30d783dfa663caf39e06633721c8d4cfcd7e. We do not attribute its results to the p06 GPT. We take the first 16 training lines and 8 validation lines from WikiText-2 containing at least 32 tokens, one line per sequence without prepending BOS. This convention differs from the BOS probe in p11-l01; positions are not directly comparable. These are small, separate samples, not evidence of broad generalization. The dataset revision is b08601e04326c79dfdd32d625aee71d232d685c3; the code prints hashes of the selected tokens.
You need PyTorch, Transformers, datasets and scikit-learn. The first run downloads the weights and corpus; the measurements shown used Transformers 5.23.0 and PyTorch 2.11.0. The code keeps the model in evaluation mode and freezes its parameters: only the lenses and, afterwards, separate classifiers are trained. To study a p06 checkpoint, convert and check its weights as in the previous lesson, adapt selection to its 513-ID vocabulary and record a new result; do not mix its figures with those of GPT-2.
The affine translator starts as the identity and is optimized for 80 steps per layer with batches of 32 positions while GPT-2 remains frozen. The KL table uses all validation positions and the entire vocabulary. Layer 11 uses the residual after the last block and before final normalization. Its logit lens matches the final output by construction, so tuning cannot improve that zero KL and can even move slightly away from it.
In a run on RTX 3060, validation KL for layer 0 is 7.210 with the logit lens and 4.955 with the tuned lens; at layer 10 it is 1.112 versus 0.794. At layer 11 the values are 0 and 0.0015, respectively. The tuned lens improves the first eleven layers in this sample, but not every layer or every dataset by definition. Evaluation texts are not used to fit the translators.
The two probe properties are position parity and whether the isolated token, after removing spaces, consists only of letters. The second is a tokenization property, not a human part-of-speech label. The control assigns a fixed pseudorandom bit per token ID. At layer 5, validation accuracy is 53.13 % for parity and 95.70 % for the alphabetic property, versus 67.19 % for the control. The latter’s selectivity is 28.52 percentage points. The majority proportion is 82.42 %, so it should accompany accuracy. Parity does not show strong recovery against its control here.
Projecting out the parity probe direction at that layer changes the final argmax for 4.69 % of evaluated positions; an equal-norm random direction changes 9.77 %. Equal direction norms do not equalize the norm of the components subtracted from each example: a finer control should also match that magnitude and use several random directions. The control has a larger effect in this run, so there is no basis to conclude that the model uses parity via that path. The change does show that the particular intervention affects some outputs. Both numbers refer only to these texts and this intervention.
import hashlib, json, random
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from transformers import AutoTokenizer, GPT2LMHeadModel
from datasets import load_dataset
from sklearn.linear_model import LogisticRegression
torch.manual_seed(17); np.random.seed(17); torch.set_num_threads(2)
device='cuda' if torch.cuda.is_available() else 'cpu'
repo='openai-community/gpt2';rev='607a30d783dfa663caf39e06633721c8d4cfcd7e'
datarev='b08601e04326c79dfdd32d625aee71d232d685c3'
tokenizer=AutoTokenizer.from_pretrained(repo,revision=rev)
model=GPT2LMHeadModel.from_pretrained(repo,revision=rev,attn_implementation='eager').eval().to(device)
for parameter in model.parameters():parameter.requires_grad_(False)
config=model.config
def texts(split,n):
dataset=load_dataset('Salesforce/wikitext','wikitext-2-raw-v1',split=split,revision=datarev)
selected=[]
for row in dataset:
ids=tokenizer.encode(row['text'])
if len(ids)>=32:
selected.append(ids[:32])
if len(selected)==n:break
assert len(selected)==n
return torch.tensor(selected,device=device)
train=texts('train',16);test=texts('validation',8)
for name,tokens in [('train',train),('validation',test)]:
print(name,'SHA256 tokens',hashlib.sha256(tokens.cpu().numpy().tobytes()).hexdigest())
def cache(x):
states=[];handles=[]
for block in model.transformer.h:
def record(module,args,output):states.append((output[0] if isinstance(output,tuple) else output).detach())
handles.append(block.register_forward_hook(record))
try:
with torch.no_grad():logits=model(x,use_cache=False).logits.detach()
finally:
for handle in handles:handle.remove()
assert len(states)==12
return torch.stack(states),logits
train_h,train_z=cache(train);test_h,test_z=cache(test)
teacher=F.softmax(train_z.reshape(-1,config.vocab_size),dim=-1)
teacher_log=F.log_softmax(train_z.reshape(-1,config.vocab_size),dim=-1)
eval_teacher=F.softmax(test_z.reshape(-1,config.vocab_size),dim=-1)
eval_log=F.log_softmax(test_z.reshape(-1,config.vocab_size),dim=-1)
def decode(h):return model.lm_head(model.transformer.ln_f(h))
def kl(logq,p,logp):return (p*(logp-F.log_softmax(logq,dim=-1))).sum(-1).mean()
rows=[];lenses=[]
for layer in range(12):
raw_train=train_h[layer].reshape(-1,config.n_embd)
raw_test=test_h[layer].reshape(-1,config.n_embd)
affine=nn.Linear(config.n_embd,config.n_embd,device=device)
with torch.no_grad():affine.weight.copy_(torch.eye(config.n_embd,device=device));affine.bias.zero_()
opt=torch.optim.AdamW(affine.parameters(),lr=1e-4,weight_decay=.01)
rng=torch.Generator(device='cpu').manual_seed(1700+layer)
for step in range(80):
idx=torch.randperm(raw_train.shape[0],generator=rng)[:32].to(device)
loss=kl(decode(affine(raw_train[idx])),teacher[idx],teacher_log[idx])
opt.zero_grad(set_to_none=True);loss.backward();opt.step()
with torch.no_grad():
baseline=kl(decode(raw_test),eval_teacher,eval_log)
tuned=kl(decode(affine(raw_test)),eval_teacher,eval_log)
rows.append({'layer':layer,'logit_kl':float(baseline),'tuned_kl':float(tuned)})
lenses.append(affine);print(rows[-1],flush=True)
layer=5
def probe_data(tokens,states):
ids=tokens.cpu().numpy().ravel();features=states[layer].cpu().numpy().reshape(-1,config.n_embd)
parity=np.tile(np.arange(tokens.shape[1]),tokens.shape[0])%2
letters=np.array([int(tokenizer.decode([int(t)]).strip().isalpha()) for t in ids])
control=np.array([random.Random(int(t)+391).randrange(2) for t in ids])
return features,{'paridad':parity,'alfabetico':letters,'control':control}
X,y=probe_data(train,train_h);Xt,yt=probe_data(test,test_h)
scores={};probes={}
for name in y:
probe=LogisticRegression(C=.01,max_iter=2000,random_state=17).fit(X,y[name])
probes[name]=probe
scores[name]={'train':float(probe.score(X,y[name])),'test':float(probe.score(Xt,yt[name])),
'mayoritaria_test':float(max(np.mean(yt[name]),1-np.mean(yt[name])))}
print('Sondas:',scores)
direction=torch.tensor(probes['paridad'].coef_[0],device=device,dtype=train_h.dtype)
direction/=direction.norm()
def intervene(direction):
def hook(module,args,output):
residual=output[0] if isinstance(output,tuple) else output
changed=residual-(residual@direction)[...,None]*direction
return (changed,)+output[1:] if isinstance(output,tuple) else changed
handle=model.transformer.h[layer].register_forward_hook(hook)
try:
with torch.no_grad():logits=model(test,use_cache=False).logits.reshape(-1,config.vocab_size)
finally:handle.remove()
return (float(kl(logits,eval_teacher,eval_log)),
float((logits.argmax(-1)!=test_z.reshape(-1,config.vocab_size).argmax(-1)).float().mean()))
random_direction=torch.randn_like(direction);random_direction/=random_direction.norm()
print('Intervención, KL y fracción de argmáximos cambiados:',
'sonda',intervene(direction),'aleatoria',intervene(random_direction))npm run lab and open the connection link.The following cell shows the twelve map positions so you can check which top token each readout selected. The model and lenses are those from the previous cell.
print('Entrada:',[tokenizer.decode([int(t)]) for t in test[0,:12]])
for layer,affine in enumerate(lenses):
with torch.no_grad():
direct=decode(test_h[layer,0,:12]).argmax(-1)
translated=decode(affine(test_h[layer,0,:12])).argmax(-1)
print('capa',layer,'directa',[tokenizer.decode([int(t)]) for t in direct],
'afinada',[tokenizer.decode([int(t)]) for t in translated])npm run lab and open the connection link.Exercises
def logit_lens(cache, layer, norm, unembed):
pass