Papa Programmer
Lesson 06 of 20

Attention, step by step

10 min read

Optional

Why a token needs the others

Read this sentence: "The animal didn't cross the street because it was too tired." The word "it" means the animal. Change "tired" to "wide", and "it" means the street. The embedding for "it" is the same in both sentences, so the model needs a way to bring in information from the other words. AttentionThe step in a transformer that lets each token gather information from earlier tokens. Each token compares its query with the keys of earlier tokens and takes a weighted mix of their values. is that way. It is the step that makes the TransformerThe model design used by nearly all LLMs. It stacks many identical blocks, and each block has an attention step and a feed-forward step. Google researchers introduced it in 2017. work.

Queries, keys and values

Attention turns each token's vector into three new vectors. Three learned tables of numbers, called weight matrices, do the conversion.

  • Query. What this token is looking for.
  • Key. What this token offers to others.
  • Value. The information this token passes on when it is chosen.

The model then follows four steps for every token.

  1. ProjectTurn every token into a query, a key and a value.
  2. CompareMultiply this token's query by each earlier token's key to get a score.
  3. NormaliseRun softmax over the scores, so the weights add up to 1.
  4. MixAdd up the earlier tokens' values, each multiplied by its weight.
How one token gathers information from earlier tokens

The result is a new vector for the token. It holds the token's own meaning plus a blend of what it found in the earlier tokens.

Attention in NumPy

The program below runs attention for three tokens. The weight matrices hold random numbers, so the scores have no meaning yet. In a trained model, training sets these matrices, and the weights then point at useful words.

python
import numpy as np

np.set_printoptions(precision=2, suppress=True)
rng = np.random.default_rng(0)

tokens = ["The", "cat", "sat"]
d = 4
x = rng.normal(size=(len(tokens), d))

W_q, W_k, W_v = (rng.normal(size=(d, d)) for _ in range(3))
Q, K, V = x @ W_q, x @ W_k, x @ W_v

scores = Q @ K.T / np.sqrt(d)
future = np.triu(np.ones((len(tokens), len(tokens)), dtype=bool), k=1)
scores[future] = -np.inf

weights = np.exp(scores - scores.max(axis=1, keepdims=True))
weights /= weights.sum(axis=1, keepdims=True)
print(weights)

output = weights @ V
print(output.shape)

It prints a table of weights and the shape of the output:

text
[[1.   0.   0.  ]
 [0.61 0.39 0.  ]
 [0.05 0.01 0.94]]
(3, 4)

Read the table one row at a time. Row 1 is "The", row 2 is "cat" and row 3 is "sat". Each row adds up to 1. "The" can only look at itself, so its weight on itself is 1. "cat" splits its attention, 0.61 on "The" and 0.39 on itself. The output has the same shape as the input: one vector of 4 numbers for each token.

Why divide by the square root

The line Q @ K.T / np.sqrt(d) divides every score by the square root of the vector length. Without this step, long vectors give large scores, and softmax then puts almost all the weight on one token. The division keeps the scores in a range where softmax can spread the weight.

The mask hides the future

The lines with future set every score above the diagonal to minus infinity, and softmax turns minus infinity into a weight of 0. This is the causal mask. It stops a token from looking at tokens that come after it.

The mask matters most in training. The model reads a whole sentence at once and predicts every next token in one pass. Without the mask, each position could see the answer it is meant to predict.

Many heads at once

One attention step can only track one kind of link at a time. A transformer runs several attention steps side by side, called heads, and joins their results. Each head has its own weight matrices and can learn a different kind of link, such as which noun a pronoun refers to, or which word a verb belongs to. GPT-2's smallest version has 12 heads in each block, and each head works with vectors of 64 numbers.

Each token looks backAttention mixes information from earlier tokens into each token.
Query meets keyThe match between one token's query and another's key sets the weight.
The mask hides the futureA token never sees the tokens after it, so training stays honest.

Your reading position is saved

0%

0 of 20 complete

Contents

Learning tools