Attention as Associative Memory
Hopfield networks, key–value storage and how much one layer can hold.
Start a Hopfield network from a corrupted copy of a stored pattern and its dynamics settle on the clean one. Nearly forty years after Hopfield's 1982 paper, a continuous generalization of his network turned out to have exactly the update rule of transformer attention. This lesson follows that thread: matrix memories and their crosstalk, the energy and capacity of Hopfield networks, energies with exponential capacity, and the evidence that trained transformers store associations in their weights.
What you’ll learn
- Derive the crosstalk of a linear associative memory with random keys, and show that its capacity grows linearly with the dimension.
- Prove that asynchronous Hopfield dynamics never increase the energy, and derive the capacity scalings and from signal-to-noise arguments and the literature.
- Explain why higher-order and exponential interaction energies raise the capacity to and .
- Derive the modern Hopfield update as a concave–convex step, bound its one-step retrieval error, and identify it with attention.
- Describe how gradient training writes associations into weight matrices, and what scaling laws for associative memories predict.
Key–value memory in a matrix
Reading key returns its value plus a contribution from every other pair, weighted by how much the keys overlap:
With orthonormal keys the crosstalk vanishes, but has at most orthonormal vectors. What happens with more keys, chosen at random?
Write , so . Condition on . Each is symmetric, so ; summing over an orthonormal basis gives , and by symmetry each term has the same mean:
For the keys are independent with mean zero, so and the cross terms of the squared norm vanish:
The bottleneck is not the Hebbian rule. If must hold exactly for the key matrix and generic values, then ; least squares, , achieves exact recall for any linearly independent keys and no more. The delta rule (Widrow–Hoff) is stochastic gradient descent on ; with step and a unit key it sets exactly, overwriting the old association instead of adding to it:
Linear attention is this memory. Causal linear attention keeps a state and reads , up to normalization: one Hebbian write per token into a fixed-size matrix. Schlag, Irie and Schmidhuber (2021) made the connection to the fast-weight programmers of the early 1990s, pointed out the capacity limit this lesson just derived, and replaced the purely additive write with a delta-rule write. Why such fixed states lose at associative recall is the subject of Hybrid Models & the Limits of Fixed-Size Memory. Softmax attention instead keeps every key and value, the KV cache, and reads them with a sharply nonlinear similarity: the rest of this lesson.
A linear memory stores pairs with random unit keys. You double . At the same signal-to-noise ratio, how many pairs can it hold?
- Four times as many, because has four times as many entries
- About twice as many
- The same number, because each write is a rank-one update
- Exponentially many more, because random vectors in high dimension are nearly orthogonal
Show the answer
B. About twice as many
The ratio is , so at fixed reliability scales with . Each value carries numbers, so pairs of numbers fill the entries about as efficiently as before.
Hopfield networks and their capacity
A Hopfield network (Hopfield, 1982) is an auto-associative memory with dynamics. It has binary neurons and stores patterns by the Hebbian rule for , with . Neurons update one at a time, with local field , and the network is scored by the energy
By symmetry, the terms of that contain add up to . Changing to therefore changes the energy by
The update sets . If the neuron flips, , so (take to mean "keep the current state"). A strictly decreasing energy on a finite set cannot cycle.
Capacity. Put the network in a stored pattern, . The local field splits into the pattern's own signal and crosstalk from the other patterns, a sum of about terms that is approximately Gaussian:
Bit flips when the crosstalk opposes the signal by more than about , with probability up to slowly varying factors. For no bit of one pattern to flip, must stay small, which gives the leading-order result of McEliece et al. (1987); for every bit of all patterns at once, must stay small:
Tolerating a small fraction of wrong bits changes the scaling from to . The statistical mechanics of Amit, Gutfreund and Sompolinsky (1985) shows that retrieval states with few errors exist for and disappear abruptly beyond it, as errors avalanche through the dynamics:
A Hopfield network with neurons and Hebbian weights stores random patterns. About how many can it hold as retrieval states, allowing a small fraction of wrong bits?
Show the answer
138 patterns
, close to Hopfield's own simulation estimate of about . Demanding that every bit of a stored pattern be a fixed point cuts this to about . Either way, a million weights hold only about a hundred patterns of a thousand bits: pairwise interactions are a poor use of parameters.
Dense associative memories
Rewrite the Hopfield energy pattern by pattern: up to a constant it is , a sum of a function of each pattern's overlap with the state. Krotov and Hopfield (2016) asked what happens with a sharper :
Neuron compares the energy with , the other neurons held at pattern . The pattern's own overlap is either way except for the term , so its signal is a difference of at the top of its range:
Every other pattern overlaps the state by , a near-Gaussian with variance , and contributes with a random sign. For a Gaussian, , so such terms have standard deviation
The ratio is , so can grow like before the noise wins, matching Krotov and Hopfield's error estimate . With , the signal is of order while a typical competitor, with overlap of order , contributes about . The rare competitors with large overlaps need a large-deviation argument rather than a variance, and Demircigil et al. carry it out: exponentially many patterns fit.
The lesson generalizes: capacity comes from how sharply the readout separates the best match from the rest. A linear readout lets every stored pair leak into every answer; a steep nonlinearity of the overlap suppresses all but the closest patterns. The exponential is the steepest standard choice, and it is the one softmax attention uses.
The update rule is attention
Split into the convex and the concave (the log-sum-exp is convex). The concave–convex procedure (CCCP) sets the gradient of the convex part at the new point equal to minus the gradient of the concave part at the old one:
The energy never increases. Concavity of bounds it by its tangent at ; convexity of , with , bounds by plus the opposite linear term. Adding the two inequalities, the linear terms cancel:
Now read the update as attention. The state is a query, the stored patterns are keys, and ; reading out each key's associated value instead of the key itself (a hetero-associative readout) gives exactly the attention output . One attention layer is one update of a modern Hopfield network whose memories are the tokens in context.
The bound also says when retrieval fails. If is small, because is small or several patterns are nearly as close as the best, the update returns an average: a metastable state over a cluster of similar patterns, and as the global fixed point, the mean of all patterns. Analyzing pretrained BERT models, Ramsauer et al. found heads operating in each of these regimes: heads that average over very many tokens are abundant in the lower layers, while heads that settle on metastable averages over medium-sized subsets predominate in the last layers.
Transformers that store associations
Associative memories in transformers are not only the tokens in context. Gradient descent writes into weight matrices in exactly the outer-product form of the first step: for a linear map , the gradient is , so every step adds a rank-one "error times input" term. In high dimension, nearly orthogonal random embeddings make such sums behave like correlation-matrix memories.
Bietti et al. (2023) made this precise on a synthetic task in which some tokens follow global bigram statistics and others follow bigrams specific to each sequence. A two-layer transformer learns the global bigrams quickly and develops an induction head for the in-context bigrams more slowly, and the authors explain both through weight matrices acting as associative memories, built by gradient steps that add outer products of embeddings. The feed-forward layers are the other candidate store, the subject of Feed-Forward Layers as Memories.
Cabannes, Dohmatob and Bietti (2024) study a memory with random embeddings in , learning a deterministic map from samples whose inputs follow a Zipf law. A memory of dimension can hold roughly the most frequent associations, up to logarithmic factors, so the error is at least the probability of the rest:
With samples, inputs whose expected count is below one are typically never seen. The cutoff is , and the unseen tail has probability
Their result has exactly these two terms, for well-chosen storage schemes and up to constants and logarithmic factors; they also compare the memories that optimization-based training produces. Error falls as a power law in both memory size and data, set by how heavy the tail of rare facts is.
Key takeaways
- A correlation-matrix memory with random keys has crosstalk of squared norm ; linear readouts, linear attention included, store about pairs, and the delta rule overwrites instead of adding.
- Hopfield dynamics descend an energy, per flip; Hebbian storage holds about exactly stable patterns, or about with a few wrong bits.
- Sharper interaction energies separate the best match from the rest: stores about patterns, and exponentially many.
- The modern Hopfield update is a concave–convex step on a log-sum-exp energy and equals attention with : single-pattern retrieval when is large, metastable averages otherwise.
- Gradient steps write outer products into weight matrices, so trained transformers hold associations in their weights; for Zipf-distributed facts the error falls as .
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A Hopfield network with neurons and Hebbian weights stores random patterns. Allowing a small fraction of wrong bits, about how many patterns can it retrieve?
- About , one per neuron
- About , that is
- About , that is
- About , one per weight
Show the answer
C. About , that is
Amit, Gutfreund and Sompolinsky's critical ratio gives about . Beyond it, retrieval states with few errors disappear abruptly.
In the modern Hopfield update , what does the state become as ?
- The stored pattern with the largest overlap
- The average of all stored patterns
- The zero vector
- It stays where it is
Show the answer
B. The average of all stored patterns
At the softmax is uniform, so the update returns , the global fixed point. Large gives single-pattern retrieval; intermediate values give metastable averages over clusters.
A linear memory already maps unit key to an old value. What does the delta-rule write do that the Hebbian write does not?
- It makes exactly, replacing the old value instead of adding the new one to it
- It stores the pair without changing
- It raises the capacity beyond linearly independent keys
- It makes all keys orthogonal
Show the answer
A. It makes exactly, replacing the old value instead of adding the new one to it
. The Hebbian write returns old value plus new value. Neither escapes the rank bound: a linear map recalls at most generic pairs exactly.
Why is the energy of the modern Hopfield network guaranteed not to increase under its update?
- Because the softmax is a contraction
- Because the energy is convex, so any gradient step decreases it
- Because the update is a concave–convex procedure step on a convex quadratic plus a concave
- Because the stored patterns are orthogonal
Show the answer
C. Because the update is a concave–convex procedure step on a convex quadratic plus a concave
Linearizing the concave part at the old state and minimizing the resulting convex upper bound gives ; the bound touches at , so cannot go up.
Further reading
- J. J. Hopfield, "Neural networks and physical systems with emergent collective computational abilities," PNAS 79 (1982).
- D. J. Amit, H. Gutfreund & H. Sompolinsky, "Storing infinite numbers of patterns in a spin-glass model of neural networks," Physical Review Letters 55 (1985).
- D. Krotov & J. J. Hopfield, "Dense associative memory for pattern recognition," NeurIPS (2016).
- H. Ramsauer et al., "Hopfield networks is all you need," ICLR (2021).
- A. Bietti, V. Cabannes, D. Bouchacourt, H. Jégou & L. Bottou, "Birth of a transformer: A memory viewpoint," NeurIPS (2023).