Module contents
Stage 6 of 8Research 120 min

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 c>0c>0 and dividing the corresponding activation by cc 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

L=E∥x−x^∥22+λE∥z∥1.\Loss=\E\norm{\vb{x}-\hat{\vb{x}}}_2^2+\lambda\E\norm{\vb{z}}_1.

Conventions for averaging or summing across dimensions change the numerical value of λ\lambda: state them when comparing implementations. A scalar example shows shrinkage. If the decoder is 1 and x>0x>0, minimizing (x−z)2+λz(x-z)^2+\lambda z with z≥0z\ge0 gives z=max⁡(0,x−λ/2)z=\max(0,x-\lambda/2). Even a correct feature is reconstructed with magnitude below xx. This is called shrinkage bias.

TopK selects the kk largest nonnegative activations per token and zeros the others. It directly controls a maximum of kk nonzero activations, but if a selected one is zero, effective L0L_0 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 λ\lambda value would mean something else if both parts were summed without normalization or residual dimension changed. Compare configurations by observed L0L_0 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 kk 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, kaux=512k_{\mathrm{aux}}=512 for GPT-2 small and an auxiliary coefficient 1/321/32. These are their protocol choices, not universal properties. A lab with another window, another kauxk_{\mathrm{aux}} 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 NN tokens and dimension dd, storage with two bytes per component is 2Nd2Nd 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 1/321/32. The auxiliary target is residual x−x^\vb{x}-\hat{\vb{x}} 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 kauxk_{\mathrm{aux}}. 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. L0L_0 is the number of strictly positive latents per token, averaged. Reconstruction error compares x^\hat{\vb{x}} with x\vb{x}, 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 ℓbase\ell_{\rm base}, ℓrec\ell_{\rm rec} and ℓ0\ell_0, define

F=ℓ0−ℓrecℓ0−ℓbase,ℓ0≠ℓbase.F=\frac{\ell_0-\ell_{\rm rec}}{\ell_0-\ell_{\rm base}},\qquad \ell_0\ne\ell_{\rm base}.

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 FF. 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 ∑∥x−x^∥22/∑∥x∥22\sum\norm{\vb{x}-\hat{\vb{x}}}_2^2/\sum\norm{\vb{x}}_2^2 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 pp in independent tokens, the probability of not observing it in nn tokens is (1−p)n(1-p)^n. For example, with p=10−5p=10^{-5} and n=100000n=100000 it is approximately e−1e^{-1}, 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 L0L_0, 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 λ=0.0005\lambda=0.0005 and 0.0020.002, and TopK with k=32k=32 and 6464. 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.

[ ]An L1 or TopK SAE from scratchLocal GPU
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())
This cell needs the local lab (PyTorch with your GPU). Start it with 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. L0L_0, 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.

InteractiveSparsity and recovered loss in eight SAEs
  • L1, 1536 latents
  • TopK, 1536 latents
  • L1, 3072 latents
  • TopK, 3072 latents

Each point comes from a training run and evaluation. Lines join the tested parameters; they do not prove behavior between points or guarantee an optimal frontier.

Mean L0100.73
Recovered loss0.969
Inactive validation latents0.0 %
Mean density6.6 %
Normalized error0.014
Select a configuration to compare mean L0, fraction of loss recovered and latents that did not activate on validation. Lines connect measured parameters for each family and width.

The TopK with 3072 latents and k=32k=32 has L0=32L_0=32, 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 k=64k=64 the fraction is 0.9892 and L0=64L_0=64; 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 k=32k=32 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.

InteractiveExplore one hundred interpreted latents

Automatic explanation: These text endings appear to be fragments of sentences that lack context and coherence, often ending abruptly or mid-sentence. A concise hypothesis is: These text endings are incomplete sentence fragments that lack proper context and grammatical structure.

Training examples with high activation:

  1. inch ( 203 mm ) , 150 @-@ pound Parro
  2. 1980s to escape civil unrest between the Tamils and Sinh
  3. his NHL debut during the season . Conversely , Vaclav Prosp
  4. vocals along with Billy T. Scott , Jamiliah Muham
  5. . During the game , several milestones were reached . James Wisn

Approximate linear token readout: "cloneembedreportprint", "�", "\u001a", "�", "\u0005", " externalToEVA", " RandomRedditor", "InstoreAndOnline", "", "\u0006"

0.000 to 0.327: 45203 tokens0.327 to 0.655: 12017 tokens0.655 to 0.982: 11103 tokens0.982 to 1.310: 9697 tokens1.310 to 1.637: 8093 tokens1.637 to 1.965: 6080 tokens1.965 to 2.291: 3681 tokens2.291 to 2.619: 2083 tokens2.619 to 2.947: 1020 tokens2.947 to 3.273: 477 tokens3.273 to 3.602: 247 tokens3.602 to 3.930: 132 tokens3.930 to 4.258: 58 tokens4.258 to 4.582: 46 tokens4.582 to 4.910: 24 tokens4.910 to 5.238: 7 tokens05.238

Logarithmic count height, including the zero bin. Isolated tokens may contain incomplete bytes, control characters or replacement symbols. The linear projection omits final normalization and later layers: it is not a causal prediction.

Matches100
Histogram tokens99968
Search for text, token or explanation and select a latent. The histogram uses all held-out vectors; the five maximum-activation examples belong to training. Token projection is linear and approximate.

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

Numeric
How many decimal GB do 50 million vectors of 768 components occupy at two bytes per component, excluding metadata?
Quiz
What distinguishes TopK from an L1 penalty on retained latents?
Quiz
An SAE reconstructs with low MSE but recovers little loss. What might have happened?
Code
Implement topk_aux(x, encoder, decoder, bias, k, dead, aux_k) in PyTorch. encoder and decoder are functions without output bias; encoder receives x−bias. Apply ReLU and retain at most k activations per row. Return (reconstruction, z, auxiliary loss). For the auxiliary select up to aux_k latents marked in the boolean dead mask, decode their activations and compute MSE against (x−reconstruction).detach(). If no latents are marked, auxiliary loss is scalar zero.
def topk_aux(x, encoder, decoder, bias, k, dead, aux_k):
  pass
Shift+Enter to run
Key idea
An SAE is a learned sparse dictionary, not an automatic list of true concepts. Compare sparsity, reconstruction, recovered loss and the predictive ability of explanations on separate data.