Wilhelm Berghammer

How much can a matrix remember?

September 2026 · Explainer · Linear attention and linear associative memory, from first principles

1The problem attention solves

A sequence model reads vectors x1,x2,…,xT∈Rdx_1, x_2, \dots, x_T \in \R^d, one per token. At the input these are token embeddings; deeper in the network they are the hidden states of the previous layer. At position tt the model has to produce an output that may depend on anything seen so far. Which earlier tokens matter is not fixed by position. In "the cat that the dog chased ran away", the verb "ran" needs "cat", five tokens back, and in another sentence the relevant word will be somewhere else. The model has to find earlier information by its content.

The simplest content-based lookup uses the dot product. For two vectors, a⊤b=∑mambm=∥a∥ ∥b∥cos⁡∠(a,b)a^\top b = \sum_m a_m b_m = \|a\|\,\|b\|\cos\angle(a,b) is large when they point in similar directions, zero when they are orthogonal, and negative when they point apart. So position tt could score every earlier token by xt⊤xix_t^\top x_i and return an average of the xix_i weighted by these scores.

This asks one vector to do three different jobs. As the thing doing the searching, xtx_t describes what position tt is looking for. As the thing being searched, xix_i describes how position ii can be found. As the result, xix_i is also what gets returned. Using a single vector for all three causes concrete failures. A token scores highest against tokens that resemble itself, so it mostly retrieves near-copies of itself. The score is symmetric, so if "ran" finds "cat", "cat" finds "ran" equally well, although what each needs from the other is different. And what is returned is the raw token, with no choice about which of its features to pass on.

The repair is to give each job its own learned linear map:

qt=WQ xt,ki=WK xi,vi=WV xi.\Q{t} = W_Q\, x_t, \qquad \K{i} = W_K\, x_i, \qquad \V{i} = W_V\, x_i.

The query qt\Q{t} is what position tt is looking for. The key ki\K{i} is how position ii advertises itself to queries. The value vi\V{i} is what position ii hands over when it is found. Queries and keys are compared by a dot product, so they must live in the same space, qt,ki∈Rdk\Q{t}, \K{i} \in \R^{d_k}. Values are never compared with anything, so their dimension dvd_v is a separate choice. The three matrices are learned by gradient descent along with the rest of the network; this post takes them as given and asks what happens once the vectors exist.

2Softmax attention

The scores qt⊤ki\Q{t}^\top\K{i} can be any real numbers. To average values we want nonnegative weights that sum to one. Exponentiating makes every score positive, and dividing by the total makes the weights sum to one:

yt  =  ∑i≤texp⁡(qt⊤ki)∑j≤texp⁡(qt⊤kj)⏟weight on vi vi.y_t \;=\; \sum_{i\le t} \underbrace{\frac{\exp(\Q{t}^\top \K{i})}{\sum_{j\le t}\exp(\Q{t}^\top \K{j})}}_{\text{weight on } \V{i}}\,\V{i}.

The exponential does more than make weights positive. A score higher by 11 gets e≈2.7e \approx 2.7 times the weight, so if one key matches the query clearly better than the others, its value dominates the average and the lookup behaves almost like picking a single entry. The sum runs over i≤ti \le t so that position tt never uses tokens that come after it, which is what makes the model usable for generation. This operation is attention (Vaswani et al., 2017). We leave out the 1/dk1/\sqrt{d_k} scaling and the use of several heads in parallel; neither changes anything below.

Now look at where qt\Q{t} appears. It sits inside every exponential and inside the denominator, which couples all the keys together. Before the query arrives there is nothing useful to compute in advance, so every pair (ki,vi)(\K{i}, \V{i}) has to be kept until it is needed. This store is the key-value cache, and it grows with tt. Each new token must be compared with all earlier ones, so producing TT tokens costs time proportional to T2T^2.

Suppose instead we are only allowed a fixed number of numbers, a matrix S∈Rdv×dkS \in \R^{d_v\times d_k}, and we must write each pair into it as it arrives and discard the pair afterwards. Two questions follow. How should a pair be written? And how many pairs can such a matrix hold before reads start to go wrong?

3Removing the softmax

Replace exp⁡(qt⊤ki)\exp(\Q{t}^\top\K{i}) by qt⊤ki\Q{t}^\top\K{i} and drop the denominator (Katharopoulos et al., 2020). Each term vi (ki⊤qt)\V{i}\,(\K{i}^\top\Q{t}) is a vector times a number, and that number is linear in qt\Q{t}. Writing ki⊤qt\K{i}^\top\Q{t} and then multiplying by vi\V{i} is the same as first forming the matrix viki⊤\V{i}\K{i}^\top and then applying it to qt\Q{t}. Since every term has this form, the query can be pulled out of the sum:

