srinivas raghav blog's

Deep Learning Note 3: Attention as Dynamic Retrieval

In our previous discussion, we explored what happens when we add a large number of quantities together. We discovered that the magnitude of their combined effect depends not only on the magnitude of the individual quantities, but also on their relationships with one another. Contributions that fluctuate independently tend to cancel, while contributions that share a direction tend to reinforce one another. We now want to explore a slightly different question. Instead of simply adding together a collection of quantities, what if we could decide how much each individual quantity should contribute to the final result?

This distinction is particularly important. Previously, every quantity participated equally in our sum. We now want to introduce the ability to decide which quantities deserve greater influence, which deserve less influence, and how that decision might change depending on what we are trying to accomplish. This is one of the fundamental ideas behind attention. Imagine reading the following sentence:

The animal didn't cross the street because it was too tired.

When we encounter the word it, we naturally look towards earlier parts of the sentence to understand what it refers to. We recognise that the animal is capable of being tired, whereas the street is not. Consequently, the information associated with the animal becomes more useful than the information associated with the street. Notice that we are not treating every earlier word as equally important. The usefulness of a word depends on what we are currently trying to understand. If we were instead trying to understand the word cross, the street might become considerably more relevant.

The information available to us has not changed. What has changed is the question we are implicitly asking of that information. This gives us a useful starting point for understanding attention: attention is a mechanism for retrieving and combining information according to its relevance to the current computation.

How a neural network represents information

Before understanding how this mechanism works mathematically, we need to understand what information actually means inside a neural network. A language model does not directly manipulate words such as animal, street, or tired. Instead, each token is represented by a vector containing many numerical coordinates. In a hypothetical model with a hidden dimension of 2,048, the representation of a token at a particular layer might be written as

hi∈R2048

The subscript i identifies the token's position, while R2048 tells us that its representation contains 2,048 real-valued coordinates. We can write such a representation explicitly as

hi=[hi,1hi,2⋮hi,2048]

These coordinates collectively encode information that the model has learned to represent. Some directions within this space might relate to grammatical structure, others to semantic relationships, and others to more abstract computational features. It is important not to imagine that the first coordinate necessarily represents grammar, the second represents meaning, and the third represents something else. Information in neural networks is often distributed across combinations of coordinates. A meaningful feature might correspond to an entire direction in this high-dimensional space rather than a single coordinate. As these token representations pass through successive layers, they are transformed and enriched with additional information.

However, there is an interesting problem. The information that one token needs may currently exist inside the representation of another token. The representation of it, for instance, may need access to information currently contained in the representation of animal. How can we allow one vector to retrieve useful information from another vector?

From sums to weighted averages

One straightforward possibility would be to simply add all the available token representations together. Suppose we have N token representations, h1,h2,…,hN. We could construct a new representation by computing

o=∑j=1Nhj

This would allow information from every token to participate in the resulting vector. Unfortunately, this approach has several limitations. Firstly, it treats every token as equally relevant. The representation of it receives just as much contribution from the, street, and because as it does from animal. Secondly, the magnitude of the result may depend heavily on how many tokens are present and how their representations relate to one another. Recall what we discovered in our previous discussion. If we sum N zero-mean quantities with variance σ2 and pairwise correlation ρ, the standard deviation of their sum is

Std(S)=σN+ρN(N−1)

When the quantities are uncorrelated, their combined magnitude grows proportionally to N. When they are perfectly aligned, it grows proportionally to N. Something similar can happen when we add vectors together, because vector addition involves adding their corresponding coordinates. As the number of available tokens increases, the characteristics of the resulting representation may therefore change simply because more tokens have participated in the sum. This is not necessarily what we want. Ideally, we would like the model to retrieve information according to its usefulness rather than allowing the number of available tokens to determine the magnitude of its output.

We could partially address this problem by taking an average instead of a sum.

o=1N∑j=1Nhj

Averaging introduces a particularly useful property. If every available vector is identical to some vector v, then

1N∑j=1Nv=NvN=v

The representation does not become larger simply because we encounter more copies of the same information. We have separated the number of contributing vectors from the scale of their combined representation. However, averaging still treats every vector equally. It does not allow the model to distinguish between useful and irrelevant information. What we really want is something between selecting a single vector and averaging all the available vectors equally. We want a mechanism that allows each vector to contribute by a different amount. This brings us to the idea of a weighted sum.

o=a1v1+a2v2+⋯+aNvN

Or, more compactly,

o=∑j=1Najvj

Here, the vj represent the information available at different token positions, while the aj determine how much influence each piece of information has on the output. For the moment, we can think of each aj as a dial controlling the contribution of a particular vector. Suppose we have three two-dimensional value vectors:

v1=[40],v2=[04],v3=[−40]

If we give every vector equal influence, the resulting representation is

o=13v1+13v2+13v3=[043]

