Module contents
Lesson 20 of 39Core 100 min

Superposition and polysemanticity

Study privileged bases, polysemanticity, and superposition through the Elhage et al. toy model. Explore phase diagrams, feature geometry, and interference as motivation for sparse dictionaries.

After this lesson you can

  • Explain what makes a basis privileged and why the residual stream is not.
  • Train the toy superposition model and reproduce its phase diagram.
  • Calculate feature dimensionality and recognize geometric configurations.
  • Bound how many nearly orthogonal directions fit in d dimensions and relate this to sparsity.
  • Find polysemantic neurons in a real model using maximum-activation examples.

Before you start

Directions and coordinates

A neuron is a coordinate chosen by the architecture. A feature is a property or direction proposed to explain a representation; equating the two without checking can conflate concepts. A privileged basis arises when an operation acts coordinatewise, as ReLU does in the hidden layer of an MLP. In a linear space between transformations, an invertible change of basis accompanied by inverse changes to adjacent matrices can preserve the function. This freedom depends on the architecture and its operations; it does not mean any rotation preserves a coordinatewise ReLU.

Polysemanticity describes a neuron that responds to several apparently distinct patterns. It can arise from superposition, but a list of high-activation examples may also mix contexts, correlations, or an unrecognized shared property. Olah and colleagues document InceptionV1 unit 4e:55, which responds to cat faces and legs and car fronts; they compare examples with feature visualization. This is a published vision example, separate from the GPT-2 result studied below. Interpretation requires testing hypotheses, not merely assigning labels.

More features than dimensions

The superposition hypothesis proposes that multiple sparse features share dimensions through different directions. If they rarely activate together, capacity savings may outweigh interference. A distributed representation alone does not imply superposition: one can rotate dd orthogonal features within dd dimensions so each coordinate mixes several, without representing more than dd features.

The toy model of Elhage and colleagues compresses x∈Rn\vb x\in\R^n using W∈Rd×nW\in\R^{d\times n} and reconstructs with tied weights and a bias:

x^=ReLU⁡(W⊤Wx+b),L=E ⁣[∑iIi(x^i−xi)2].\hat{\vb x}=\operatorname{ReLU}(W\T W\vb x+\vb b),\qquad \mathcal L=\mathbb E\!\left[\sum_i I_i(\hat x_i-x_i)^2\right].

Each xix_i is zero with probability SS and, when active, is sampled uniformly from [0,1]. Importance IiI_i weights errors; a negative bias can filter small interference at the cost of losing weak signals. This model radically simplifies a real network and does not determine its geometry.

For two features in one dimension we can compare two unbiased candidates. Write p=1−Sp=1-S and r=I2/I1r=I_2/I_1, with I1=1I_1=1. If W=(1,0)W=(1,0), the second feature is ignored and loss is rp/3rp/3. If W=(1,−1)W=(1,-1), error occurs only when both are active: loss is p2(1+r)/6p^2(1+r)/6, since E[min⁡(U,V)2]=1/6E[\min(U,V)^2]=1/6 for independent uniforms. Equality occurs at p=2r/(1+r)p=2r/(1+r). This curve compares only those two candidates: allowing biases, different weights, and same-sign solutions can change the optimal frontier. Indeed, the analytical replication discussed in the source also finds a phase of confused features.

InteractiveMeasured phase diagram

Rows: zero probability S. Columns: relative importance I₂/I₁.

S / I₂0.10.20.40.60.81
0
0.25
0.5
0.7
0.8
0.9
0.95

± antipodal; 1 one small column; ++ same sign. Classification uses |Wᵢ| < 0.2 and does not certify the optimum.

Learned W1.02, −0.99
Selection loss0.0035
Candidates: dedicated / antipodal0.0333 / 0.0033
Each cell shows the best of four Adam restarts, selected by loss on 10 000 fresh samples. Column classification is indicative; the two analytical losses use the unbiased candidates described in the text.

Now train the five columns directly. Each click computes 100 stochastic descent steps with 96 examples per step, without interpolating prerecorded weights. Changing SS continues from the current state: reset to compare from the same initialization. The result depends on order, optimizer, and seed; finding the pentagon is not guaranteed.

