Sparse autoencoders on the residual stream
Train overcomplete sparse autoencoders on the residual stream, using the instrumented model or GPT-2 small as the public fallback from Lesson 1. Process tens of millions of tokens with L1 and TopK sparsity, measure standard metrics and revive inactive latents. Use a local language model to explain a hundred features and score its ability to predict activations.
After this lesson you can
- Generate and store activations on disk and train sparse autoencoders with L1 and TopK.
- Measure L0, reconstruction error, loss recovered and inactive latents.
- Compare the sparsity–fidelity frontier of the two variants.
- Use a local language model to interpret 100 latents automatically and score the explanations.
Before you start
Many features in a shared channel
One residual coordinate can participate in several properties. Looking only for a neuron that activates on a word confuses the basis in which vectors are stored with directions that might encode properties. The superposition hypothesis proposes that a model can represent more features than dimensions when activations are sparse. It does not guarantee that every direction learned by another model is a unique or interpretable feature.
This mixture is related to polysemanticity: a neuron can respond to apparently different contexts. An SAE is a nonlinear autoencoder with an overcomplete bottleneck and a sparsity constraint, not a guarantee that every latent has one function. Sparse regularization imposes a mathematical preference; interpretation needs additional evidence.
To separate candidates, an overcomplete dictionary uses more columns than residual dimensions and requires each vector to activate only a few. This connects to dictionary learning and sparse coding. The cost is imperfect identification: two different dictionaries can reconstruct the same data well, and one direction can mix concepts. Quality is measured on separate texts and through interventions on the original model.
Encoder, decoder and scale
The parameterization has a scale symmetry: multiplying a decoder column by and dividing the corresponding activation by preserves its contribution. Without normalizing columns, an activation penalty can be reduced by inflating the decoder. Keeping each column at unit norm fixes that scale ambiguity. It does not resolve permutation ambiguity of latents or make the dictionary unique.
Data normalization and decoder normalization have different roles. The lab estimates a mean per coordinate and a scalar root-mean-square scale on the first 100,000 training vectors; it transforms each residual by subtracting that mean and dividing by the scale. When inserting a reconstruction into the model, it reverses the transformation: multiply by the same scale and add the same mean. Validation plays no part in fitting those constants. Forgetting this inverse operation changes the units and reference point of all residuals, even if the SAE seems to work in its own normalized space.
Each latent has two directions with distinct roles. An encoder row decides when it activates from the centered residual; a decoder column determines what is added to the reconstruction. They need not remain equal after training. High similarity between rows or columns does not prove functional duplication either: compare activations on held-out examples and the consequence of removing a contribution. Conversely, different directions may respond in a correlated way to the same limited distribution.
With an L1 penalty one minimizes a trade-off such as
Conventions for averaging or summing across dimensions change the numerical value of : state them when comparing implementations. A scalar example shows shrinkage. If the decoder is 1 and , minimizing with gives . Even a correct feature is reconstructed with magnitude below . This is called shrinkage bias.
TopK selects the largest nonnegative activations per token and zeros the others. It directly controls a maximum of nonzero activations, but if a selected one is zero, effective is lower. It does not impose a penalty proportional to selected activation magnitudes; discrete selection can change when two scores cross. Gao and colleagues study TopK, dead latents and evaluation metrics in SAEs at several scales. Their training on GPT-4 is not a result from our model.
In this experiment’s code squared error is averaged over batch and coordinates, while the L1 penalty sums latents per token then averages tokens. Thus the same value would mean something else if both parts were summed without normalization or residual dimension changed. Compare configurations by observed and measured losses as well as stating the hyperparameter. TopK alone does not guarantee a useful dictionary: it can distribute activations among redundant directions or leave latents unused.
Hard selection has an optimization limit. Latents outside the selected receive no gradient from the main reconstruction for that token. If a unit remains outside for many batches, it may have few opportunities to compete; the auxiliary term below gives it another training signal. If two positive scores cross, the selected set changes abruptly. This does not invalidate the gradient calculated for the current selection, but reminds us it is a piecewise approximation, not a smooth derivative of the selected index.
A dead latent is not an absent property
A latent that does not activate in a finite window may be dead or rare in that sample. Report the number of tokens, window and rule. An auxiliary can select inactive latents and ask them to reconstruct the part left unexplained by the main SAE. Another strategy resets inactive directions using reconstruction residuals and also resets optimizer moments for those coordinates. Both alter training and require controls: declaring latents dead after too few batches discards rare features.
As a scale reference, Gao and colleagues describe a typical window of ten million tokens, for GPT-2 small and an auxiliary coefficient . These are their protocol choices, not universal properties. A lab with another window, another or explicit resets must declare it and not present its figures as an exact replication. The auxiliary mask must select only inactive candidates, even if their nonpositive scores tie at zero.
Save activations from a specific layer, with model identity and hash, corpus, tokenizer, position and precision. The evaluation set must come from separate documents. For tokens and dimension , storage with two bytes per component is bytes, excluding IDs, indices and metadata. Fifty million vectors of dimension 768 occupy 76.8 decimal GB, about 71.53 GiB. A matrix of fifty million components is a different, much smaller scale.
The educational lab variant uses windows of 1000 batches of 4096 vectors, up to 4,096,000 tokens. At a window’s end it marks latents without activations in the main TopK; for them it uses up to 32 positive activations in the auxiliary loss, with coefficient . The auxiliary target is residual detached from the gradient graph. It does not use per-token auxiliary normalization or the decoder gradient projection described in Gao’s protocol; it also does not use their threshold or . The mask is updated when a candidate re-enters the main TopK.
In addition, this implementation resets inactive candidates with reconstruction-error directions from the last batch. It normalizes the decoder column and assigns the encoder a direction of norm 0.02; it zeros Adam’s first and second moments for reset coordinates. The optimizer’s global step counter remains: this is not equivalent to creating a new Adam for each latent. Since auxiliary activity does not count as entry into the main TopK, a candidate can receive auxiliary gradient and still meet the reset criterion in a later window. Metrics around each reset should be saved to detect oscillations; these choices are part of the experiment, not a canonical procedure.
For L1, positive activations are counted over the same window and the reset rule is applied, but AuxK is not added. Batches of 4096 are traversed in a fixed permutation, retaining token contiguity inside each block. Order and window are part of the saved training identity; they are not a uniform shuffle of individual documents.
Reconstruction is not enough
SAE evaluation metrics answer different questions. is the number of strictly positive latents per token, averaged. Reconstruction error compares with , but residual directions do not have equal importance for the model’s loss. A reconstruction with small Euclidean error can erase a small direction that greatly affects a logit.
To measure the consequence, run the same model and validation batch three times: original residual, residual replaced by reconstruction, and residual replaced by zero. With next-token losses , and , define
The fraction is 1 if replacement preserves base loss and 0 if it matches the zero control. It can be negative or greater than 1. Zero may be out of distribution; it is an operational reference, not a neutral intervention. Present all three losses and the denominator as well as . To build the sparsity-versus-fidelity frontier, train several configurations and measure all on the same set. Comparing one configuration per family does not establish which method dominates.
The error metric also depends on the reference. The ratio asks how much error remains relative to data energy on the chosen scale. It is not necessarily one minus variance explained around the mean unless data are centered with the same mean. To compare models use the same set and normalization; if a configuration reconstructs a different residual or another layer, its figures are not directly comparable.
The density window matters for rare latents. If a latent has activation probability in independent tokens, the probability of not observing it in tokens is . For example, with and it is approximately , so a real but infrequent feature can appear dead in that sample. Text tokens are not independent, so this approximation is illustrative, not a confidence interval for a corpus. Report densities and document the reset rule alongside window size.
When replacing the residual, the zero control and base model must use exactly the same tokens, positions and loss mask. If the corpus changes across the three runs, some difference may be due to text difficulty. Replacement must affect the site used to collect data: a block-output SAE is not equivalent to a block-input SAE, even if both vectors have 768 coordinates. Remove the hook after each condition and run an identity condition to check the replacement mechanism does not accidentally alter the model.
An observed curve is not automatically an optimal frontier. If one configuration achieves higher fidelity at equal or lower , it dominates another on those two metrics; but they may differ in training cost, inactive latents and interpretability. With few points you do not know whether an intermediate configuration would be better. Numbers of vectors and documents, batch mixing and seed also limit comparison. Retain unnormalized losses and results of every configuration, including dominated ones.
Explanations that predict new examples
Automatic feature interpretation shows a local model training snippets where a latent activates and asks for a brief hypothesis. That explanation is not a true label. Then, for validation snippets not shown to the interpreter, use the explanation to predict which snippet in a pair activates the latent more. Compare accuracy with chance and with explanations permuted across latents, keeping the same pairs. Fix selection and order beforehand, record invalid answers and do not silently discard failures.
The agent project’s local service lets the interpreter run without sending snippets to a remote service. If requesting structured output, validate its schema and retain both text and failures; valid JSON does not make the explanation true. The same interpreter can perform forced prediction, provided that dependence is declared and permuted explanations are compared under the same protocol.
Maximum examples are useful for generating hypotheses but bias the impression: a feature can activate in different contexts. Also inspect medium and negative samples, and tokens favored by its decoder direction when projected to logits, with the limits of normalization and later layers. An explanation predicting held-out examples is evidence of predictive usefulness, not proof the original model uses that feature causally.
Forced choice between two options has its own decisions. If the interpreter receives an explanation and two snippets, fixed order can introduce a preference for A or B; alternate the position of the more activating snippet and check that the tokenizer represents both options as expected. A permuted explanation preserves format but breaks its association with the latent. If the real score does not exceed that control, the result does not justify claiming explanations identify activations better, even if some sound plausible. Evaluate all selected latents, including those with poor explanations.
In this protocol 100 latents are chosen by frequency in the first 32,768 training vectors before consulting validation. For each, five high-activation training snippets are provided. The predictor then receives eight new pairs chosen from the 99,968 held-out vectors: each combines a positive snippet and a zero-activation one, with alternating order. The score of token A is compared with token B at the first answer position; this forces a choice without depending on the model writing valid format. This is a discrimination task between extremes, not an estimate of continuous activation or a test of monosemanticity.
The permuted control uses the same pairs and shifts descriptions across latents. It can be easier or harder than another random control if several descriptions are similar, so retain individual predictions and specify the permutation. The model writing and predicting is the same local quantized Qwen 7B; its agreement may reflect shared biases. Up to 128 tokens are allowed for each explanation and its termination is recorded. A grammar restricts the answer to A or B tokens and the lab verifies their log probabilities to check which scores higher. A next experiment could use a different evaluator and intermediate-activation samples while keeping latent selection and evaluation set separate.
The API returns log probabilities of the most likely tokens, and A or B are not always among the top two. To avoid losing those pairs, the protocol requests the top 50; if an option is missing, it forces that option in another query and retrieves the selected token’s original log probability. Check that the order of A and B matches the restricted answer and record each fallback query. This avoids confusing “did not appear among the top” with zero probability.
Lab: from tokens to dictionary
The reference run uses published GPT-2 small, the alternative from p11-l01, and WikiText-103 at a fixed revision. It extracted 20,000,000 training vectors of dimension 768 and 99,968 validation vectors from the residual after layer 6 in sequences of 128 tokens. The float16 training file occupies 30,720,000,000 bytes; tokens and metadata are stored separately. The validation split comes from different documents and is not used to estimate normalization or select latents.
Published resources are GPT-2 small, WikiText-103 and Qwen2.5-7B-Instruct-GGUF Q4_K_M. The package pins those revisions: check the GPT and corpus files directly, and document how to verify the two GGUF files before starting the server.
The lab package contains instructions and files for corpus download, activation extraction, training and evaluation, preparation, server interpretation, auxiliary interpreter and block reader. Save them together and run in order:
python wikitext.py
python extract.py
python train.py
python prepare.py
python interpret-server.py explain
python interpret-server.py real
python interpret-server.py shuffled
python interpret-server.py assemble
The code checks revisions and hashes, writes resumable checkpoints and reads residuals by ranges rather than mapping the entire training file into memory. Eight configurations use two widths, 1536 and 3072; for each width L1 is tested with and , and TopK with and . Each configuration traverses all 20 million vectors once in blocks shuffled with a fixed seed. The quick option documented in the package checks installation but does not produce the full figures.
The model core can be examined separately. Normalizing decoder columns removes one scale freedom; for TopK, selected zeros do not count as positive activations.
import torch
from torch import nn
import torch.nn.functional as F
class SAE(nn.Module):
def __init__(self, d, features, kind, k=32):
super().__init__()
self.encoder=nn.Linear(d,features)
self.decoder=nn.Linear(features,d,bias=False)
self.bias=nn.Parameter(torch.zeros(d))
self.kind,self.k=kind,k
with torch.no_grad():
self.decoder.weight.copy_(F.normalize(self.decoder.weight,dim=0))
self.encoder.weight.copy_(self.decoder.weight.T)
self.encoder.bias.zero_()
def forward(self,x):
pre=self.encoder(x-self.bias)
z=F.relu(pre)
if self.kind=='topk':
values,indices=z.topk(self.k,dim=-1)
z=torch.zeros_like(z).scatter(-1,indices,values)
return self.decoder(z)+self.bias,z,pre
torch.manual_seed(1806)
sae=SAE(d=4,features=8,kind='topk',k=2)
x=torch.tensor([[1.,-1.,0.5,0.],[0.,0.,0.,0.]])
reconstruction,z,_=sae(x)
assert reconstruction.shape==x.shape and (z>0).sum(-1).max()<=2
print('forma',tuple(reconstruction.shape),'L0 por fila',(z>0).sum(-1).tolist())npm run lab and open the connection link.The complete lab adds the L1 term or auxiliary for inactive candidates, optimizer update, renormalization and evaluation of the intervened model. The example above checks shapes and selection; its small dimensions do not replace training or justify the frontier figures.
For intervened loss, the same 128 held-out sequences of 128 tokens were used: 16,256 next-token predictions per condition. Base loss is 4.0588 nats per token, and the identity hook reproduces it; zeroing the layer residual gives 14.1725. , error and the fraction of inactive latents are measured on the 99,968 held-out vectors, a larger sample. All checkpoints come from one complete traversal of 20 million vectors, with the same split and normalization.
The TopK with 3072 latents and has , normalized error 0.01047 and four latents without validation activations, 0.13%. Replacing the residual yields loss 4.2340 and recovered fraction 0.9827 relative to the zero control. For the fraction is 0.9892 and ; that difference does not show universal superiority, since it uses one intervention, layer and sample. Zero may be a very damaging reference: report original losses along with the fraction and do not interpret it as percentage of understanding or true features.
The 100 explanations of TopK were generated with Qwen2.5-7B-Instruct Q4_K_M on a local server. In 800 decisions on held-out pairs, the corresponding description got 517 right, 64.625%; cyclically shifting descriptions got 394 right, 49.25%. The difference is 15.375 percentage points. For 60 latents the matching description got more pairs right than the permuted one, for 16 they tied and for 24 it got fewer right. The result supports average predictive usefulness for this selection, not that all explanations are correct.
All 100 explanations ended by end-of-sequence within the 128-token maximum. All 1600 decisions verified both log probabilities among the 50 most likely tokens, without fallback queries. Descriptive resampling of the 100 latents, with 10,000 replicates and seed 1819, gives a percentile interval of 9.875 to 20.75 points for the accuracy difference. Latents were chosen by frequency and may share texts, so that interval does not automatically generalize to all latents or other corpora. The same models generate and evaluate explanations, and pairs compare positive extremes against zeros; both choices narrow the conclusion.
You can inspect the complete results of the eight SAEs and the 1600 decisions with their log probabilities. The browser loads only the data needed to visualize the 100 latents.
Exercises
def topk_aux(x, encoder, decoder, bias, k, dead, aux_k):
pass