Notice that the first and third vectors cancel one another in the horizontal direction. Although both contain substantial information in that direction, their contributions disappear when combined equally. This is precisely the mathematical phenomenon we explored in our first bridge. Now suppose we decide that the first vector contains the most useful information for our current task. We might choose

(a1,a2,a3)=(0.8,0.15,0.05)

Our output becomes

o=0.8v1+0.15v2+0.05v3=[3.20]+[00.6]+[−0.20]=[30.6]

The output now points predominantly in the direction of the first vector. We have not changed the individual value vectors. We have changed their relative contributions to the final result. This is a particularly important distinction. Our first bridge taught us that the combined behaviour of quantities depends on whether they cancel or reinforce one another. Attention introduces a mechanism that can dynamically influence which contributions are allowed to participate strongly in that combination. Rather than allowing every available vector to participate equally, attention can emphasise useful contributions and reduce distracting or conflicting ones. But we are immediately faced with another question.

Where should the weights a1,a2,…,aN come from? We cannot manually specify them because the relevant information changes from sentence to sentence, token to token, and layer to layer. Instead, we want the model to learn how to determine these weights from the information it currently possesses.

Queries, keys, and values

This is where an attention head enters the picture. An attention head is a learned computational mechanism that allows a token to determine what information it needs, compare that need against the information available at other token positions, retrieve a weighted combination of that information, and make the retrieved information available to the subsequent computation. More precisely, an attention head contains learned linear transformations that produce three different representations from the hidden states: queries, keys, and values. Although these three representations originate from the same hidden-state vectors in self-attention, they serve different purposes. A query represents the kind of information a particular token is looking for. A key represents how another token can be matched against such a request. A value represents the information that another token can actually contribute if it is selected.

We can think of this as a distinction between searching for information and retrieving information. Imagine searching through a collection of books. The title, keywords, and description of a book help us determine whether it is relevant to what we are looking for. However, once we identify a useful book, it is the contents of the book that we actually want to read. The description and the contents serve related but distinct purposes. Similarly, the key is involved in deciding whether information should be retrieved, while the value determines what information is retrieved. This distinction gives the neural network considerable flexibility. The features that are useful for finding information do not have to be the same features that are useful after the information has been found.

Mathematically, if the hidden representation of token i is hi, we construct its query, key, and value using learned matrices:

qi=WQhiki=WKhivi=WVhi

Here, WQ, WK, and WV are different parameter matrices belonging to the attention head. During training, the model learns the entries of these matrices through gradient descent. The query projection can learn to emphasise features useful for expressing a request. The key projection can learn to emphasise features useful for being matched against requests. The value projection can learn to extract features that are useful to communicate between tokens. Suppose our hidden representation has 2,048 coordinates, but we want the query and key representations within one head to contain only 128 coordinates. Then

hi∈R2048

and

WQ,WK∈R128×2048

Multiplying these matrices by the hidden representation gives

qi,ki∈R128

We denote the number of coordinates in a query or key vector by dk. In this example,

dk=128

The value vectors have their own dimension, usually denoted by dv. Many architectures choose dv=dk, although they do not mathematically have to be equal. It is important to distinguish dk from the number of tokens, which we have been calling N. If a sequence contains 10,000 tokens and each token has a 128-dimensional key vector, then N=10,000 and dk=128. The first number tells us how many pieces of information are available to search through. The second tells us how many coordinates we use to describe each key and query. One describes the size of the collection. The other describes the dimensionality of the space in which the comparisons take place.

A single attention head can learn one particular way of searching through information and retrieving it. However, a token may need several different kinds of information simultaneously. For example, understanding a pronoun might involve identifying the noun it refers to, recognising the grammatical structure of the sentence, retrieving information from a previous sentence, and resolving the meaning of an ambiguous word. It would be rather restrictive if all these different computational needs had to share exactly the same attention distribution.

Why multiple attention heads

This is one of the motivations for using multiple attention heads. Each head has its own learned projections, allowing it to construct different queries, keys, and values from the same hidden representations. In a hypothetical model with 16 attention heads and a hidden dimension of 2,048, each head might operate on 128-dimensional query, key, and value vectors.

16×128=2048

One head might learn to retrieve information related to grammatical relationships, another might learn to identify repeated patterns, while another might learn to retrieve information from particular positions. These are intuitive examples of possible specialisations, not assignments explicitly given to the heads by the architecture. During training, heads can develop overlapping, distributed, or much less interpretable behaviours. The outputs of the individual heads are combined and passed through another learned linear projection, usually called the output projection WO.

MultiHead(hi)=WO[oi(1)oi(2)⋮oi(H)]

Here, H is the number of attention heads, and oi(r) represents the information retrieved by head r for token i. The resulting vector can then be added back into the token's residual stream.

hi′=hi+MultiHead(hi)

