ContentsThe library

The Mathematics of Attention

Why Attention Needs Three Matrices, Not One

Attention projects each token into query, key and value spaces. Here is what breaks if you compare token vectors directly instead.

Attention is usually introduced with its final formula, and the three matrices

WQW_Q, WKW_K and WVW_V arrive already named, as though the names explained

themselves. They do not. The useful question is what goes wrong without them,

and the answer is specific enough to derive.

The version without any matrices

Start with what you have. A sequence of LL tokens, each already a vector of

width dmodeld_{model}, stacked into a matrix XX of shape (L,dmodel)(L, d_{model}).

You want each token to gather information from the others, weighted by how

relevant they are. Relevance between two vectors has an obvious candidate: the

dot product. Large when they point the same way, near zero when they are

unrelated. So the simplest possible mechanism is to score every pair directly

and use those scores to mix the tokens.

FIG 1Attention with no learned parameters
the input tokens, one row each, shape (L, d_model)
the raw score for every ordered pair of tokens, shape (L, L)
those scores turned into weights that sum to one along each row
Score every pair of tokens by their dot product, normalise the scores into weights, and mix. No parameters anywhere.

This runs. It produces output of the right shape. It is also broken in three

separate ways, and each of the three matrices exists to fix exactly one of them.

Problem one: the scores are symmetric

S=XX⊤S = XX^\top means Sij=xi⋅xjS_{ij} = x_i \cdot x_j, and the dot product does not care

about order. So Sij=SjiS_{ij} = S_{ji}, always, as an algebraic fact rather than a

tendency. Any matrix of the form MM⊤MM^\top is symmetric by construction.

That forces every attention relationship to be mutual. How much the word it

attends to the cat must equal how much the cat attends to it.

Almost nothing in language works that way. A pronoun needs its antecedent

badly; the antecedent has little use for the pronoun. A verb needs its subject;

the subject is not especially interested in the verb. An adjective modifies a

noun in one direction only. Relevance is directional, and a symmetric score

matrix cannot represent direction at all.

FIG 2What symmetry forces
thecatit
the0.70.20.1
cat0.20.70.1
it0.10.10.8
With a single projection the two marked cells are the same number by construction. The row for 'it' cannot lean on 'cat' unless 'cat' leans back equally hard.

Two separate projections fix this. Send the input through one matrix to ask a

question and through a different matrix to answer it:

Q=XWQ,K=XWK,S=QK⊤Q = X W_Q, \qquad K = X W_K, \qquad S = Q K^\top

Now Sij=(xiWQ)⋅(xjWK)S_{ij} = (x_i W_Q) \cdot (x_j W_K), and swapping ii and jj gives

(xjWQ)⋅(xiWK)(x_j W_Q) \cdot (x_i W_K), which is a different number whenever

WQ≠WKW_Q \neq W_K. The constraint is gone. The model can learn that it should

look hard at cat while cat largely ignores it.

The names follow from the roles rather than the other way round. The query is

what a token is looking for. The key is what a token advertises about itself.

They are separate because asking and being asked are separate.

Problem two: nothing can be learned

The parameter-free version has no way to improve. XX⊤XX^\top is a fixed function

of the input. If the useful notion of relevance for a task is not raw vector

similarity, and it usually is not, there is no mechanism by which the model

could discover that.

This is the deeper reason for the projections, and it is easy to miss behind

the symmetry argument. The dot product is fixed. The softmax is fixed. Neither

has a single parameter. **Everything an attention head knows is stored in its

projection matrices.** They are the entire learnable content of the mechanism.

What they learn is a subspace to compare in. WQW_Q and WKW_K together decide

which directions of the input space count toward relevance and which are

ignored, because the score can be rewritten to make the pairing explicit:

FIG 3The two matrices act as one bilinear form
the score matrix the head computes, before scaling and softmax
a single d_model by d_model matrix, often written W_QK, which is what the head has actually learned. The naive version is the case where this is the identity
The naive version is the special case where the middle matrix is the identity. Learning that matrix is the whole point of the query and key projections.

Written this way the naive attempt is revealed as a particular, and arbitrary,