yt  =  ∑i≤tvi (ki⊤qt)  =  (∑i≤tviki⊤) qt  =  St qt.y_t \;=\; \sum_{i\le t} \V{i}\,(\K{i}^\top \Q{t}) \;=\; \Big(\sum_{i\le t} \V{i}\K{i}^\top\Big)\,\Q{t} \;=\; S_t\,\Q{t}.

The matrix vk⊤∈Rdv×dk\Vb\Kb^\top \in \R^{d_v\times d_k} is the outer product of v\Vb and k\Kb, with entries (vk⊤)ab=vakb(\Vb\Kb^\top)_{ab} = v_a k_b. Pulling qt\Q{t} out of the sum is the entire derivation. Everything the past contributes to any future read is collected into StS_t before the query is known. The pairs can be thrown away, and StS_t is updated by adding one term per step:

St=St−1+vtkt⊤,S0=0.S_t = S_{t-1} + \V{t}\K{t}^\top, \qquad S_0 = 0.

A model that carries a fixed-size state from one step to the next and updates it with each input is a recurrent network, and StS_t is its state. Storing a pair means adding its outer product to the state. Retrieving means multiplying the state by a query.

The same matrix appeared long before transformers, as the correlation matrix memory (Kohonen, 1972; Anderson, 1972), and Schlag et al. (2021) show that linear attention is a fast weight programmer, a network whose weights are rewritten at every step. To understand what this memory can and cannot do, we need to understand the object being added.

4One stored pair

Apply vk⊤\Vb\Kb^\top to an arbitrary input x∈Rdkx \in \R^{d_k}:

(vk⊤) x  =  v (k⊤x).(\Vb\Kb^\top)\,x \;=\; \Vb\,(\Kb^\top x).

Read the right-hand side from the inside out. The scalar k⊤x\Kb^\top x depends only on the component of xx along k\Kb. That number is then used as a coefficient on v\Vb. So the map ignores every direction of the input perpendicular to k\Kb, and it can only ever output multiples of v\Vb. The set of inputs sent to zero, the null space, is the set of vectors perpendicular to k\Kb. The set of possible outputs, the image, is the line through v\Vb. A matrix whose image is a single line has rank 1, and every rank-1 matrix is an outer product of this kind.

Querying with the key itself gives (vk⊤)k=v ∥k∥2(\Vb\Kb^\top)\Kb = \Vb\,\|\Kb\|^2. The stored value comes back scaled by the squared length of the key, so for exact recall we want keys of length one. We assume ∥ki∥=1\|\K{i}\|=1 from here on.

In the figures dk=dv=2d_k = d_v = 2, so keys, queries and values are arrows in a plane and everything can be drawn. Nothing in the argument depends on the dimension being 2. The left panel of each figure is the space of keys and queries, the right panel is the space of values, and the matrix in between is the map from one to the other.

Inputs (drag xx)

SS
=vk⊤= \Vb\Kb^\top

Outputs SxSx

Figure 1. A single stored pair. The input xx is dropped perpendicularly onto the line through k\Kb, and the length of that drop, k⊤x\Kb^\top x, sets how much of v\Vb comes out. Moving xx parallel to the gray line k⊥\Kb^\perp changes nothing on the right; inputs on that line give zero. The dashed unit circle on the left is flattened onto the dark segment on the right, which is what rank 1 looks like. With x=kx = \Kb the output is ∥k∥2v\|\Kb\|^2\Vb, so changing the length of k\Kb changes the recalled value.

5Two pairs, and the Gram matrix

Store a second pair. The memory is S=v1k1⊤+v2k2⊤S = \V{1}\K{1}^\top + \V{2}\K{2}^\top, and a read is the sum of what each outer product does on its own:

Sq  =  v1 (k1⊤q)  +  v2 (k2⊤q).S\Qb \;=\; \V{1}\,(\K{1}^\top\Qb) \;+\; \V{2}\,(\K{2}^\top\Qb).