We will understand residual connections more deeply later. For now, the important idea is that attention provides a mechanism through which the representation of one token can be updated using information retrieved from other tokens. The basic concept of dynamically retrieving a weighted combination of information was already present in earlier attention mechanisms. In their 2014 paper, Neural Machine Translation by Jointly Learning to Align and Translate, Bahdanau, Cho, and Bengio explored how a translation model could adaptively retrieve relevant source representations instead of compressing an entire source sentence into one fixed-length vector. The Transformer subsequently made attention central to its architecture, using learned query, key, and value projections to implement this kind of information retrieval.

Measuring compatibility with dot products

Let us now return to the question of how an attention head decides which information is relevant. Suppose the current token has a query vector qi, and we have a collection of key vectors k1,k2,…,kN. We want to assign a numerical score to the compatibility between the current query and each available key. A natural mathematical operation for measuring this compatibility is the dot product. We explored the dot product earlier when studying vectors. Geometrically, the dot product between two vectors is

q⊤k=‖q‖2‖k‖2cosθ

Here, θ is the angle between the two vectors. When two vectors point in similar directions, cosθ is positive, and their dot product is positive. When they are perpendicular, cosθ=0, and their dot product is zero. When they point in opposing directions, cosθ is negative, and their dot product is negative. The dot product therefore gives us a way of measuring directional agreement, while also taking the magnitudes of the vectors into account. This is particularly useful when the directions themselves are learned. The model can learn to construct queries and keys such that information that is useful for a particular computation has strong alignment with the corresponding query. Suppose the query and key contain only two coordinates.

q=[21],k1=[11]

Their dot product is

q⊤k1=(2)(1)+(1)(1)=2+1=3

Now consider a second key.

k2=[1−1]

Its dot product with the same query is

q⊤k2=(2)(1)+(1)(−1)=2−1=1

Finally, consider a third key.

k3=[−11]

The resulting dot product is

q⊤k3=(2)(−1)+(1)(1)=−2+1=−1

Notice what is happening inside each dot product. Every coordinate produces a contribution. When the corresponding coordinates have the same sign, their product is positive. When they have opposite signs, their product is negative. We then add these contributions together. The resulting scalar measures the net agreement between the two vectors, accounting for both agreement and disagreement across their coordinates. Once again, this is our first mathematical bridge appearing in a new form. The dot product is an accumulation of individual contributions. Some contributions cancel, while others reinforce one another. For a query and key containing dk coordinates, we can write the dot product as

sij=qi⊤kj=∑r=1dkqi,rkj,r

Let us carefully understand every index in this expression. The index i identifies the token requesting information. The index j identifies the token whose key is being examined. The index r identifies an individual coordinate within the query and key vectors. The quantity qi,r is the r-th coordinate of the query belonging to token i, while kj,r is the r-th coordinate of the key belonging to token j. For a particular query, we can simplify the notation by temporarily dropping the index i.

sj=∑r=1dkqrkj,r

The result sj is not a vector. It is a single real number describing the compatibility between the current query and key j. If dk=128, we perform 128 coordinate-wise multiplications and sum their results to obtain one compatibility score. We repeat this process for every available key. If there are N=10,000 keys, we obtain 10,000 compatibility scores for the current query.

s=[s1s2⋮sN]

These scores represent the model's learned preferences over the information available to it. However, a higher dot product should not automatically be interpreted as greater semantic similarity in the ordinary human sense. The query and key projections are learned for the model's task. They may represent positional relationships, grammatical patterns, algorithmic relationships, or other features that are useful for prediction. The dot product simply measures compatibility within the learned query-key space.

Why attention weights are normalized

We now have scores describing how useful each available piece of information might be. But we still have not answered our original question: how much of each value vector should participate in the attention output? Consider the three raw compatibility scores we obtained earlier.

(s1,s2,s3)=(3,1,−1)

One possibility would be to directly use these scores as weights.

o=3v1+v2−v3

This is mathematically valid, and some alternative attention mechanisms use signed or unnormalized weights. However, let us consider what this means for the particular kind of information retrieval mechanism we are trying to construct. A negative weight does not merely prevent information from being retrieved. It subtracts the corresponding value vector from the output. If the third token is irrelevant to our current computation, do we necessarily want to subtract its information? Perhaps we simply want it to contribute less. Furthermore, a score of 3 would multiply a value vector by three, potentially changing the magnitude of the information we retrieve.

A large score would therefore have two meanings simultaneously. It would indicate that the information is relevant, and it would amplify the magnitude of the retrieved information. We would prefer to have a clearer separation between these two responsibilities. We want the query-key comparison to determine which information should be retrieved, while allowing the value vectors and subsequent projections to determine the content and scale of that information. This suggests that instead of interpreting the raw scores as arbitrary multiplication factors, we could interpret them as relative proportions of the information to retrieve. Imagine that the model has one unit of attention to distribute among the available tokens.

