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 orthogonal features within dimensions so each coordinate mixes several, without representing more than features.
The toy model of Elhage and colleagues compresses using and reconstructs with tied weights and a bias:
Each is zero with probability and, when active, is sampled uniformly from [0,1]. Importance 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 and , with . If , the second feature is ignored and loss is . If , error occurs only when both are active: loss is , since for independent uniforms. Equality occurs at . 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.
Now train the five columns directly. Each click computes 100 stochastic descent steps with 96 examples per step, without interpolating prerecorded weights. Changing 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.
The figure weights come from independent training runs with the same seed, not a training animation. At , 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 , the model’s feature dimensionality is
Here . Define for a zero column. A column orthogonal to all others has ; two antipodal unit columns share one dimension and each has . The sum of dimensionalities approaches 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 , a concentration bound of the form , with a universal positive constant, and a union bound over pairs show that sets of exponential size in exist with bounded interference. This is an existence bound, not a promise that every collection of that size satisfies the maximum limit.
The connection to compressed sensing is an analogy with recovering sparse signals from few measurements, not a recovery theorem for every learned . 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 case in the figure.
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.
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)
h=x@w.transpose(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+(dz@w.transpose(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.
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)
h=x@w.transpose(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+(dz@w.transpose(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((x@w.transpose(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))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.
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((x@W.T)@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])npm run lab and open the connection link.Exercises
Step 1 of 2. How do you bound the probability that any pair among n vectors fails?
def feature_dimensions(W):
passdef train_toy_model(n_features, d, sparsity, importance):
pass