InteractiveTrain five features
12345
D1: 0.48D2: 0.50D3: 0.39D4: 0.32D5: 0.30
0.90
Steps0
Sum of dimensionalities2.00
Segments show the current columns; readouts show their dimensionalities. The experiment uses SGD and tied weights, with reproducible seeds per block.
InteractiveFive features in two dimensions
12345
Feature 1
0.40
Feature 2
0.41
Feature 3
0.39
Feature 4
0.39
Feature 5
0.40
Zero probability
Loss on 10,000 new examples0.0259
Zero-output baseline0.1619
Weights obtained with NumPy, seed 20, and 1800 updates per sparsity level. Bars show each column’s dimensionality; evaluation uses 10 000 new examples.

The figure weights come from independent training runs with the same seed, not a training animation. At S=0,9S=0,9, the five columns approximately form a pentagon and each dimensionality is around 0.4; this is an observation from this run. Loss is compared with returning zero, rather than a certified global optimum.

Dimensionality and interference

For Wi≠0W_i\ne0, the model’s feature dimensionality is

Di=∥Wi∥22∑j(W^i⊤Wj)2=∥Wi∥24∑j(Wi⊤Wj)2.D_i=\frac{\norm{W_i}_2^2}{\sum_j(\widehat W_i\T W_j)^2} =\frac{\norm{W_i}_2^4}{\sum_j(W_i\T W_j)^2}.

Here W^i=Wi/∥Wi∥2\widehat W_i=W_i/\norm{W_i}_2. Define Di=0D_i=0 for a zero column. A column orthogonal to all others has Di=1D_i=1; two antipodal unit columns share one dimension and each has Di=1/2D_i=1/2. The sum of dimensionalities approaches dd in well-packed configurations, but this is not an identity for every matrix. The paper describes configurations such as pentagons and tetrahedra under specific conditions; no geometry is mandatory in every training run.

In high dimensions, pairs of random directions typically have a small inner product. For uniform unit vectors and 0<ε<10<\varepsilon<1, a concentration bound of the form P(∣u⊤v∣>ε)≤2e−cdε2P(|u\T v|>\varepsilon)\le 2e^{-c d\varepsilon^2}, with a universal positive constant, and a union bound over pairs show that sets of exponential size in dε2d\varepsilon^2 exist with bounded interference. This is an existence bound, not a promise that every collection of that size satisfies the maximum limit.

InteractiveNearly orthogonal directions
−101
40
64
0.30
Maximum |cosine|0.375
Pairs outside ε18 / 780
Typical scale 1/√d0.125
Samples are normalized Gaussians with a fixed seed. The histogram includes all pairs; the maximum and violations show the cost of requiring a simultaneous bound.

The connection to compressed sensing is an analogy with recovering sparse signals from few measurements, not a recovery theorem for every learned WW. Interference also suggests a hypothesis about adversarial vulnerability: perturbing one direction may affect others, but the toy model does not prove that this causes an attack on a real model.

Lab: training and measurement

This training uses manual gradients and Adam on five features of equal importance. The evaluation set is generated after training using the same generator: samples are new, although the distribution is unchanged. Compare with zero output and repeat with other seeds before discussing stability. The code reproduces the S=0,9S=0,9 case in the figure.

[ ]Learn five directions with NumPyBrowser
import numpy as np
rng = np.random.default_rng(20)
n, d, S = 5, 2, 0.9
W = rng.normal(0, .2, (d, n)); b = np.zeros(n)
mw = np.zeros_like(W); vw = np.zeros_like(W)
mb = np.zeros_like(b); vb = np.zeros_like(b)
for t in range(1, 1801):
    x = rng.random((512,n)) * (rng.random((512,n)) > S)
    h = x @ W.T; z = h @ W + b; y = np.maximum(z, 0)
    dz = 2 * (y-x) * (z > 0) / len(x)
    gw = h.T @ dz + (dz @ W.T).T @ x
    gb = dz.sum(axis=0)
    mw = .9*mw + .1*gw; vw = .999*vw + .001*gw**2
    mb = .9*mb + .1*gb; vb = .999*vb + .001*gb**2
    W -= .01 * (mw/(1-.9**t)) / (np.sqrt(vw/(1-.999**t))+1e-8)
    b -= .01 * (mb/(1-.9**t)) / (np.sqrt(vb/(1-.999**t))+1e-8)
x = rng.random((10000,n)) * (rng.random((10000,n)) > S)
y = np.maximum((x @ W.T) @ W + b, 0)
gram = W.T @ W; norm = np.linalg.norm(W, axis=0)
dim = np.divide(norm**4, (gram**2).sum(axis=1), out=np.zeros(n), where=norm>1e-12)
print('pérdida', round(np.mean(np.sum((y-x)**2,axis=1)), 6))
print('salida cero', round(np.mean(np.sum(x*x,axis=1)), 6))
print('dimensionalidades', np.round(dim, 3), 'suma', round(dim.sum(), 3))