If the first token deserves 70% of the attention, the second deserves 20%, and the third deserves 10%, we obtain

o=0.7v1+0.2v2+0.1v3

The coefficients are now non-negative and sum to one.

0.7+0.2+0.1=1

We have transformed arbitrary compatibility scores into a controlled weighted average. This is why we begin thinking about quantities that are positive and sum to one. The goal is not to produce probabilities merely because probabilities are mathematically familiar. The goal is to construct a mechanism that distributes influence among competing pieces of information while maintaining a controlled total weight. We can denote these normalized weights by p1,p2,…,pN. We would like them to satisfy

pj≥0

and

∑j=1Npj=1

The first condition ensures that each coefficient represents a non-negative share of attention. The second ensures that the total share of attention is exactly one. We would also like the transformation to preserve the ordering of the original scores.

sa>sb⟹pa>pb

If one key receives a higher compatibility score than another, its value should receive a greater coefficient in the weighted combination. These three conditions describe a useful design for attention, rather than a mathematical law that every possible attention mechanism must obey. Other designs are possible. We could use independent gates, signed weights, sparse selection, or entirely different normalization schemes. However, ordinary softmax attention deliberately chooses this particular structure because it provides a smooth and controlled way of mixing information. Let us see why having a fixed total coefficient is useful. Suppose that every value vector has a magnitude no greater than some constant M.

‖vj‖2≤M

Our attention output is

o=∑j=1Npjvj

Using the triangle inequality, we obtain

‖∑j=1Npjvj‖2≤∑j=1N‖pjvj‖2

Because the coefficients are non-negative,

‖pjvj‖2=pj‖vj‖2

Therefore,

‖o‖2≤∑j=1Npj‖vj‖2≤∑j=1NpjM=M∑j=1Npj=M

Consequently,

‖o‖2≤maxj‖vj‖2

This is a surprisingly useful property. Regardless of how many value vectors participate in the weighted average, the magnitude of the attention head's weighted value output cannot exceed the magnitude of the largest value vector. This does not mean that the output of an entire Transformer layer is bounded in the same way. The output projection and residual connection can subsequently change its magnitude. But at the level of the attention-weighted combination, normalization provides a meaningful constraint. We have prevented the number of tokens, by itself, from introducing an arbitrary multiplicative increase in the magnitude of the retrieved information.

Compare this with an unnormalized sum. If all N value vectors are identical to v, then

∑j=1Nv=Nv

Their magnitude increases linearly with N. But if we combine those same vectors using normalized attention weights,

∑j=1Npjv=v∑j=1Npj=v

The resulting vector remains exactly v. This is a direct connection to our discussion of alignment. Perfectly aligned contributions ordinarily accumulate linearly. A normalized weighted average controls that accumulation by requiring the total weight to remain fixed.

Variance and the effective number of tokens

We can understand this even more deeply through variance. Suppose we examine one coordinate of the value vectors and represent its values as random variables X1,X2,…,XN. The corresponding coordinate of the attention output becomes

O=∑j=1NpjXj

For this calculation, we treat the weights as fixed and assume the random variables have zero mean, equal variance σv2, and no pairwise correlation. The variance of a weighted sum is then

Var(O)=σv2∑j=1Npj2

If the attention is distributed uniformly, then pj=1/N. Substituting,

Var(O)=σv2∑j=1N(1N)2=σv2N1N2=σv2N

Taking the square root gives

Std(O)=σvN

This is the counterpart of the square-root accumulation law we discovered earlier. An unnormalized sum of independent quantities grows in standard deviation as N. A uniform average shrinks in standard deviation as 1/N. Now consider the opposite situation, where one token receives all the attention.

p1=1,p2=⋯=pN=0

Then

O=X1

and

Var(O)=σv2

The magnitude of the selected contribution is preserved because it is no longer averaged together with unrelated contributions. This reveals another reason selective attention is valuable. If useful information is contained in one value vector, averaging it with thousands of unrelated vectors may dilute that information. By concentrating the attention weights on the relevant vectors, the model can preserve more of their distinctive features. We can express this using a quantity called the effective number of contributing elements:

Neff=1∑jpj2

For uniform attention over N tokens,

Neff=N

For attention concentrated entirely on one token,

Neff=1

Our earlier variance equation can therefore be rewritten as

Var(O)=σv2Neff

Under our simplifying assumptions, the more concentrated the attention distribution becomes, the fewer effectively independent contributions are being averaged. Real attention is more complicated because the weights depend on the input, and the values can be correlated. Nevertheless, this equation gives us a useful statistical picture of what happens when attention changes from diffuse to selective. Attention is not merely assigning importance scores. It is changing how the available information participates in an accumulation process.

#dl-notes