Transformers as Memory: From Outer Products to Attention


A transformer can be understood as a collection of memory lookups. This is a useful way to see why its two familiar ingredients—a feedforward network and self-attention—have the shapes they do. Both compare a query with keys and combine the corresponding values. They differ in where those key–value pairs live and in how sharply the lookup separates a match from the rest.

The key problem is interference. If a query retrieves the value it wanted plus fragments of many unrelated values, adding more memories eventually makes recall useless. Starting with the simplest possible store, we can improve the way memories are written, then the way they are selected, until the equations look like transformer layers.

This account follows the associative-memory construction by Alex Wang and adds context from the original Transformer paper and work connecting modern Hopfield networks to attention. The capacity figures below describe a particular random-vector experiment, not the factual knowledge or usable context length of a trained language model.

One memory is a key and a value

Call a memory a pair (key, value). The key identifies when the memory should be retrieved; the value is the information to return. A query vector is compared with stored keys. A good store returns the value belonging to a matching key and gives little weight to unrelated values.

If the keys are unit vectors, their dot product with the query measures similarity. A dot product of 1 means an exact match. Random unrelated keys in d dimensions usually have dot products near zero, with a typical size around 1 / √d. Small is not the same as harmless: many small contributions can add up.

For a concrete picture, suppose a 64-dimensional query matches one stored key exactly. Each other random key contributes a noisy weight of roughly 1/8, positive or negative. If there are enough unrelated memories, the combined noise becomes comparable to the target signal.

The simplest store: add outer products

We can write each memory into a matrix by taking the outer product of its value and key, then adding all those products:

W = Σ valueᵢ · keyᵢᵀ
recall(query) = W · query
              = Σ valueᵢ · (keyᵢᵀ · query)

The final expression says exactly what the store does: score each key against the query and return a weighted sum of values. Adding a new memory takes one matrix update. A gradient step on a linear layer has the same outer-product form: the layer input supplies a key-like vector and the output gradient supplies a value-like update.

Now query the store with one of its own unit keys, keyⱼ. The answer has two parts:

recall(keyⱼ) = valueⱼ
             + Σᵢ≠ⱼ valueᵢ · (keyᵢᵀ · keyⱼ)

The first term is the wanted signal. The second is interference from every other key. Orthogonal keys would eliminate it, but a d-dimensional space has at most d mutually orthogonal directions. With random keys and values of similar length, noise grows roughly as √(M/d) relative to the signal, where M is the number of memories. At M ≈ d, the two are comparable. In the 64-dimensional example, that happens around 64 random memories.

An exact query retrieves one target value while many unrelated keys contribute small noise; a selective nonlinear gate suppresses those weak contributions.
Capacity improves when weak matches stop contributing so much noise.

Write more carefully: the optimal linear fit

The outer-product rule stores each pair independently. It never checks whether the latest key overlaps with keys already stored. A better linear store chooses the matrix so that all stored keys map to their values as well as possible:

choose W to minimize Σ ||W · keyᵢ − valueᵢ||²

This is ordinary least squares. When there are no more memories than key dimensions and the keys are linearly independent, it can recall every stored value exactly—even if the keys are not mutually orthogonal. The solution effectively compensates for shared directions among the keys. For more memories than dimensions, the fit cannot satisfy every arbitrary pair exactly; its typical interference-to-signal ratio becomes √(M/d − 1) under the random-vector assumptions.

The ratio reaches one around M = 2d, or about 128 memories in the 64-dimensional example. That is twice the simple store’s threshold. It also shows a limit of fixing only the write rule: the lookup remains linear. Every similarity, however weak, still feeds into the output.

Select more carefully: an MLP appears

The next move is to pass each similarity through a nonlinear function before mixing the values:

recall(query) = Σ valueᵢ · activation(keyᵢᵀ · query)

Written as matrix operations, this is Vᵀ activation(K query): a two-layer feedforward network. Rows of the first matrix act like keys; columns of the second act like values. These are parameters learned during training, so this is a view of a layer’s weights as a memory store. It does not claim that every neuron holds one clean human-readable fact.

The activation changes the noise. ReLU deletes negative similarities, roughly half of the interference from random keys. Under this simple model its threshold rises from about d to 2d. A squared ReLU also makes small positive matches much smaller: 0.1 becomes 0.01, while a perfect match stays 1. For random keys and values, the resulting capacity estimate is about 2d²/3, roughly 2,700 memories at d = 64. A tied-gate SwiGLU-like function gives a similar estimate; a cubed ReLU can push the idealized number higher still.

