Simple Algorithm
Deep Learning · Emergence · 28 min

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 W=∑iviki⊤W=\sum_i\mathbf v_i\mathbf k_i^\top 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 N/(2ln⁡N)N/(2\ln N) and ≈0.138N\approx0.138N from signal-to-noise arguments and the literature.
  • Explain why higher-order and exponential interaction energies raise the capacity to Nn−1N^{n-1} and eΘ(N)e^{\Theta(N)}.
  • Derive the modern Hopfield update ξ←Xsoftmax⁡(βX⊤ξ)\boldsymbol\xi\leftarrow X\softmax(\beta X^\top\boldsymbol\xi) 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 jj returns its value plus a contribution from every other pair, weighted by how much the keys overlap:

Wkj=vj ∥kj∥2+∑i≠j(ki⋅kj) vi.W\mathbf k_j=\mathbf v_j\,\norm{\mathbf k_j}^2+\sum_{i\ne j}(\mathbf k_i\cdot\mathbf k_j)\,\mathbf v_i.

With orthonormal keys the crosstalk vanishes, but Rd\R^d has at most dd orthonormal vectors. What happens with more keys, chosen at random?

DerivationProof
  1. E[ci∣kj]=0,E[ci2∣kj]=1d\E[c_i\mid\mathbf k_j]=0,\qquad\E[c_i^2\mid\mathbf k_j]=\frac1d

    Write ci=ki⋅kjc_i=\mathbf k_i\cdot\mathbf k_j, so nj=∑i≠jcivi\mathbf n_j=\sum_{i\ne j}c_i\mathbf v_i. Condition on kj\mathbf k_j. Each ki\mathbf k_i is symmetric, so E[ci]=0\E[c_i]=0; summing (ki⋅em)2(\mathbf k_i\cdot\mathbf e_m)^2 over an orthonormal basis gives 11, and by symmetry each term has the same mean:

  2. E∥nj∥2=∑i≠j∑l≠jE[cicl] vi⋅vl=∑i≠jE[ci2] ∥vi∥2=N−1d\E\norm{\mathbf n_j}^2=\sum_{i\ne j}\sum_{l\ne j}\E[c_ic_l]\,\mathbf v_i\cdot\mathbf v_l=\sum_{i\ne j}\E[c_i^2]\,\norm{\mathbf v_i}^2=\frac{N-1}{d}

    For i≠li\ne l the keys are independent with mean zero, so E[cicl∣kj]=0\E[c_ic_l\mid\mathbf k_j]=0 and the cross terms of the squared norm vanish:

  3. W←W+(v−Wk) k⊤⟹Wnewk=Wk+(v−Wk)∥k∥2=vW\leftarrow W+(\mathbf v-W\mathbf k)\,\mathbf k^\top\quad\Longrightarrow\quad W_{\text{new}}\mathbf k=W\mathbf k+(\mathbf v-W\mathbf k)\norm{\mathbf k}^2=\mathbf v

    The bottleneck is not the Hebbian rule. If WK=VWK=V must hold exactly for the key matrix K∈Rd×NK\in\R^{d\times N} and generic values, then rank⁡V≤rank⁡K≤d\rank V\le\rank K\le d; least squares, W=VK+W=VK^+, achieves exact recall for any N≤dN\le d linearly independent keys and no more. The delta rule (Widrow–Hoff) is stochastic gradient descent on 12∥v−Wk∥2\tfrac12\norm{\mathbf v-W\mathbf k}^2; with step 11 and a unit key it sets Wk=vW\mathbf k=\mathbf v exactly, overwriting the old association instead of adding to it:

Linear attention is this memory. Causal linear attention keeps a state St=St−1+vt ϕ(kt)⊤S_t=S_{t-1}+\mathbf v_t\,\phi(\mathbf k_t)^\top and reads St ϕ(qt)S_t\,\phi(\mathbf q_t), 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.

Check your understanding

