Sparse autoencoders: feature dictionaries
Study sparse autoencoders as amortized sparse coding on activations, including decoder normalization, biases, penalties, shrinkage, and TopK, BatchTopK, JumpReLU, and Gated variants. Train and evaluate SAEs, build a feature dashboard, and investigate splitting and absorption.
After this lesson you can
- Implement a ReLU SAE with an L1 penalty and normalized decoder, explaining each design decision.
- Derive the shrinkage introduced by the L1 penalty and implement TopK and JumpReLU to avoid it.
- Evaluate SAEs with L0, reconstruction error, recovered cross-entropy, and dead latents, and plot their Pareto frontier.
- Interpret features using activation examples across their range, logit effects, and automatic explanations.
- Detect feature splitting and absorption as the dictionary size changes.
Before you start
Decomposing an activation
A sparse autoencoder learns a dictionary to reconstruct activations using few coefficients. A common architecture centers the input with , encodes it, and decodes it:
The loss combines reconstruction and sparsity, for example . This is an amortized approximation to sparse coding: the encoder predicts coefficients in one pass instead of optimizing them from scratch for every input. Decoder columns are usually normalized: without a scale constraint, multiplying a column by and dividing its coefficient by preserves the reconstruction while artificially reducing the L1 penalty.
Magnitude matters too
In one dimension, minimizing gives . Even large signals shrink by . The figure compares this solution with an illustrative hard threshold, which preserves the magnitude of retained signals. It does not claim that both minimize the same objective.
Activation variants change the tradeoff. TopK keeps the largest values per example; BatchTopK allocates a budget across the batch, so examples may have different numbers of active latents. JumpReLU retains a preactivation if it exceeds a learned threshold and uses special estimators to train through the discontinuity. Gated separates feature selection from magnitude estimation. These are distinct families, with no guarantee of unbiasedness in every training run. See Gao and colleagues, JumpReLU y Gated SAE.
Evaluation inside and outside the dictionary
Evaluation metrics answer different questions. counts active latents per example; the unexplained variance fraction compares squared error to activation variability; firing frequency identifies dead or very dense latents for a stated dataset and threshold. To measure model impact, replace the original activation with its reconstruction and evaluate next-token loss on held-out data. With original loss , reference ablation , and inserted SAE , a common recovered fraction is
It is undefined when the denominator is zero, depends on the ablation, and can fall outside [0,1]. A reconstruction with low squared error does not guarantee preservation of the directions most important to the model. Compare several sizes and sparsity levels, and plot the fidelity frontier against .
The following six points come from our own training runs on the residual output of GPT-2 small block 5, with 1024 latents and 400 steps per configuration. The training set contains 6852 positions and the evaluation set 1503 positions from different WikiText-2 documents; one seed and short training cannot compare model families in general. Original and ablated losses are 3.828 and 13.619 nats per token. The figure shows measured points rather than a certified optimal frontier. For example, TopK with recovers 0.812 of the loss with , but 714 of its 1024 latents do not activate in this sample.
Feature interpretation requires examining examples with high, medium, low, and absent activation, together with controls and intervention effects. Projecting the decoder direction onto logits can help, but does not alone identify a complete concept. Automatic explanations must be evaluated on held-out examples; an appealing label does not establish monosemanticity.
The dashboard uses three latents from the L1 SAE with , selected by variation across the first eight validation documents. The histogram and examples cover all 1503 positions; some maximum activations occur at document starts, a positional hypothesis worth investigating. Logit changes are measured by adding a decoder direction at a specific position and running the remaining layers: the “largest change” can be negative if every logit falls. The automatic explanation is a deliberately simple lexical rule, selected on eight documents and scored on the other eight; precision and recall use the upper-quartile threshold from selection. Tokens may be BPE fragments. Labels and marks persist only while the figure remains open.
In splitting and absorption, changing dictionary size or training can distribute a general pattern across more specific latents or stop a general latent from firing in contexts covered by another. Overlapping examples and latent correlations help formulate hypotheses, but do not prove a unique correspondence between dictionaries. Some information may remain unexplained by the SAE.
The following search uses three public dictionaries from the same GPT-2 family at the input of block 8, with 1536, 6144, and 24 576 latents. We select the small latent whose second decoder neighbor in the medium dictionary has the highest cosine similarity, then find a large-dictionary neighbor for each candidate. Across 827 positions in eight documents, at least one medium candidate fired in 67, and the small parent did not fire in 27 of those. This suggests a splitting or absorption investigation but does not prove either: near-identical directions may be duplicates, and frequencies do not establish meaning or causality.
You can run the search code in the SAELens environment described below. It downloads the gpt2-small-res-jb-feature-splitting family; our cache corresponds to revision 174d298f1633aab71e440685c3292ce8108a5a73 of the public repository. The loader defaults to the current revision, so check its version before comparing future runs.
Reproducing the SAEs and dashboard
Download the reproducible training script and the dashboard generator. In a local environment with PyTorch, Transformers, Hugging Face Hub, pandas, and PyArrow, run python sae_experiment.py first and python dashboard.py second from the same directory. The first program creates sae-output/ with all six sets of weights and metrics; the second loads the L1 SAE from that directory. GPT-2 and WikiText-2 revisions are pinned in the files. You can add --cuda to the first command if you have a compatible GPU. The JumpReLU threshold is learned with a rectangular window of width 0.1 as a gradient estimator; that is not the ordinary derivative of the jump. Training normalizes each decoder column and counts dead latents but does not resample them: compare their frequencies before choosing a resurrection policy.
As a separate reference, SAELens can load a pretrained dictionary of 24 576 latents for blocks.6.hook_resid_pre, the location after block 5. The following test uses TransformerLens in compatibility mode because the dictionary was trained with that weight-processing convention. For one 11-token sentence including BOS, we obtained and per-coordinate MSE 0.357; zero output gives 1091.81 for the same activation. These figures use one sentence and a different weight convention, so they do not belong to the earlier comparison. Our environment used SAELens 6.55.5, TransformerLens 4.4.0, and repository jbloom/GPT2-Small-SAEs-Reformatted at revision 57d08a4fd333fbf18caf3fbea63ceeb88e2f50d9.
import torch
from sae_lens import SAE
from transformer_lens import TransformerBridge
torch.set_num_threads(2)
sae=SAE.from_pretrained(release='gpt2-small-res-jb',sae_id='blocks.6.hook_resid_pre',device='cpu')
model=TransformerBridge.boot_transformers('openai-community/gpt2',revision='607a30d783dfa663caf39e06633721c8d4cfcd7e',device='cpu')
model.enable_compatibility_mode()
with torch.inference_mode():
_,cache=model.run_with_cache('The scientist wrote a careful report about the experiment.',names_filter=lambda n:n=='blocks.6.hook_resid_pre')
x=cache['blocks.6.hook_resid_pre'];z=sae.encode(x);rec=sae.decode(z)
print('forma',tuple(z.shape),'L0',float((z>0).sum(-1).float().mean()),
'MSE',float((rec-x).square().mean()),'salida cero',float(x.square().mean()))npm run lab and open the connection link.Lab: recovering synthetic directions
We create six true directions in three dimensions and sparse mixtures with positive amplitudes. We train a ReLU SAE with L1 and normalize decoder columns after each step. On new examples we measure reconstruction, , activations per latent, and the mean best cosine similarity for each true direction. The last metric can assign the same learned direction to multiple true directions; it does not establish a one-to-one correspondence. This is not an evaluation on a language model.
import numpy as np
rng=np.random.default_rng(21)
d,n,m=3,6,8
D=rng.normal(size=(d,n));D/=np.linalg.norm(D,axis=0)
def sample(count):
f=rng.exponential(size=(count,n))*(rng.random((count,n))<.1)
return f@D.T
train=sample(3000);test=sample(2000)
E=rng.normal(0,.2,(d,m));Dhat=rng.normal(0,.2,(d,m));Dhat/=np.linalg.norm(Dhat,axis=0);be=np.zeros(m);bd=np.zeros(d)
rate=.01; lam=.1
for t in range(1800):
x=train[rng.integers(len(train),size=128)];u=(x-bd)@E+be;z=np.maximum(u,0);rec=z@Dhat.T+bd;dr=2*(rec-x)/len(x)
gd=dr.T@z; dz=dr@Dhat+lam/len(x);du=dz*(u>0);ge=(x-bd).T@du; gbe=du.sum(0); gbd=dr.sum(0)-(du@E.T).sum(0)
Dhat-=rate*gd;Dhat/=np.maximum(np.linalg.norm(Dhat,axis=0),1e-8);E-=rate*ge;be-=rate*gbe;bd-=rate*gbd
u=(test-bd)@E+be;z=np.maximum(u,0);rec=z@Dhat.T+bd
cos=D.T@Dhat
print('mse',np.mean(np.sum((test-rec)**2,axis=1)),'zero',np.mean(np.sum(test**2,axis=1)),'L0',np.mean(np.sum(z>0,axis=1)),'mean_max_cos',np.mean(cos.max(axis=1)),'activaciones_por_latente',(z>0).sum(axis=0).tolist())
This sweep resets the model and generator for each size and penalty pair. Test samples are fresh within each run; comparing a few seeds does not establish a scaling law.
import numpy as np
for m in (6,12):
for lam in (.02,.2):
rng=np.random.default_rng(2101);d,n=3,6
true=rng.normal(size=(d,n));true/=np.linalg.norm(true,axis=0)
def sample(k):return (rng.exponential(size=(k,n))*(rng.random((k,n))<.1))@true.T
train=sample(3000);test=sample(2000)
E=rng.normal(0,.2,(d,m));D=rng.normal(0,.2,(d,m));D/=np.linalg.norm(D,axis=0)
be=np.zeros(m);bd=np.zeros(d)
for step in range(1200):
x=train[rng.integers(len(train),size=128)];u=(x-bd)@E+be;z=np.maximum(u,0)
rec=z@D.T+bd;dr=2*(rec-x)/len(x);gd=dr.T@z
du=(dr@D+lam/len(x))*(u>0);ge=(x-bd).T@du;gbe=du.sum(0)
gbd=dr.sum(0)-(du@E.T).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);rec=z@D.T+bd
print('m',m,'lambda',lam,'MSE',round(float(np.mean(np.sum((test-rec)**2,axis=1))),4),
'L0',round(float((z>0).sum(1).mean()),3),
'coseno máximo medio',round(float((true.T@D).max(1).mean()),4))Exercises
Step 1 of 2. What is the stationary point in the region z>0?
def topk_sae_forward(x, W_enc, b_enc, W_dec, b_dec, k):
passdef mean_max_cosine_similarity(D_learned, D_true):
pass