All courses

Sparse autoencoders for interpretable features

Train a sparse autoencoder on model activations: a network that reconstructs them through a much wider hidden layer, with a penalty keeping only a few hidden units active. Its units recover interpretable feature directions. Explain how these features are inspected and used to steer the model.

Builds on: Superposition and polysemantic neurons

▶ Watch this lesson Start the whole course

What the animation says

Undoing superposition

Superposition packs many sparse features into a few dimensions, so one neuron ends up meaning several things. To pull the features back out, train a second, small network on saved activations: a sparse autoencoder. It encodes each activation vector into many more hidden units, say sixteen times the width, then decodes it back. Two pressures: rebuild the input accurately, and let only a few units fire per token. What's the cheapest way to satisfy both?

The machine: encode, decode, loss

Right: the cheapest fit is one hidden unit per real feature. Here's the machine that finds them. Subtract the decoder bias, about the mean activation, multiply by encoder weights, add a bias, apply ReLU: non-negative feature activations. Decoding multiplies by the decoder weights and adds the bias back. Each decoder row is one feature's direction, kept at unit length. Together they form the dictionary. So the rebuild is a weighted sum of directions. The loss adds squared error to alpha times the total activation.

Two exact codes, one input

Let's price it in two dimensions. Three dictionary directions: right, up, and the diagonal between them. The input points to one, one. Alpha is zero point one. Code A uses right and up, one each. The arrows add to exactly one, one. Code B uses only the diagonal, at strength root two, about one point four one. Also exact. Both have zero error. Which pays less penalty?

Cheaper, but not too short

Code B wins. A's activations sum to two, penalty zero point two. B's sum to one point four one, penalty about zero point one four. One unit along the true direction is cheaper than a mix of others. So why not shrink B further? Code C uses the diagonal at only zero point seven one. Its penalty halves. But the rebuilt arrow stops at half, half, short of the input. Tap the code with the lowest total loss: error plus penalty.

Inspect and steer a feature

Trained on millions of real activation rows, only a few percent of units fire per token. Inspect: list the snippets where one feature fires hardest. All about French cooking? Label it that. Steer: add that feature's direction, times a constant c, to the residual stream at every position. Unit length puts c on the activation's scale. Peak near five? c of ten pushes toward cooking; negative c suppresses. A matching behavior change is evidence the label is right.

Undoing superposition with a wider hidden layer

Superposition packs many sparse features into $d$ dimensions, so single neurons are polysemantic. Can we recover the features themselves? Train a second, small network, a **sparse autoencoder**, on saved activations. It **encodes** each activation vector into $m \gg d$ hidden units (say $m = 16d$), then **decodes** it back. Reconstruction forces it to keep the information. A sparsity penalty lets only a few units fire per token. The cheapest way to satisfy both is one unit per real feature.

The sparse autoencoder (SAE)

For an activation row $a\in\mathbb{R}^d$ (e.g. row $t$ of $r^{(\ell)}$): $$f=\mathrm{ReLU}((a-b_{dec})W_{enc}+b_{enc}),\quad \hat a=fW_{dec}+b_{dec}$$ $W_{enc}\in\mathbb{R}^{d\times m}$ and $W_{dec}\in\mathbb{R}^{m\times d}$. The bias $b_{dec}$ sits near the mean activation, so subtracting it centers the input. $f\in\mathbb{R}^m$ holds the feature activations (all $\ge 0$). $$\text{loss}=\|a-\hat a\|^2+\alpha\textstyle\sum_i f_i$$ Row $i$ of $W_{dec}$, called $u_i$ and kept at unit length, is feature $i$'s direction. Together the $u_i$ form the **dictionary**, so $\hat a=\sum_i f_i u_i+b_{dec}$. $\alpha$ trades accuracy for sparsity.

Why the penalty picks one feature

Take $d=2$, $b_{dec}=0$, and dictionary $u_1=(1,0)$, $u_2=(0,1)$, $u_3=(1/\sqrt2,1/\sqrt2)\approx(0.71,0.71)$. Let $a=(1,1)$ and $\alpha=0.1$. Code A: $f=(1,1,0)$ gives $\hat a=(1,1)$. Error is 0, penalty is $0.1\cdot2=0.20$. Code B: $f=(0,0,\sqrt2)$ gives $\hat a=\sqrt2\cdot(1/\sqrt2,1/\sqrt2)=(1,1)$. Error is 0, penalty is $0.1\sqrt2\approx0.141$. B wins. A single unit aligned with the true direction is cheaper than a mix of others.

Inspecting and steering a feature

**Inspect:** run millions of tokens through the model and the SAE. For feature $i$, list the text snippets where $f_i$ is largest. If they all concern, say, French cooking, label it that way. **Steer:** at that layer, add $c\,u_i$ to the residual stream at every position: $r^{(\ell)}_t\leftarrow r^{(\ell)}_t+c\,u_i$. Because $u_i$ has unit length, $c$ is on the same scale as $f_i$. If $f_i$ normally peaks near 5, then $c=10$ is twice its strongest natural value and pushes the text toward cooking. A negative $c$ suppresses it. A matching behavior change is evidence that the label is right.

SAE forward pass and loss in numpy

Here is one forward pass on stand-in activations. They are random numbers, so there are no real features to find. To train, backprop this loss, update the weights, and renormalize the rows of $W_{dec}$ to unit length. Real runs use many millions of saved activation rows from one layer. Training drives the fraction of active units from about 50% at random init down to a few percent or less.
import numpy as np
rng = np.random.default_rng(0)
d, m, alpha = 64, 512, 1e-3                 # m = 8d hidden units
acts = rng.standard_normal((1024, d))       # stand-in activations [n_tok, d]
W_enc = rng.standard_normal((d, m)) / np.sqrt(d)
b_enc = np.zeros(m)
W_dec = W_enc.T / np.linalg.norm(W_enc.T, axis=1, keepdims=True)  # unit rows u_i
b_dec = acts.mean(0)
F = np.maximum(0, (acts - b_dec) @ W_enc + b_enc)  # feature acts [n_tok, m]
acts_hat = F @ W_dec + b_dec
loss = ((acts - acts_hat)**2).sum(1).mean() + alpha * F.sum(1).mean()
print(loss, (F > 0).mean())                 # loss, fraction active

What to remember

An SAE rewrites each activation as a sparse sum $\hat a\approx\sum_i f_i u_i+b_{dec}$ over a learned dictionary much wider than $d$. The decoder rows $u_i$ are candidate features. You read them from their top-activating examples and test them by adding $c\,u_i$ to the residual stream and watching behavior change.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.