This short browser sweep changes both sparsity and importance; it uses one restart per cell and can therefore fall into local minima. The larger grid underlying the figure uses the local protocol below.

[ ]Sweep sparsity and importance in NumPyBrowser
import numpy as np
g=np.random.default_rng(2042)
grid=[(s,r) for s in (0.,.7,.95) for r in (.2,.6,1.)]
s=np.array([a for a,_ in grid])[:,None,None]
importance=np.array([[1.,b] for _,b in grid])[:,None,:]
w=g.normal(0,.3,(len(grid),1,2));bias=np.zeros((len(grid),1,2))
mw=np.zeros_like(w);vw=np.zeros_like(w);mb=np.zeros_like(bias);vb=np.zeros_like(bias)
for t in range(1,801):
    x=g.random((len(grid),128,2))*(g.random((len(grid),128,2))>s)
    [email protected](0,2,1);pre=h@w+bias;y=np.maximum(pre,0)
    dz=2*importance*(y-x)*(pre>0)/128
    gw=h.transpose(0,2,1)@dz+([email protected](0,2,1)).transpose(0,2,1)@x
    gb=dz.sum(1,keepdims=True)
    mw=.9*mw+.1*gw;vw=.999*vw+.001*gw**2
    mb=.9*mb+.1*gb;vb=.999*vb+.001*gb**2
    w-=.01*(mw/(1-.9**t))/(np.sqrt(vw/(1-.999**t))+1e-8)
    bias-=.01*(mb/(1-.9**t))/(np.sqrt(vb/(1-.999**t))+1e-8)
for i,(s0,r0) in enumerate(grid):
    gram=w[i].T@w[i];den=(gram**2).sum(1)
    dims=np.divide(np.diag(gram)**2,den,out=np.zeros(2),where=den>0)
    print('S',s0,'importancia',r0,'W',np.round(w[i,0],2),'D',np.round(dims,2))

To reproduce the entire grid, the following computation groups the 168 training runs and selects among four restarts using a fresh selection set. It runs locally because the full sweep is heavier than a browser cell. The selection sample chooses the restart and is not an independent estimate after selection.

[ ]Sparsity and importance sweepLocal GPU
import numpy as np
rng = np.random.default_rng(2041)
spar = np.array([0, .25, .5, .7, .8, .9, .95])
ratio = np.array([.1, .2, .4, .6, .8, 1.])
grid = [(s, r, seed) for s in spar for r in ratio for seed in range(4)]
s = np.array([g[0] for g in grid])[:,None,None]
imp = np.array([[1.,g[1]] for g in grid])[:,None,:]
w = rng.normal(0,.3,(len(grid),1,2)); b=np.zeros((len(grid),1,2))
mw=np.zeros_like(w); vw=np.zeros_like(w); mb=np.zeros_like(b); vb=np.zeros_like(b)
for t in range(1,2001):
    x=rng.random((len(grid),256,2))*(rng.random((len(grid),256,2))>s)
    [email protected](0,2,1); pre=h@w+b; y=np.maximum(pre,0)
    dz=2*imp*(y-x)*(pre>0)/256
    gw=h.transpose(0,2,1)@dz+([email protected](0,2,1)).transpose(0,2,1)@x
    gb=dz.sum(axis=1,keepdims=True)
    mw=.9*mw+.1*gw; vw=.999*vw+.001*gw**2
    mb=.9*mb+.1*gb; vb=.999*vb+.001*gb**2
    w-=.01*(mw/(1-.9**t))/(np.sqrt(vw/(1-.999**t))+1e-8)
    b-=.01*(mb/(1-.9**t))/(np.sqrt(vb/(1-.999**t))+1e-8)
x=rng.random((len(grid),10000,2))*(rng.random((len(grid),10000,2))>s)
y=np.maximum(([email protected](0,2,1))@w+b,0)
loss=(imp*(y-x)**2).sum(axis=2).mean(axis=1)
for i in range(0,len(grid),4):
    best=i+int(np.argmin(loss[i:i+4]))
    print('S, importancia',grid[best][:2], 'W',np.round(w[best,0],3),
          'sesgo',np.round(b[best,0],3),'pérdida selección',round(float(loss[best]),5))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Scaling up and searching in a real MLP