Why does a power help so much? A random wrong key has similarity on the order of d⁻¹ᐟ². Raising that score to power p reduces its weight to roughly d⁻ᵖᐟ², while a perfect match still weighs one. Many weak matches are still present, but each does far less damage.

This is a useful model for what feedforward layers can do. Geva and colleagues observed key–value behavior in trained transformer feedforward blocks. Actual layers also have biases, learned feature geometry, residual paths, normalization, and—in many models—gated activations. Their behavior is richer than the clean random-key calculation.

Put the memories in the current sequence

An MLP keeps its keys and values in learned weights. Self-attention builds them from the tokens currently in the context. For each token, learned projections produce a key and a value; another projection produces a query. The current query compares against the permitted keys, then blends their values.

The selection function is an exponential followed by normalization:

weightᵢ = exp(β · keyᵢᵀ · query) / Σⱼ exp(β · keyⱼᵀ · query)
output  = Σᵢ weightᵢ · valueᵢ

This is softmax attention in a simplified notation. The exponential strongly rewards a better match, while the denominator turns raw scores into weights that sum to one. In ordinary transformer notation the logits are query · key / √dₖ. Wang’s derivation uses unit-length vectors and writes the comparable sharpness as β = √dₖ; the different forms account for different assumptions about vector lengths.

A feedforward block retrieves from learned key-value parameters, while self-attention retrieves from keys and values produced by the current token sequence.
Both layers perform similarity-weighted retrieval; they differ in where the memories reside.

Because context tokens supply the pairs, attention’s memory set grows with the sequence. It is nonparametric in this narrow sense: the temporary entries are activations, not extra learned parameters. For an autoregressive model, a causal mask restricts retrieval to earlier and current positions. Multi-head attention repeats the lookup with different learned projections and combines the results.

Why softmax can separate many random memories

An exponential includes terms of every polynomial power. In the random-key thought experiment, that lets it suppress weak matches more aggressively than a fixed low-degree activation. If one stored key matches a unit query exactly, its unnormalized weight is exp(β). A random wrong key has a dot product near zero and a much smaller typical weight.

For random unit keys and values, Wang derives a noise-to-signal approximation of √M · exp(β²/d − β). Setting it to one gives an estimated threshold near exp(2β(1 − β/d)). At d = 64 and β = 8, that is about 1.2 million pairs, compared with about 64 for the basic outer-product store and about 2,700 for squared ReLU. The modern Hopfield-network connection offers another route to understanding the strong retrieval behavior of attention-like updates.

These numbers are conditional. They assume random, well-separated unit keys, random values, a query that is exactly one stored key, and a particular point where noise equals signal. Real queries may be approximate or ambiguous; trained keys are not random; relevant information may require composing several values. The estimate is not a promise that a transformer can faithfully use a million-token context.

Sharpness also has a cost. Making β huge turns softmax toward a hard winner-take-all choice and can make gradients to other keys vanish. As the number of candidate keys grows, some long-context methods adjust the logit scale with sequence length; Wang describes logarithmic scaling variants used in research and models such as Qwen. That can preserve separation in the idealized experiment, but it cannot by itself solve positional extrapolation, compute and memory cost, or the problem of a missing relevant key.

What the memory picture explains—and what it does not

The construction gives a coherent progression:

StoreHow it retrievesApproximate threshold at 64 dimensions
Outer-product matrixLinear similarity64
Least-squares linear fitLinear similarity after compensating for overlap128
ReLU MLPDrops negative matches128
Squared-ReLU MLPSuppresses weak positive matches2,700
Softmax attentionExponentially favors stronger matches1.2 million under the stated assumptions

The first improvement fits memories jointly. The second filters weak matches. The third uses a much sharper, normalized selection over keys supplied by the current sequence. This explains why an MLP and an attention head can both be described as associative memories even though one stores long-lived learned parameters and the other reads temporary context.

It is only one lens on transformers. It does not measure a trained model’s factual knowledge in bits, explain how layers compose algorithms, or settle when attention retrieves a value versus transforms information. In practice, the model learns its own representations, and a useful answer may depend on several imperfect matches. The memory view is most valuable for seeing the design pressure behind the equations: retrieve a relevant signal while keeping a growing crowd of other signals quiet.

Sources

100%