Module contents
Lesson 21 of 39Core 120 min

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 x\vb x using few coefficients. A common architecture centers the input with bd\vb b_d, encodes it, and decodes it:

z=ReLU⁡(We(x−bd)+be),x^=Wdz+bd.\vb z=\operatorname{ReLU}(W_e(\vb x-\vb b_d)+\vb b_e),\qquad \hat{\vb x}=W_d\vb z+\vb b_d.

The loss combines reconstruction and sparsity, for example ∥x−x^∥22+λ∥z∥1\norm{\vb x-\hat{\vb x}}_2^2+\lambda\norm{\vb z}_1. 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 cc and dividing its coefficient by cc preserves the reconstruction while artificially reducing the L1 penalty.

Magnitude matters too

In one dimension, minimizing (x−z)2+λ∣z∣(x-z)^2+\lambda|z| gives z∗=sign⁡(x)max⁡(∣x∣−λ/2,0)z^*=\operatorname{sign}(x)\max(|x|-\lambda/2,0). Even large signals shrink by λ/2\lambda/2. 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.

InteractiveThe price of L1
  • L1 soft threshold
  • Hard threshold
Minimizes (x − z)² + λ|z|. The soft solution removes small signals and shrinks large ones by λ/2.
The hard threshold preserves magnitude when it exceeds λ/2; it illustrates a discontinuous jump but does not minimize this L1 objective or equal multidimensional TopK.
2.0
1.0
L1 solution1.50
Illustrative hard threshold2.00
L1 objective at its solution1.75
Change the input and penalty. Soft thresholding is the exact solution of the stated scalar problem; hard thresholding compares their shapes.

Activation variants change the tradeoff. TopK keeps the kk 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. L0L_0 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 LoL_o, reference ablation LbL_b, and inserted SAE LsL_s, a common recovered fraction is

R=Lb−LsLb−Lo.R=\frac{L_b-L_s}{L_b-L_o}.

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 L0L_0.

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 k=32k=32 recovers 0.812 of the loss with L0=32L_0=32, but 714 of its 1024 latents do not activate in this sample.

InteractiveSparsity and fidelity in GPT-2
0600Mean L010

Recovered CE on vertical axis. L1 · TopK · JumpReLU

First four coordinates of a held-out activation, divided by the training scale:

Original: 0.06 · −0.16 · 0.04 · 0.01

Reconstruction: −0.13 · −0.22 · 0.07 · −0.10

Mean L0544.0
Recovered CE0.962
Dead latents on test54 / 1024
FVU0.009
L1, TopK, and JumpReLU were trained on the same activations; cross-entropy is measured after inserting the reconstruction into the model. Two points per family do not establish universal superiority.

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 λ=0.1\lambda=0.1, 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.

InteractiveThree-latent dashboard
Activations by quantile

low: 15 in · 0.00

median: not including · 0.00

maximum: Attempt · 22.28

Histogram over 1503 positions022.3
Largest logit changes

anza 0.73

aires 0.72

oux 0.65

Smallest logit changes

suspended −0.50

� −0.49

エル −0.49

Automatic rule: ‘the token is The’. Evaluated on 9 positive predictions; high precision with low recall can miss most activations.
Frequency in selection18.6 %
Rule precision on test22.2 %
Rule recall2.0 %
Examples, histograms, and logit changes come from the lab run; the automatic rule and its evaluation do not prove that a feature is monosemantic.

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.

InteractiveCandidates across dictionaries
1536: latent 1314 · active 72 times

Candidate columns were chosen by decoder similarity; frequencies describe a text sample, not validation of meaning.

Dictionary size
Observed positions827
Any candidate active, parent inactive27 / 67
Real pretrained weights and measured frequencies. Links denote cosine neighbors, not a proven genealogy; sizes are those available in this public family.

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 L0=38.82L_0=38.82 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.

[ ]Load a pretrained dictionary with SAELensLocal GPU
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()))
This cell needs the local lab (PyTorch with your GPU). Start it with 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, L0L_0, 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.

[ ]ReLU SAE on synthetic dataBrowser
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.

[ ]Vary size and penaltyBrowser
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

Proof
Prove: Derive the minimizer of (x−z)² + λ|z| for λ≥0.
0
Consider the cases where z is positive, negative, or zero.

Step 1 of 2. What is the stationary point in the region z>0?

Numeric
The loss is 3.2 in the original model, 7.0 under ablation, and 3.5 with the SAE inserted. Calculate the recovered fraction.
Quiz
A latent never activates on a held-out evaluation set. What can be concluded?
Code
Implement topk_sae_forward(x, W_enc, b_enc, W_dec, b_dec, k). x is B×d, W_enc is d×m, and W_dec is m×d. Apply ReLU and retain up to the k largest values per row. Return the reconstruction and codes; k may be zero.
def topk_sae_forward(x, W_enc, b_enc, W_dec, b_dec, k):
  pass
Shift+Enter to run
Code
Implement mean_max_cosine_similarity(D_learned, D_true). Both matrices have vectors as columns. Normalize them, find the maximum cosine similarity for each true column over the learned columns, and return the mean; use zero similarity for columns with zero norm.
def mean_max_cosine_similarity(D_learned, D_true):
  pass
Shift+Enter to run
Key idea
An SAE proposes a sparse dictionary; its quality requires evaluating reconstruction, model behavior, and interpretive evidence on held-out data.