Docsity

scaling in data science, Slides of Advanced Data Analysis

Toggle sidebar
bg1
Scaled Dot-Product Attention
A Case Study in Vectors, Dot Products and Matrix Multiplication
1 The Problem Attention Solves
Consider the two sentences
“The bank approved the loan.” “The bank is beside the river.”
The word bank does not carry the same contextual meaning in both cases. A static repre-
sentation assigns bank a single vector, and that vector cannot be sensitive to the surrounding
words. What we would like instead is a mechanism that allows the representation of bank to
absorb information from loan in the first sentence and from river in the second.
This gives us the operational question that self-attention answers:
For the current token, which other tokens should I attend to, and by how
much?
Answering it requires two distinct capabilities:
1. a way of scoring how relevant one token is to another;
2. a way of combining the information of the relevant tokens.
The first is performed by dot products; the second by a weighted linear combination. Both are
elementary linear algebra.
2 Query, Key and Value: The Intuition
Imagine walking into a library and asking for material on machine learning. Three conceptually
different objects are involved.
Component Question it answers Library analogy
Query (Q) What am I looking for? Your stated information need
Key (K) What kind of information do I offer? The index card or tag on a book
Value (V) What information do I actually provide? The contents of the book
The single most important conceptual distinction:
Qand Kdetermine relevance.Vcarries the information.
A librarian matches your request against the index tags; the tags are not the information you
leave with. Likewise, attention scores are computed from Qand Kalone, and only afterwards
is Vused to build the output.
1
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download scaling in data science and more Slides Advanced Data Analysis in PDF only on Docsity!

Scaled Dot-Product Attention

A Case Study in Vectors, Dot Products and Matrix Multiplication

1 The Problem Attention Solves

Consider the two sentences

“The bank approved the loan.” “The bank is beside the river.”

The word bank does not carry the same contextual meaning in both cases. A static repre- sentation assigns bank a single vector, and that vector cannot be sensitive to the surrounding words. What we would like instead is a mechanism that allows the representation of bank to absorb information from loan in the first sentence and from river in the second. This gives us the operational question that self-attention answers:

For the current token, which other tokens should I attend to, and by how much?

Answering it requires two distinct capabilities:

  1. a way of scoring how relevant one token is to another;
  2. a way of combining the information of the relevant tokens.

The first is performed by dot products; the second by a weighted linear combination. Both are elementary linear algebra.

2 Query, Key and Value: The Intuition

Imagine walking into a library and asking for material on machine learning. Three conceptually different objects are involved.

Component Question it answers Library analogy Query (Q) What am I looking for? Your stated information need Key (K) What kind of information do I offer? The index card or tag on a book Value (V ) What information do I actually provide? The contents of the book

The single most important conceptual distinction: Q and K determine relevance. V carries the information.

A librarian matches your request against the index tags; the tags are not the information you leave with. Likewise, attention scores are computed from Q and K alone, and only afterwards is V used to build the output.

2.1 Why three representations of the same token?

Each token starts life as one embedding vector. But the model needs that token to play three different roles simultaneously: it must be able to ask for information, to advertise what it holds, and to supply content. A single vector cannot be optimised for all three roles at once, so the model learns three separate linear maps:

Q = XWQ, K = XWK , V = XWV. (1)

Q, K and V are not three different words and not three different parts of the input. They are three different projections of the same tokens.

The matrices WQ, WK , WV are learned during training. In these notes they are chosen by hand so that all arithmetic remains checkable.

3 The Running Example

3.1 Input

Take two tokens, A and B, each with a 3-dimensional embedding:

X =

∈ R^2 ×^3 , xA = (1, 0 , 1), xB = (0, 2 , 1). (2)

3.2 Weight matrices

We project down to dk = 2 dimensions using

WQ =

 , WK =

 , WV =

each in R^3 ×^2. The shape arithmetic is worth stating explicitly:

(2 × 3) | {z } X

× (3 × 2)

| {z } W

= (2 × 2)

| {z } Q,K,V

Two tokens in, two tokens out; the dimensionality per token changes from 3 to 2, while the number of tokens is untouched. Attention never changes the number of tokens.

4 Computing Q, K and V

4.1 The query matrix

Q = XWQ =

Row A:

Q 11 = 1(1) + 0(0) + 1(1) = 2, (6) Q 12 = 1(0) + 0(1) + 1(1) = 1, (7)

so qA = (2, 1).

5.2 Why the dot product is a reasonable relevance measure

A single scalar simultaneously summarises how aligned two vectors are and how large they are. Alignment of a query with a key is precisely “this key advertises the kind of thing this query is asking for”. Perpendicular vectors score zero (irrelevant); opposing vectors score negative (actively mismatched).

6 All Scores at Once: QKT

6.1 The four dot products, computed individually

With qA = (2, 1), qB = (1, 3), kA = (1, 2), kB = (3, 1):

qA · kA = 2(1) + 1(2) = 4, qA · kB = 2(3) + 1(1) = 7, (17) qB · kA = 1(1) + 3(2) = 7, qB · kB = 1(3) + 3(1) = 6. (18)