The query is dropped onto each key separately, and each drop weights its own value. Querying with k1\K{1} gives v1 ∥k1∥2+v2 (k2⊤k1)=v1+cos⁡θ v2\V{1}\,\|\K{1}\|^2 + \V{2}\,(\K{2}^\top\K{1}) = \V{1} + \cos\theta\,\V{2}, where θ\theta is the angle between the keys. The second term is interference: part of the other value comes back as well, in proportion to how much the keys overlap.

Keys and query (drag q\Qb)

SS
=v1k1⊤+v2k2⊤= \V{1}\K{1}^\top + \V{2}\K{2}^\top

Values and output SqS\Qb

Figure 2. Two stored pairs with unit keys. The dots on the left mark the drops k1⊤q\K{1}^\top\Qb and k2⊤q\K{2}^\top\Qb; on the right these weight v1\V{1} and v2\V{2}, and the read is their sum drawn tip to tail. The ellipse is the image of the dashed unit circle. With perpendicular keys it passes through both values, for any angle between the values. Narrow the angle between the keys and the read at q=k1\Qb = \K{1} moves off v1\V{1} toward v2\V{2}.

The same computation works for any number of pairs. Stack the nn keys as the columns of K=[k1  ⋯  kn]∈Rdk×n\KK = [\K{1}\;\cdots\;\K{n}] \in \R^{d_k\times n} and the values as the columns of V=[v1  ⋯  vn]∈Rdv×n\VV = [\V{1}\;\cdots\;\V{n}] \in \R^{d_v\times n}. The sum of outer products is S=VK⊤S = \VV\KK^\top, and querying with every stored key at once gives

S K  =  V (K⊤K)  =  V G,Gij=ki⊤kj.S\,\KK \;=\; \VV\,(\KK^\top\KK) \;=\; \VV\,G, \qquad G_{ij} = \K{i}^\top\K{j}.

The n×nn \times n matrix GG of all dot products between keys is the Gram matrix. Column jj of VG\VV G is the read for kj\K{j}, namely ∑iGij vi\sum_i G_{ij}\,\V{i}, so column jj of GG lists how much of each value comes back. The diagonal entries are ∥kj∥2=1\|\K{j}\|^2 = 1, the wanted value at full strength. The off-diagonal entries are the cosines between keys, and each one is the weight of a wrong value leaking into a read.

Every stored value is read back exactly if and only if G=IG = I, which means the keys are orthonormal: unit length and mutually perpendicular. The values can point anywhere. In Rdk\R^{d_k} at most dkd_k vectors are mutually perpendicular, so at most dkd_k pairs can be stored without interference, and in the plane a third key always overlaps the first two. The capacity depends on the key dimension alone. The values are only written down; the keys are what has to be kept apart. Schlag et al. (2021) discuss this limit for linear transformers.

This explains why softmax attention does not run out of room. Expand the exponential as a power series, exp⁡(q⊤k)=∑m≥0(q⊤k)m/m!\exp(\Qb^\top\Kb) = \sum_{m\ge 0} (\Qb^\top\Kb)^m/m!. Each power (q⊤k)m(\Qb^\top\Kb)^m is itself a dot product, between the vectors of all mm-fold products of coordinates of q\Qb and of k\Kb. Collecting these vectors for every mm gives a map ϕ\phi with exp⁡(q⊤k)=ϕ(q)⊤ϕ(k)\exp(\Qb^\top\Kb) = \phi(\Qb)^\top\phi(\Kb), where ϕ\phi has infinitely many coordinates. Apart from the denominator, softmax attention is the memory of this post with keys ϕ(ki)\phi(\K{i}) in an infinite-dimensional space, where the dimension bound never applies. The price is that ϕ(k)\phi(\Kb) cannot be stored, so the original pairs are stored instead. Linear attention with a finite map ϕ\phi of dimension dϕd_\phi applied to queries and keys has capacity dϕd_\phi. Tsai et al. (2019) develop this kernel view of attention, and Choromanski et al. (2021) approximate ϕ\phi with finitely many random features.

6The best a fixed matrix can do

Adding outer products is one way to fill SS. Is it the best? Suppose all nn pairs are available and we choose the matrix whose reads are closest to the stored values, measured by the total squared error:

S⋆=arg⁡min⁡S ∑j=1n∥Skj−vj∥2=arg⁡min⁡S ∥SK−V∥F2.S^\star = \arg\min_S\, \sum_{j=1}^n \|S\K{j} - \V{j}\|^2 = \arg\min_S\, \|S\KK - \VV\|_F^2.

The subscript FF denotes the Frobenius norm, the square root of the sum of squared entries; the two expressions are the same sum. This is a least squares problem. When the keys are linearly independent, GG is invertible and the solution is