The next experiment uses 128 features and 32 dimensions. It compares independent inputs with pairs sharing an activation mask while keeping the marginal distribution fixed. Measurements use new data and do not assert that both distributions have the same solution. Next, a neuron is sought in GPT-2 small layer 5 GELU output across 64 template-generated sentences; the neuron whose four maxima cover the most distinct topics is selected. This is an exploratory search on a small sample, not a demonstration of polysemanticity: examples may share the same template. In the fixed run, unit 1888 responds to garden, cat, train, and painting, all in “The … was mentioned in the newspaper”. Shared context is an explicit alternative hypothesis. Expand the corpus, hold out examples, and test interventions before assigning meanings.

[ ]Hundreds of features and GPT-2 maximaLocal GPU
import numpy as np, torch
from transformers import AutoTokenizer, AutoModelForCausalLM
torch.set_num_threads(2)
torch.manual_seed(20)
n, d, S = 128, 32, .9
def sample(batch, correlated):
    mask = torch.rand(batch, n//2 if correlated else n) > S
    if correlated:
        mask = mask.repeat_interleave(2, dim=1)
    return torch.rand(batch, n) * mask
for correlated in (False, True):
    W = torch.nn.Parameter(torch.randn(d,n)*.1)
    b = torch.nn.Parameter(torch.zeros(n))
    opt = torch.optim.Adam([W,b],lr=.01)
    for step in range(500):
        x=sample(256,correlated)
        y=torch.relu((x @ W.T) @ W+b)
        loss=((y-x)**2).sum(dim=1).mean()
        opt.zero_grad(); loss.backward(); opt.step()
    with torch.no_grad():
        x=sample(4096,correlated)
        loss=((torch.relu(([email protected])@W+b)-x)**2).sum(dim=1).mean()
        print('correlacionadas',correlated,'pérdida test',round(float(loss),4),
              'referencia cero',round(float((x*x).sum(dim=1).mean()),4))

name='openai-community/gpt2'
rev='607a30d783dfa663caf39e06633721c8d4cfcd7e'
tok=AutoTokenizer.from_pretrained(name,revision=rev)
model=AutoModelForCausalLM.from_pretrained(name,revision=rev,
                                           attn_implementation='eager').eval()
topics=['cat','dog','car','train','poem','music','garden','river',
        'planet','computer','doctor','bread','football','painting','ocean','book']
templates=['The {} was mentioned in the newspaper.',
           'Yesterday I saw a {} near the station.',
           'A short story about a {} appeared today.',
           'She wrote a detailed note about the {}.']
texts=[t.format(w) for t in templates for w in topics]
captures=[]
handle=model.transformer.h[5].mlp.act.register_forward_hook(
    lambda mod,inp,out: captures.append(out.detach()))
records=[]
with torch.inference_mode():
    for text in texts:
        ids=tok(text,return_tensors='pt').input_ids
        captures.clear(); model(ids,use_cache=False)
        vals,positions=captures[0][0].max(dim=0)
        records.append((vals,positions,ids[0]))
handle.remove()
stack=torch.stack([r[0] for r in records])
rankings=stack.topk(4,dim=0).indices
distinct=[len({i % len(topics) for i in rankings[:,j].tolist()})
          for j in range(stack.shape[1])]
unit=max(range(len(distinct)),key=lambda j:(distinct[j],float(stack[:,j].max())))
print('capa 5, neurona',unit,'temas distintos',distinct[unit])
for i in rankings[:,unit].tolist():
    pos=int(records[i][1][unit]); ids=records[i][2]
    print(round(float(stack[i,unit]),4),repr(tok.decode([int(ids[pos])])),texts[i])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Numeric
W has columns (1,0), (−1,0), (0,1). What is the dimensionality of the first feature?
Quiz
Which operation privileges a coordinate basis?
Proof
Prove: Use concentration and a union bound to justify the existence of many nearly orthogonal directions.
0
Suppose P(|u·v| > ε) ≤ 2 exp(−c d ε²) for two independent random unit vectors.

Step 1 of 2. How do you bound the probability that any pair among n vectors fails?

Code
Implement feature_dimensions(W): W is a d×n matrix. Return the n dimensionalities; a zero column has zero dimensionality.
def feature_dimensions(W):
  pass
Shift+Enter to run
Code
Implement train_toy_model(n_features, d, sparsity, importance). Train the tied-weight model with SGD, seed 20, 400 steps, and batch size 128; return W, b, and loss on 2000 fresh examples. Check the dimensions of importance.
def train_toy_model(n_features, d, sparsity, importance):
  pass
Shift+Enter to run
Key idea
Superposition lets sparse features share dimensions, but geometry and interpretation must be measured for each model.