choice: the one where the middle matrix is II. There is no reason the identity

should be the right similarity measure for a language task, and the projections

are simply the machinery for learning something better.

Problem three: being found and being useful are different

The third flaw is the least obvious and the most interesting.

In the naive version, the same vector xjx_j does two jobs. It is matched

against (it determines whether token jj gets attended to) and it is passed on

(it is what token ii receives). Those are different jobs with different

requirements, and one vector cannot be optimised for both.

Consider a token whose useful contribution is a piece of factual content, but

which is found by matching on grammatical role. The features that make it

findable and the features that make it worth having need not overlap at

all. Forcing them into one vector means every improvement in retrievability

costs something in content, and the reverse.

The value projection separates them:

V=XWV,out=AVV = X W_V, \qquad \mathrm{out} = A V

Now WQW_Q and WKW_K shape what makes a token findable, while WVW_V shapes what

a token contributes once found. They can be optimised independently, because

they are.

The dictionary analogy usually offered for attention is worth stating carefully,

because the loose version obscures the point. In a dictionary you look up a

query, compare it against keys, and receive the associated value. The part worth

noticing is that the key and the value are stored separately. A dictionary in

which the key and the value were forced to be the same object would be nearly

useless, and that is precisely what the parameter-free version is.

Putting it together

The three matrices, assembled into the mechanism they exist to make:

FIG 4One attention head, end to end
The three paths out of X are the whole mechanism. Two of them decide who talks to whom; the third decides what is said.

The full expression, with the scaling factor that the next lesson derives:

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right) V

Why the query and key spaces can be narrow

One detail that looks arbitrary in the original paper: with a model width of

512 and eight heads, each head uses dk=64d_k = 64. The queries and keys are

projected into a space eight times narrower than the input.

This is not a compromise forced by memory. It follows from where those vectors

are used. Queries and keys appear only inside a dot product, and that dot

product collapses them to a single number. Their width therefore sets the rank

of the learned middle matrix WQWK⊤W_Q W_K^\top, which is at most dkd_k, and

nothing else. No downstream component ever sees a query or a key.

The value projection is different. Values are summed and passed forward, so

dvd_v has to line up with what the rest of the block expects. In practice the

two are set equal for convenience, but they are constrained by different things,

and only one of them is free.

FIG 5
ProjectionWhere its output is usedWhat its width controls
Inside the dot product onlyRank of the learned similarity
Inside the dot product onlyRank of the learned similarity
Summed and passed to the next blockWidth of the information carried forward

What to hold on to

Three matrices, three distinct failures repaired. Splitting query from key makes

relevance directional and makes it learnable. Splitting value from both means a

token's findability and its contribution stop competing for the same

coordinates.

The next lesson takes the one remaining unexplained term in the formula, the

division by dk\sqrt{d_k}, and shows that it falls straight out of the variance

of a dot product between independent vectors.

Recap

  • Attention uses three projections because matching and retrieving are different jobs: queries and keys decide how relevant two tokens are, while values carry the content that actually gets passed on.
  • Without separate query and key matrices the score matrix would be symmetric, forcing the relevance of token A to token B to equal the relevance of B to A, which is false for almost every linguistic relationship.
  • The three projection matrices are the only learned parameters inside an attention head; the dot product and the softmax have none.

This is the reading half

Starting the course gives you your own copy of it. Every idea on every page has problems standing under it, marked with a reason rather than a tick, and any sentence you do not believe can be opened and argued with. None of that can happen on a page nobody owns.

The contents

NextThe Scaling Factor →

The rest of this course

  1. 01Why Attention Needs Three Matrices, Not Oneyou are here
  2. 02Where the Square Root of dkd_k Comes Fromopening only
  3. 03Why Softmax and Not Some Other Normalisationopening only
  4. 04One Weighted Average Is Not Enoughopening only
  5. 05Attention Cannot See Order, So Order Has to Be Addedopening only
  6. 06The Skip Connection Is the Main Roadopening only
  7. 07Why Transformers Normalise Across Features and Not Across the Batchopening only
  8. 08The Half of the Transformer That Does Not Move Informationopening only

Read alongside