A linear memory W∈Rd×dW\in\R^{d\times d} stores pairs with random unit keys. You double dd. At the same signal-to-noise ratio, how many pairs can it hold?

  1. Four times as many, because WW has four times as many entries
  2. About twice as many
  3. The same number, because each write is a rank-one update
  4. Exponentially many more, because random vectors in high dimension are nearly orthogonal
Show the answer

B. About twice as many

The ratio is d/(N−1)d/(N-1), so at fixed reliability NN scales with dd. Each value carries dd numbers, so 2d2d pairs of 2d2d numbers fill the 4d24d^2 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 NN binary neurons s∈{−1,+1}N\mathbf s\in\{-1,+1\}^N and stores PP patterns ξμ\boldsymbol\xi^\mu by the Hebbian rule Wij=1N∑μξiμξjμW_{ij}=\tfrac1N\sum_{\mu}\xi^\mu_i\xi^\mu_j for i≠ji\ne j, with Wii=0W_{ii}=0. Neurons update one at a time, si←sign⁡(hi)s_i\leftarrow\sign(h_i) with local field hi=∑jWijsjh_i=\sum_jW_{ij}s_j, and the network is scored by the energy

E(s)=−12∑i≠jWij sisj.E(\mathbf s)=-\tfrac12\sum_{i\ne j}W_{ij}\,s_is_j.
DerivationProof, then capacity
  1. ΔE=−(si′−si) hi\Delta E=-(s_i'-s_i)\,h_i

    By symmetry, the terms of EE that contain sis_i add up to −sihi-s_ih_i. Changing sis_i to si′s_i' therefore changes the energy by

  2. ΔE=−2∣hi∣<0for every flip\Delta E=-2\abs{h_i}<0\quad\text{for every flip}

    The update sets si′=sign⁡(hi)s_i'=\sign(h_i). If the neuron flips, si′−si=2sign⁡(hi)s_i'-s_i=2\sign(h_i), so ΔE=−2∣hi∣<0\Delta E=-2\abs{h_i}<0 (take sign⁡(0)\sign(0) to mean "keep the current state"). A strictly decreasing energy on a finite set cannot cycle.

  3. hi=ξiν N−1N+Ci,Ci≈N ⁣(0, PN)h_i=\xi_i^\nu\,\frac{N-1}N+C_i,\qquad C_i\approx\mathcal N\!\Big(0,\ \frac PN\Big)

    Capacity. Put the network in a stored pattern, s=ξν\mathbf s=\boldsymbol\xi^\nu. The local field splits into the pattern's own signal and crosstalk from the other P−1P-1 patterns, a sum of about PNPN terms ±1/N\pm1/N that is approximately Gaussian:

  4. P≈N2ln⁡N(each pattern stable),P≈N4ln⁡N(all patterns exactly)P\approx\frac{N}{2\ln N}\quad\text{(each pattern stable)},\qquad P\approx\frac{N}{4\ln N}\quad\text{(all patterns exactly)}

    Bit ii flips when the crosstalk opposes the signal by more than about 11, with probability Φ(−N/P)≈e−N/2P\Phi(-\sqrt{N/P})\approx e^{-N/2P} up to slowly varying factors. For no bit of one pattern to flip, Ne−N/2PNe^{-N/2P} must stay small, which gives the leading-order result of McEliece et al. (1987); for every bit of all PP patterns at once, NP e−N/2PNP\,e^{-N/2P} must stay small:

  5. αc=Pmax⁡N≈0.138\alpha_c=\frac{P_{\max}}{N}\approx0.138

    Tolerating a small fraction of wrong bits changes the scaling from N/ln⁡NN/\ln N to NN. The statistical mechanics of Amit, Gutfreund and Sompolinsky (1985) shows that retrieval states with few errors exist for P<αcNP<\alpha_cN and disappear abruptly beyond it, as errors avalanche through the dynamics:

Predict before you look

A Hopfield network with N=1000N=1000 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

0.138×1000≈1380.138\times1000\approx138, close to Hopfield's own simulation estimate of about 0.15N0.15N. Demanding that every bit of a stored pattern be a fixed point cuts this to about N/(2ln⁡N)≈72N/(2\ln N)\approx72. 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 −12N∑μ(ξμ⋅s)2-\tfrac1{2N}\sum_\mu(\boldsymbol\xi^\mu\cdot\mathbf s)^2, a sum of a function FF of each pattern's overlap with the state. Krotov and Hopfield (2016) asked what happens with a sharper FF:

E(s)=−∑μ=1PF(ξμ⋅s),F(x)=xn ⇒ Pmax⁡=αn N n−1,F(x)=ex ⇒ Pmax⁡=eΘ(N)E(\mathbf s)=-\sum_{\mu=1}^{P}F\big(\boldsymbol\xi^\mu\cdot\mathbf s\big),\qquad F(x)=x^n\ \Rightarrow\ P_{\max}=\alpha_n\,N^{\,n-1},\qquad F(x)=e^{x}\ \Rightarrow\ P_{\max}=e^{\Theta(N)}
n=2n=2 recovers the classical network. The polynomial result is from Krotov and Hopfield (2016), with αn\alpha_n a constant set by the tolerated error; Demircigil et al. (2017) proved the polynomial claim and showed that the exponential interaction stores exponentially many patterns in NN, with basins of attraction nearly as large as the classical ones.
DerivationWhy sharper interactions store more
  1. signal≈F(N)−F(N−2)≈2F′(N)=2n N n−1\text{signal}\approx F(N)-F(N-2)\approx2F'(N)=2n\,N^{\,n-1}

    Neuron ii compares the energy with si=±1s_i=\pm1, the other neurons held at pattern ν\nu. The pattern's own overlap is N−1N-1 either way except for the term ±1\pm1, so its signal is a difference of FF at the top of its range:

  2. noise≈2nP (2n−3)!! N n−1\text{noise}\approx2n\sqrt{P\,(2n-3)!!\,N^{\,n-1}}

    Every other pattern overlaps the state by xμ≈±Nx_\mu\approx\pm\sqrt N, a near-Gaussian with variance NN, and contributes ±2F′(xμ)\pm2F'(x_\mu) with a random sign. For a Gaussian, E[x2n−2]=(2n−3)!! Nn−1\E[x^{2n-2}]=(2n-3)!!\,N^{n-1}, so PP such terms have standard deviation

  3. signalnoise≈N n−1P (2n−3)!!\frac{\text{signal}}{\text{noise}}\approx\sqrt{\frac{N^{\,n-1}}{P\,(2n-3)!!}}

    The ratio is Nn−1/(P(2n−3)!!)\sqrt{N^{n-1}/\big(P(2n-3)!!\big)}, so PP can grow like Nn−1N^{n-1} before the noise wins, matching Krotov and Hopfield's error estimate exp⁡ ⁣(−Nn−1/2P(2n−3)!!)\exp\!\big(-N^{n-1}/2P(2n-3)!!\big). With F=exp⁡F=\exp, the signal is of order eNe^N while a typical competitor, with overlap of order N\sqrt N, contributes about eNe^{\sqrt N}. 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

DerivationThe update as a concave–convex step
  1. ∇E1(ξt+1)=−∇E2(ξt)⟹ξt+1=∇ξlse⁡(β,X⊤ξt)=X softmax⁡ ⁣(βX⊤ξt)\nabla E_1(\boldsymbol\xi^{t+1})=-\nabla E_2(\boldsymbol\xi^{t})\quad\Longrightarrow\quad\boldsymbol\xi^{t+1}=\nabla_{\boldsymbol\xi}\operatorname{lse}(\beta,X^\top\boldsymbol\xi^t)=X\,\softmax\!\big(\beta X^\top\boldsymbol\xi^t\big)

    Split E=E1+E2E=E_1+E_2 into the convex E1(ξ)=12ξ⊤ξE_1(\boldsymbol\xi)=\tfrac12\boldsymbol\xi^\top\boldsymbol\xi and the concave E2(ξ)=−lse⁡(β,X⊤ξ)E_2(\boldsymbol\xi)=-\operatorname{lse}(\beta,X^\top\boldsymbol\xi) (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:

  2. E(ξt+1)≤E1(ξt)+∇E2(ξt)⊤(ξt−ξt+1)+E2(ξt)+∇E2(ξt)⊤(ξt+1−ξt)=E(ξt)E(\boldsymbol\xi^{t+1})\le E_1(\boldsymbol\xi^t)+\nabla E_2(\boldsymbol\xi^t)^\top(\boldsymbol\xi^t-\boldsymbol\xi^{t+1})+E_2(\boldsymbol\xi^t)+\nabla E_2(\boldsymbol\xi^t)^\top(\boldsymbol\xi^{t+1}-\boldsymbol\xi^t)=E(\boldsymbol\xi^t)

    The energy never increases. Concavity of E2E_2 bounds it by its tangent at ξt\boldsymbol\xi^t; convexity of E1E_1, with ∇E1(ξt+1)=−∇E2(ξt)\nabla E_1(\boldsymbol\xi^{t+1})=-\nabla E_2(\boldsymbol\xi^t), bounds E1(ξt+1)E_1(\boldsymbol\xi^{t+1}) by E1(ξt)E_1(\boldsymbol\xi^t) plus the opposite linear term. Adding the two inequalities, the linear terms cancel:

  3. ξnew=Xsoftmax⁡(βX⊤ξ)⟷z=V⊤softmax⁡ ⁣(Kqdk)\boldsymbol\xi^{\text{new}}=X\softmax(\beta X^\top\boldsymbol\xi)\quad\longleftrightarrow\quad\mathbf z=V^\top\softmax\!\Big(\frac{K\mathbf q}{\sqrt{d_k}}\Big)

    Now read the update as attention. The state is a query, the stored patterns are keys, and β=1/dk\beta=1/\sqrt{d_k}; reading out each key's associated value instead of the key itself (a hetero-associative readout) gives exactly the attention output ∑jsoftmax⁡j(β q⋅kj) vj\sum_j\softmax_j(\beta\,\mathbf q\cdot\mathbf k_j)\,\mathbf v_j. 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 βδ\beta\delta is small, because β\beta 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 β→0\beta\to0 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 z=Wx\mathbf z=W\mathbf x, the gradient is ∂ℓ/∂W=(∂ℓ/∂z) x⊤\partial\ell/\partial W=(\partial\ell/\partial\mathbf z)\,\mathbf x^\top, 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.

DerivationScaling laws for associative memories, heuristically
  1. p(x)∝x−α (α>1)⟹∑x>dp(x)≍d 1−αp(x)\propto x^{-\alpha}\ (\alpha>1)\quad\Longrightarrow\quad\sum_{x>d}p(x)\asymp d^{\,1-\alpha}

    Cabannes, Dohmatob and Bietti (2024) study a memory W=∑xq(x) uf(x)ex⊤W=\sum_xq(x)\,\mathbf u_{f(x)}\mathbf e_x^\top with random embeddings in Rd\R^d, learning a deterministic map ff from TT samples whose inputs follow a Zipf law. A memory of dimension dd can hold roughly the dd most frequent associations, up to logarithmic factors, so the error is at least the probability of the rest:

  2. ∑x>T1/αp(x)≍(T1/α)1−α=T−1+1/α\sum_{x>T^{1/\alpha}}p(x)\asymp\big(T^{1/\alpha}\big)^{1-\alpha}=T^{-1+1/\alpha}

    With TT samples, inputs whose expected count Tp(x)Tp(x) is below one are typically never seen. The cutoff is x≈T1/αx\approx T^{1/\alpha}, and the unseen tail has probability

  3. E E ≍ T−1+1/α+d−α+1\E\,\mathcal E\ \asymp\ T^{-1+1/\alpha}+d^{-\alpha+1}

    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 W=∑iviki⊤W=\sum_i\mathbf v_i\mathbf k_i^\top with random keys has crosstalk of squared norm (N−1)/d(N-1)/d; linear readouts, linear attention included, store about dd pairs, and the delta rule overwrites instead of adding.
  • Hopfield dynamics descend an energy, ΔE=−2∣hi∣\Delta E=-2\abs{h_i} per flip; Hebbian storage holds about N/(2ln⁡N)N/(2\ln N) exactly stable patterns, or about 0.138N0.138N with a few wrong bits.
  • Sharper interaction energies separate the best match from the rest: F(x)=xnF(x)=x^n stores about Nn−1N^{n-1} patterns, and F=exp⁡F=\exp exponentially many.
  • The modern Hopfield update Xsoftmax⁡(βX⊤ξ)X\softmax(\beta X^\top\boldsymbol\xi) is a concave–convex step on a log-sum-exp energy and equals attention with β=1/dk\beta=1/\sqrt{d_k}: single-pattern retrieval when βδ\beta\delta 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 T−1+1/α+d−α+1T^{-1+1/\alpha}+d^{-\alpha+1}.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A Hopfield network with N=2000N=2000 neurons and Hebbian weights stores random patterns. Allowing a small fraction of wrong bits, about how many patterns can it retrieve?

  1. About 20002000, one per neuron
  2. About 132132, that is N/(2ln⁡N)N/(2\ln N)
  3. About 276276, that is 0.138N0.138N
  4. About 2×1062\times10^6, one per weight
Show the answer

C. About 276276, that is 0.138N0.138N

Amit, Gutfreund and Sompolinsky's critical ratio αc≈0.138\alpha_c\approx0.138 gives about 276276. Beyond it, retrieval states with few errors disappear abruptly.

Question 2

In the modern Hopfield update ξ←Xsoftmax⁡(βX⊤ξ)\boldsymbol\xi\leftarrow X\softmax(\beta X^\top\boldsymbol\xi), what does the state become as β→0\beta\to0?

  1. The stored pattern with the largest overlap
  2. The average of all stored patterns
  3. The zero vector
  4. It stays where it is
Show the answer

B. The average of all stored patterns

At β=0\beta=0 the softmax is uniform, so the update returns 1N∑ixi\tfrac1N\sum_i\mathbf x_i, the global fixed point. Large β\beta gives single-pattern retrieval; intermediate values give metastable averages over clusters.

Question 3

A linear memory already maps unit key k\mathbf k to an old value. What does the delta-rule write W←W+(v−Wk)k⊤W\leftarrow W+(\mathbf v-W\mathbf k)\mathbf k^\top do that the Hebbian write W←W+vk⊤W\leftarrow W+\mathbf v\mathbf k^\top does not?

  1. It makes Wk=vW\mathbf k=\mathbf v exactly, replacing the old value instead of adding the new one to it
  2. It stores the pair without changing WW
  3. It raises the capacity beyond dd linearly independent keys
  4. It makes all keys orthogonal
Show the answer

A. It makes Wk=vW\mathbf k=\mathbf v exactly, replacing the old value instead of adding the new one to it

Wnewk=Wk+(v−Wk)∥k∥2=vW_{\text{new}}\mathbf k=W\mathbf k+(\mathbf v-W\mathbf k)\norm{\mathbf k}^2=\mathbf v. The Hebbian write returns old value plus new value. Neither escapes the rank bound: a linear map recalls at most dd generic pairs exactly.

Question 4

Why is the energy of the modern Hopfield network guaranteed not to increase under its update?

  1. Because the softmax is a contraction
  2. Because the energy is convex, so any gradient step decreases it
  3. Because the update is a concave–convex procedure step on a convex quadratic plus a concave −lse⁡-\operatorname{lse}
  4. 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 −lse⁡-\operatorname{lse}

Linearizing the concave part at the old state and minimizing the resulting convex upper bound gives ξt+1=Xsoftmax⁡(βX⊤ξt)\boldsymbol\xi^{t+1}=X\softmax(\beta X^\top\boldsymbol\xi^t); the bound touches EE at ξt\boldsymbol\xi^t, so EE 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).