S⋆=V G−1K⊤,S⋆K=VG−1G=V.S^\star = \VV\,G^{-1}\KK^\top, \qquad S^\star\KK = \VV G^{-1} G = \VV.

Every value is recalled exactly, even for keys that overlap. To see what G−1G^{-1} does, write S⋆=∑ivi k~i⊤S^\star = \sum_i \V{i}\,\tilde{k}_i^\top, where k~i\tilde{k}_i is column ii of KG−1\KK G^{-1}. These vectors satisfy

k~i⊤kj=(G−1K⊤K)ij=(G−1G)ij={1i=j0i≠j.\tilde{k}_i^\top \K{j} = (G^{-1}\KK^\top\KK)_{ij} = (G^{-1}G)_{ij} = \begin{cases} 1 & i = j \\ 0 & i \neq j. \end{cases}

So k~i\tilde{k}_i has dot product one with its own key and zero with every other key. The vectors k~i\tilde{k}_i are called the dual basis of the keys. The least squares memory stores each value under the dual of its key, and since the dual of k1\K{1} is perpendicular to k2\K{2}, querying with k2\K{2} picks up nothing of v1\V{1}.

There is a second way to read the same formula. A query in the span of the keys can be written in exactly one way as q=∑jcjkj\Qb = \sum_j c_j \K{j}, and taking the dot product with k~i\tilde{k}_i shows ci=k~i⊤qc_i = \tilde{k}_i^\top\Qb. Hence S⋆q=∑iciviS^\star\Qb = \sum_i c_i \V{i}: the least squares memory is the linear map that sends each key to its value, applied to the coordinates of the query in the basis of keys. The additive memory weights vi\V{i} by ki⊤q\K{i}^\top\Qb, a perpendicular drop onto each key separately; the least squares memory weights it by cic_i, which is found by walking to the query along the key directions. The two agree exactly when the keys are orthonormal.

Keys and query (drag q\Qb)

SS
=VK⊤= \VV\KK^\top

Values and output SqS\Qb

Figure 3. The same two pairs stored in two ways. In additive mode the dashed lines drop perpendicularly onto each key, as in Figure 2. In least squares mode they run parallel to the other key, so the dots mark the coordinates c1,c2c_1, c_2 of the query in the basis of keys, and the thin dashed arrows are the dual vectors k~1,k~2\tilde{k}_1, \tilde{k}_2. Least squares recalls both values at any angle. Narrow the angle and watch its ellipse stretch and σmax⁡\sigma_{\max} grow.

Exact recall of overlapping keys has a cost, and Figure 3 shows it. For two unit keys at angle θ\theta, the dual vectors have length ∥k~i∥=1/sin⁡θ\|\tilde{k}_i\| = 1/\sin\theta. As the keys approach each other the dual vectors grow without bound, and S⋆S^\star stretches the direction in which the two keys differ by a large factor. The largest stretch of a matrix, its largest singular value σmax⁡\sigma_{\max}, is the long semi-axis of the ellipse. A query that is slightly off k1\K{1} then gives a read that is far from v1\V{1}. Least squares separates nearby keys by amplifying the small difference between them, and it amplifies small errors in the query by the same factor.

When the keys are linearly dependent, which is unavoidable once n>dkn > d_k, GG is not invertible. The minimizer is then S⋆=VK+S^\star = \VV\KK^{+}, where K+\KK^{+} is the pseudoinverse, and S⋆S^\star is the best compromise in squared error rather than an exact memory. This optimal linear associative memory was described by Kohonen and Ruohonen (1973). Linear attention cannot use it. Forming GG requires the dot product between every pair of keys, and a recurrent memory discards each key after writing it.

7How much can a matrix remember?

Section 5 answered this for keys we choose. A trained network does not choose its keys to be perpendicular; they are WKxiW_K x_i for whatever tokens arrive, and they overlap. To see what happens then, take the simplest model of overlapping keys: nn keys drawn independently and uniformly from the unit sphere in Rdk\R^{d_k}, and values drawn independently with mean zero and E∥vi∥2=1\mathbb{E}\|\V{i}\|^2 = 1. We measure the average squared read error e(n)=E ∥Skj−vj∥2e(n) = \mathbb{E}\,\|S\K{j} - \V{j}\|^2, which is on the same scale as a stored value.

Additive memory. The error in reading kj\K{j} is the interference term, Skj−vj=∑i≠jvi (ki⊤kj)S\K{j} - \V{j} = \sum_{i\neq j}\V{i}\,(\K{i}^\top\K{j}). Different values are uncorrelated, so the cross terms average to zero and

eadd(n)=∑i≠jE[(ki⊤kj)2].e_{\text{add}}(n) = \sum_{i\neq j} \mathbb{E}\big[(\K{i}^\top\K{j})^2\big].

The expectation can be found without integrating. The distribution of keys does not change under rotations, so we may rotate until kj\K{j} is the first coordinate axis. Then ki⊤kj\K{i}^\top\K{j} is just the first coordinate of ki\K{i}. The squared coordinates of a unit vector add up to 1, and by symmetry none of the dkd_k coordinates is special, so each squared coordinate has mean 1/dk1/d_k. With n−1n - 1 interfering pairs,

eadd(n)=n−1dk.e_{\text{add}}(n) = \frac{n-1}{d_k}.

The error grows in a straight line from the first extra pair onward. There is no threshold: the interference reaches the size of the signal at n=dk+1n = d_k + 1, and keeping the error below a fraction ε\varepsilon allows only about ε dk\varepsilon\, d_k pairs.

Least squares memory. For n≤dkn \le d_k, random keys are linearly independent with probability one, so els(n)=0e_{\text{ls}}(n) = 0. For n>dkn > d_k the reads are S⋆K=V K+KS^\star\KK = \VV\,\KK^{+}\KK, and K+K\KK^{+}\KK is the orthogonal projection of Rn\R^n onto a dkd_k-dimensional subspace (the row space of K\KK). Each row of V\VV is a vector in Rn\R^n holding one coordinate of all nn values. If the values are Gaussian, this row points in a uniformly random direction independent of the keys, and projecting it onto a dkd_k-dimensional subspace of Rn\R^n keeps, on average, a fraction dk/nd_k/n of its squared length. The lost fraction is the error:

els(n)={0n≤dk1−dknn>dk.e_{\text{ls}}(n) = \begin{cases} 0 & n \le d_k \\[2pt] 1 - \dfrac{d_k}{n} & n > d_k. \end{cases}

This memory is exact up to exactly dkd_k pairs and then degrades, reaching half the signal at n=2dkn = 2d_k.

Figure 4. Average read error for random unit keys in Rdk\R^{d_k} and random Gaussian values, on the scale of a stored value. Lines are the formulas (n−1)/dk(n-1)/d_k and 1−dk/n1 - d_k/n; dots are averages over simulated memories, and for least squares with n≤dkn \le d_k the error is exactly zero. The dashed horizontal line is where the error equals the signal, and the dashed vertical line is n=dkn = d_k.

This answers the question in the title for the two memories we have. A matrix in Rdv×dk\R^{d_v\times d_k} can hold dkd_k pairs exactly if it is fitted with all the keys in hand. Filled by adding outer products, as linear attention does, it recalls a single pair exactly and holds about ε dk\varepsilon\, d_k pairs at relative error ε\varepsilon. The value dimension appears in neither answer. Everything a linear associative memory can store is limited by how many directions its keys can occupy.

References

  • Anderson, J. A. (1972). A simple neural network generating an interactive memory. Mathematical Biosciences, 14(3–4), 197–220.
  • Choromanski, K., Likhosherstov, V., Dohan, D., Song, X., Gane, A., Sarlos, T., et al. (2021). Rethinking attention with Performers. International Conference on Learning Representations.
  • Katharopoulos, A., Vyas, A., Pappas, N., & Fleuret, F. (2020). Transformers are RNNs: Fast autoregressive transformers with linear attention. International Conference on Machine Learning.
  • Kohonen, T. (1972). Correlation matrix memories. IEEE Transactions on Computers, C-21(4), 353–359.
  • Kohonen, T., & Ruohonen, M. (1973). Representation of associated data by matrix operators. IEEE Transactions on Computers, C-22(7), 701–702.
  • Schlag, I., Irie, K., & Schmidhuber, J. (2021). Linear transformers are secretly fast weight programmers. International Conference on Machine Learning.
  • Tsai, Y.-H. H., Bai, S., Yamada, M., Morency, L.-P., & Salakhutdinov, R. (2019). Transformer dissection: A unified understanding of transformer's attention via the lens of kernel. Empirical Methods in Natural Language Processing.
  • Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., & Polosukhin, I. (2017). Attention is all you need. Advances in Neural Information Processing Systems.