Associative Memory, Attention, and Superposition: A Rigorous Walkthrough
1. Classical Hopfield Networks
1.1 Setup
We have binary neurons with states , and we want to store patterns with . Storage uses the Hebbian rule:
Asynchronous dynamics: at each step pick a neuron and update
1.2 Energy function and Lyapunov argument
Define
Claim. Asynchronous dynamics monotonically decrease .
Proof. Suppose neuron flips: with . Because and is symmetric,
By the update rule, , so and have the same sign (when a flip occurs), giving .
Since is bounded below and changes by discrete amounts, dynamics terminate at a fixed point — a local minimum of .
1.3 Stability of stored patterns and signal-to-noise
Is a fixed point? Compute the local field when the state equals :
The “signal” is deterministic . For i.i.d. uniform patterns, is a sum of i.i.d. terms, so and .
By CLT, . The probability of a single-neuron error at retrieval is
1.4 Capacity
The naive CLT argument gives “small error retrieval” for . The precise capacity requires replica theory:
- Amit–Gutfreund–Sompolinsky (1985). Below , retrieval states exist as stable attractors with fraction of errors. Above , retrieval states disappear in a first-order transition; the system enters a spin-glass phase.
- McEliece–Posner–Rodemich–Venkatesh (1987). For perfect recovery of all patterns w.h.p., one needs .
So classical Hopfield capacity is linear in (with a small constant) for error-tolerant recall and sub-linear () for perfect recall.
2. Modern Hopfield Networks (Ramsauer et al. 2020)
2.1 New energy
Let the state (continuous) and stack patterns as columns of . Ramsauer et al. define
where and .
2.2 Update rule derivation
We derive the update via the concave-convex procedure (CCCP). Write with (convex in ) and (concave, since is convex). The CCCP update solves
Compute: , and
Therefore
This is a fixed-point iteration, but their Theorem 2 shows it converges in one step for well-separated patterns.
2.3 Exponential capacity
Say patterns are -separated: for . Ramsauer et al. (Thm 3) show that the number of patterns that can be retrieved with retrieval error scales as
for patterns on the unit sphere with cosine-similarity separation. The precise statement: for some constants ,
patterns can be stored with exponentially small retrieval error. The proof uses a concentration argument: the softmax with high acts as a sharp selector, and the “noise” from non-target patterns concentrates like a sum of exponentially-small weighted contributions.
The upshot: capacity is exponential in , compared to for classical Hopfield.
2.4 Equivalence to attention
Take attention input (queries) and (keys/values source). Define projections , , , with projecting to . Standard (scaled) attention:
Comparing to the Hopfield update :
- patterns (stored keys),
- query ,
- inverse temperature ,
- readout is from instead of — this is the hetero-associative generalization: retrieve a value given a key.
So a single attention head is literally one step of a hetero-associative modern Hopfield retrieval.
3. Transformer MLPs as Key-Value Memory (Geva et al. 2021)
The FFN block in a transformer:
with , , a pointwise nonlinearity (GELU, ReLU, SwiGLU, etc.).
Let be the -th row of and the -th column of . Then
This is an associative memory: inner-product matching on keys, gated through , reads out a linear combination of values. Unlike attention (which softmax-normalizes across a context), the FFN memory is normalized pointwise and keys are learned weights, not context.
ROME (Meng et al. 2022) — locate-and-edit. Treating as the storage matrix with the key for a specific fact and the desired new value, ROME solves
Derivation. Lagrangian . Stationarity: , so the update is rank-1. Plug into constraint: , giving , hence
To preserve other associations, ROME replaces the plain inner product with a whitened one using over a reference distribution of keys, yielding
This minimizes , i.e., damage weighted by how often a direction is actually used.
4. Toy Models of Superposition (Elhage et al. 2022)
This is the centerpiece. Below I reconstruct the theory in detail.
4.1 Data model
There are features indexed by , each with:
- importance (appears as a weight in the loss),
- sparsity (feature active with probability , zero otherwise).
Data: where and , independent across .
4.2 Model
Tied-weight linear autoencoder with ReLU output:
The columns are the learned feature directions. The loss is weighted MSE:
4.3 Structure of the linear part
Write , the Gram matrix of feature directions: . Then
The first term is the signal; the second is interference from other simultaneously-active features. Because , cannot be identity — some interference is inevitable.
4.4 Dense limit: PCA
If for all (every feature always on), there is no sparsity to exploit. The optimal linear encoder ignoring the ReLU is the rank- truncated SVD: represent the top- eigendirections of , drop the rest. The ReLU provides no gain because interference is always active. You end up with orthogonal features represented, unrepresented.
4.5 Sparse limit: why ReLU enables superposition
Intuition: if at most one feature is active per example, interference is “virtual” — it only exists for outputs of features currently inactive. With the bias , the ReLU clips negative predictions back to zero, matching the zero-valued inactive features at no cost.
More formally, decompose loss contribution of output :
Condition on the support pattern . When and is very sparse, the interference term is typically a sum of a few small values. If their sum plus is , ReLU makes exactly. Sparsity lets the model tune so that interference gets killed by the ReLU in most cases.
When , want for unbiased recovery and conditional on firing — there is a tension, and the solution involves both partial scaling and “hiding” interference under the ReLU threshold.
4.6 Phase transition
As (probability of firing) decreases from toward at fixed , the optimal transitions:
- At : has rank , representing orthogonal features; the remaining columns are zero.
- At : a second-order–like transition where previously-zero columns acquire norm.
- At : all columns are nonzero; they arrange into a geometric packing.
Elhage et al. compute and visualize this phase boundary; it is a function of both and relative importance .
4.7 Geometric structures (the case)
When and features have equal importance, Elhage et al. show that the learned columns form specific regular structures as grows at sufficient sparsity:
- : antipodal pair (digon), .
- : equilateral triangle (Mercedes-star), mutual angles .
- : square (two antipodal pairs at ).
- : regular pentagon at equal angles.
- : regular hexagon / three antipodal pairs (equivalent).
- Higher : mixtures, uniform -gons, and product structures (tegum products) in higher .
These are precisely the solutions to the Tammes problem and equiangular tight-frame problems: pack unit vectors in to minimize max pairwise .
4.8 Feature dimensionality and the “budget” theorem
Elhage et al. define the dimensionality of feature as
Intuition: is the fraction of “one dimension of representation space” that feature consumes.
Key identity.
Proof sketch. Let . Then
Write . Then and has norm equal to the projection of onto . Summing over with the weights gives the trace of the orthogonal projector onto the column space, which equals .
So each feature consumes a “fractional dimension,” and the total consumption is bounded by . Values like (antipodal pair), (triangle vertex), (pentagon vertex) appear in trained models and match regular-polytope packings.
4.9 Capacity: feature count vs. bottleneck dimension
A heuristic bound: superposition can store features in dimensions with interference provided
Quantitatively, if feature sparsity is and interference tolerance is fixed, the count scales roughly as
with tighter constants from Welch’s bound and -net arguments. Comparing against classical Hopfield () and modern Hopfield (), the toy model sits in between: polynomial in at fixed sparsity, scaling inversely with .
4.10 Connection to compressed sensing
If is -sparse and satisfies the Restricted Isometry Property (RIP) of order :
then can be recovered from by minimization (Candès–Tao, Donoho), with measurements. The ReLU autoencoder’s job is to learn such a (when features happen to be sparse), and to implement recovery via a simple feed-forward operation rather than a convex program. The ReLU provides a cheap, data-dependent approximation to recovery.
4.11 Why the connection to Hopfield matters
The modern Hopfield view and the superposition view are two sides of the same capacity story. In both:
- A low-rank/low-dim bottleneck () must represent many items ().
- Items are embedded as non-orthogonal directions: .
- A nonlinearity (softmax in Hopfield, ReLU here) breaks the orthogonality bottleneck by gating / sharpening.
- Retrieval or reconstruction succeeds when only a sparse subset is “active” at a time.
Classical (), superposition (), modern Hopfield () are all points on the same curve, parameterized by how aggressive the nonlinearity is and how sparse the data.
4.12 Implications for interpretability
Polysemanticity — single neurons that respond to multiple unrelated features — is the empirical fingerprint of superposition. If features are stored as non-axis-aligned directions in a low-dim space, individual neurons (axes) correspond to linear combinations of features, not single features. Sparse autoencoders (SAEs, e.g., Cunningham et al. 2023; Bricken et al. 2023) recover the overcomplete dictionary: train , with and on . The columns of approximate the of the toy model — interpretable “features” living in superposition inside the real network.
5. Synthesis
The through-line:
Associative memory is retrieval by content match. Classical Hopfield implements this with Hebbian weights and sign dynamics, with linear-in- capacity. Continuous, softmax-sharpened Hopfield lifts capacity to exponential — and its one-step retrieval is mathematically identical to a transformer attention head. MLPs are also associative memories, but with learned keys and pointwise gating, which is why you can edit facts with rank-1 updates à la ROME.
Superposition is the reason all of this works at scale: features are packed into non-orthogonal directions, more than the ambient dimension would naively permit, and the nonlinearity disambiguates them at read-time under the sparsity assumption. The toy model formalizes the phase diagram (when does superposition occur, in what geometry), bounds the per-feature dimensional budget via , and connects naturally to compressed sensing. SAEs are the inverse operation: a learned approximate dictionary that re-extracts the superposed features from a trained model’s residual stream.
References
- Amit, Gutfreund, Sompolinsky (1985). Storing infinite numbers of patterns in a spin-glass model of neural networks. Phys. Rev. Lett. 55.
- McEliece, Posner, Rodemich, Venkatesh (1987). The capacity of the Hopfield associative memory. IEEE Trans. Inf. Theory 33(4).
- Ramsauer et al. (2020). Hopfield Networks Is All You Need. ICLR 2021. arXiv:2008.02217.
- Geva, Schuster, Berant, Levy (2021). Transformer Feed-Forward Layers Are Key-Value Memories. EMNLP 2021. arXiv:2012.14913.
- Meng, Bau, Andonian, Belinkov (2022). Locating and Editing Factual Associations in GPT (ROME). NeurIPS 2022. arXiv:2202.05262.
- Meng, Sharma, Andonian, Belinkov, Bau (2023). Mass-Editing Memory in a Transformer (MEMIT). ICLR 2023. arXiv:2210.07229.
- Elhage et al. (2022). Toy Models of Superposition. Anthropic. transformer-circuits.pub.
- Cunningham et al. (2023). Sparse Autoencoders Find Highly Interpretable Features in Language Models. arXiv:2309.08600.
- Bricken et al. (2023). Towards Monosemanticity: Decomposing Language Models with Dictionary Learning. Anthropic. transformer-circuits.pub.
- Candès, Tao (2005). Decoding by linear programming. IEEE Trans. Inf. Theory 51(12).