ENع
←Transformers
Lesson 17 · Deep learning

Attention and transformers

14 min11 steps5 questionsIntermediate
About this lesson

A transformer lets every token look at every other token and decide how much each one matters. Follow one worked example of self-attention on "the cat sat", with real numbers: queries, keys and values, dot-product scores, scaling by √d_k, softmax weights and the weighted sum. Then see how heads, feed-forward layers, stacked blocks and positions turn that one step into the model behind GPT.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 17 · Interactive
01 / 11

Tokens become vectors

A transformer reads text as tokens, here "the cat sat". Each token starts as an embedding: a list of numbers for its meaning. Ours have 2 numbers. Alone, each vector ignores its neighbours: "sat" does not know who sat.

token   embedding
the     [1, 0]
cat     [0, 1]
sat     [1, 1]

each vector was made for the word alone,
without looking at the other words
Loading figure…
or ← →
Read the lesson step by step
  1. Tokens become vectors

    A transformer reads text as tokens, here "the cat sat". Each token starts as an embedding: a list of numbers for its meaning. Ours have 2 numbers. Alone, each vector ignores its neighbours: "sat" does not know who sat.

    token   embedding
    the     [1, 0]
    cat     [0, 1]
    sat     [1, 1]
    
    each vector was made for the word alone,
    without looking at the other words
  2. Query, key and value

    Three learned weight matrices turn every embedding into three new vectors: a query (what am I looking for?), a key (what do I offer?) and a value (what do I pass on?). The query of "sat" is [−1, 1].

    query  q = x · W_Q     W_Q = [[0, 1], [-1, 0]]
    key    k = x · W_K     W_K = [[1, 0], [0, 2]]
    value  v = x · W_V     W_V = [[0, 1], [1, 0]]
    
    token   key       value
    the     [1, 0]    [0, 1]
    cat     [0, 2]    [1, 0]
    sat     [1, 2]    [1, 1]
    query of sat: [−1, 1]
  3. Score: query · key

    Attention compares the query of "sat" with every key using a dot product: multiply matching numbers, then add. For "cat": [−1, 1] · [0, 2] = 2. The scores are the −1, cat 2, sat 1. Bigger means a better match.

    s = [dot(q, k) for k in K]
    the  [−1, 1] · [1, 0]  = −1×1 + 1×0 = −1
    cat  [−1, 1] · [0, 2]  = −1×0 + 1×2 = 2
    sat  [−1, 1] · [1, 2]  = −1×1 + 1×2 = 1
  4. Scale by √d_k

    Each score is divided by √d_k, the square root of the key length. Here d_k = 2, so we divide by 1.41: −0.71, 1.41, 0.71. With long vectors, unscaled scores grow huge and learning slows down.

    d_k = len(q) = 2        sqrt(2) = 1.414
    the  −1 / 1.414 = −0.71
    cat   2 / 1.414 = 1.41
    sat   1 / 1.414 = 0.71
    
    the original transformer: d_k = 64, so it divides by 8
  5. Softmax: scores to weights

    Softmax turns the scores into weights: raise e to the power of each score, then divide each by their sum. The weights are positive and add up to 1: the 0.07, cat 0.62, sat 0.31. So "sat" attends mostly to "cat".

    e = [exp(x) for x in s]
    w = [x / sum(e) for x in e]
    the  exp(−0.71) = 0.49   / 6.63 = 0.07
    cat  exp(1.41) = 4.11   / 6.63 = 0.62
    sat  exp(0.71) = 2.03   / 6.63 = 0.31
    
    sum of weights = 0.07 + 0.62 + 0.31 = 1.00
  6. Mix the values

    The new vector for "sat" is the weighted sum of the values: 0.07×[0, 1] + 0.62×[1, 0] + 0.31×[1, 1] = [0.93, 0.38]. It now carries information from "cat". That is self-attention.

    return mix(w, V)
      0.07 × [0, 1]
      0.62 × [1, 0]
      0.31 × [1, 1]
    = [0.93, 0.38]
    
    "sat" before: [1, 1]   after: [0.93, 0.38]
  7. Every token at once

    Every token does the same with its own query, all at the same time. Written with matrices it is one formula: softmax(QKᵀ / √d_k) V. No token waits for the one before it, so the work runs in parallel on the hardware.

    Attention(Q, K, V) = softmax(Q Kᵀ / √d_k) V
    
    weights, one row per query:
            the   cat   sat
    the     0.11  0.45  0.45
    cat     0.25  0.50  0.25
    sat     0.07  0.62  0.31
  8. Many heads

    One attention finds one kind of match. The original transformer runs 8 attention heads side by side, each with its own weights and vectors of 64 numbers instead of 512. Their outputs are joined and mixed back into one vector per token.

    d_model = 512   heads h = 8
    d_k = d_model / h = 512 / 8 = 64
    
    each head: its own W_Q, W_K, W_V
    join the 8 outputs (8 × 64 = 512 numbers),
    then one more matrix W_O mixes them
  9. A transformer block

    A block is attention followed by a small feed-forward network applied to each token. Each part adds its result to its input (a residual connection) and then normalises. The original stacks 6 blocks; GPT-3 stacks 96.

    x = LayerNorm(x + Attention(x))
    x = LayerNorm(x + FeedForward(x))
    
    feed-forward: 512 -> 2048 -> 512 numbers, per token
    blocks: 6 (original), 96 (GPT-3)
  10. Where is each word?

    Attention alone ignores word order: shuffle the words and each one gets the same mix as before. So a position signal is added to every embedding first. The original transformer used sine and cosine waves of different lengths.

    input = embedding + position signal
    
    PE(pos, 2i)   = sin(pos / 10000^(2i / d_model))
    PE(pos, 2i+1) = cos(pos / 10000^(2i / d_model))
    
    BERT and GPT-2 learn their position vectors instead
  11. Predict the next token

    A language model such as GPT stacks only these blocks, with a mask so each token sees only earlier ones. The last vector becomes a probability for every token in the vocabulary. A likely one, "on", is added, and it repeats.

    prompt      the cat sat
    mask        each token attends to itself and earlier ones
    last vector -> one probability per vocabulary token
    pick        "on"
    text        the cat sat on ...

Quiz Unlocks after the last step.