Arranged into a grid,

S =

6.2 The same result as one matrix product

Transposing K turns its key rows into columns:

K =

=⇒ KT^ =

and therefore

QKT^ =

= S. (21)

In symbolic form,

QKT^ =

qA · kA qA · kB qB · kA qB · kB

, Sij = qi · kj. (22)

Central lesson. A dot product is a single comparison producing one number. Matrix multiplication performs all such comparisons at once and files them in a table. QKT^ is not a new kind of similarity; it is bookkeeping for n^2 dot products.

6.3 Reading the score matrix

Key A Key B Query A 4 7 Query B 7 6

  • Row i = the token doing the asking.
  • Column j = the token being considered.
  • SAB = 7 reads: how strongly should token A take token B into account?

Note that S is not symmetric in general: how much A cares about B need not equal how much B cares about A, because qA · kB ̸= qB · kA in general. (Here they coincide numerically by accident of our chosen weights.)

7 Scaling by

√ dk

The entries 4, 7 , 7 , 6 are raw scores, not weights. Before normalising them we divide by

dk, where dk is the dimension of the key vectors. Here dk = 2, so

Sscaled =

QKT

7.1 Why divide at all?

If query and key components behave like independent zero-mean, unit-variance random variables, then

q · k =

X^ dk

t=

qtkt (24)

is a sum of dk such terms, with variance growing proportionally to dk and typical magnitude therefore growing like

dk. Dividing by

dk restores unit-scale scores independently of the dimension chosen. The consequence matters. Softmax applied to [2, 1] gives roughly [0. 731 , 0 .269]; applied to [20, 10] it gives roughly [0. 99995 , 0 .00005]. In the second case the distribution is effectively one-hot, the gradients of the softmax are almost zero, and learning stalls.

Magnitude is informative, but uncontrolled magnitude is harmful. Scaling retains the information while preventing saturation.

8 Softmax: From Scores to Weights

For a vector z = (z 1 ,... , zn),

softmax(zi) = ezi Pn j=1 e zj ,^ softmax(zi)^ >^0 ,^

X

i

softmax(zi) = 1. (25)

Softmax is applied row-wise: each token distributes a total attention budget of 1 across all tokens.

8.1 Token A

The scaled scores are (2. 83 , 4 .95), with difference 4. 95 − 2 .83 = 2.12. Since e−^2.^12 ≈ 0 .120,

αAA =

≈ 0. 107 , αAB =

Token A places about 10.7% of its attention on itself and 89.3% on token B.

8.2 Token B

The scaled scores are (4. 95 , 4 .24), with difference 0.71 and e^0.^71 ≈ 2 .028:

αBA =

≈ 0. 670 , αBB =

8.3 The attention matrix

A = softmax

QKT

dk

Every row sums to 1. These, and only these, are the attention weights.

10 The Complete Pipeline

10.1 Step by step

Step 1: Input X =

Step 2: Project Q =

, K =

, V =

Step 3: Score QKT^ =

Step 4: Scale

QKT

Step 5: Softmax A ≈

Step 6: Mix values O = AV ≈

10.2 Diagram

Input embeddings X

WQ WK WV

Q (^) K V

QKT raw scores

divide by

√ dk

softmax (row-wise)

attention weights A

output O = AV

Q and K decide where to look. V is what we take from there.

10.3 The formula

Attention(Q, K, V ) = softmax

QKT

dk

V (42)

This should not be memorised as one object. It is the answer to two questions:

Where should I look? softmax

QKT

dk

What should I take? AV (44)

11 Dot Product versus Cosine Similarity

If we are measuring similarity, why not use cosine similarity, which is standard in retrieval and recommendation?

11.1 The two quantities

q · k = ∥q∥∥k∥ cos θ, cos(q, k) =

q · k ∥q∥ ∥k∥

Cosine similarity is the dot product with magnitude divided out. It asks only are these pointing the same way? The dot product asks are they pointing the same way, and how large are they?

11.2 Magnitude changes the sharpness of attention

Let q 1 = (1, 1) and q 2 = (10, 10). These have identical direction, so cos(q 1 , k) = cos(q 2 , k) for every k: cosine similarity cannot tell them apart. But with k 1 = (1, 1) and k 2 = (1, 0),

scores softmax q 1 [2, 1] [0. 731 , 0 .269] q 2 [20, 10] [0. 99995 , 0 .00005]

The ranking is unchanged, but the concentration of the resulting distribution is completely dif- ferent. Small scores produce diffuse attention; large scores produce near-hard selection. Because WQ and WK are learned, the model can use the norms of Q and K to control this concentration — an expressive capability cosine similarity discards by construction.

11.3 Magnitude can also change the ranking

Take q = (1, 1), k 1 = (3, 0), k 2 = (0. 5 , 0 .5):

dot product cosine k 1 3 0. 707 k 2 1 1. 000

The two criteria disagree outright: the dot product prefers k 1 , cosine prefers k 2.

  1. “Attention outputs are new information.” Each output is a convex combination of existing value vectors.