Attention and Transformers

How attention lets each token in a text pull in information from other tokens, how transformers stack it, and what that means when you write prompts.

14 minLesson 3 of 6
On this page
  1. How attention works
  2. A worked example with two-number vectors
  3. From one attention step to a transformer
  4. Pitfalls
  5. What this changes in practice
  6. Check yourself
  7. What to practise next

Attention is the mechanism that lets a language model update the meaning of each token using the other tokens in the text. A transformer is a model built from many repeated layers of attention and small neural networks, and it is the design behind most current LLMs. Without attention, the vector for a word like "it" would carry almost no information, because the word alone does not say what it refers to.

After tokenization, every token is turned into a vector, which is a list of numbers that stands for the token's meaning. In "Sam made soup and ate it", the vector for "it" is the same as in any other sentence until attention lets it collect information from "soup". Everything a model does with context, such as resolving references, following instructions and using an example you gave, depends on this step.

How attention works

Each token produces three vectors from its current vector:

  • A query, which describes what the token is looking for. For "it" this is roughly "a thing that was mentioned earlier".
  • A key, which describes what the token offers to others. For "soup" this is roughly "I am a thing, and a food".
  • A value, which is the information the token hands over when another token picks it.

A token compares its query with the key of every token it can see, and a better match gives a higher score. The scores are converted into shares that add up to 1, and the token then collects a blend of all the values, weighted by those shares. The result replaces the token's vector, so the vector for "it" now contains information taken mostly from "soup".

Sam made soup and ate it 0.00 0.04 0.80 0.01 0.11 0.04
Attention from "it" to the words it can see. Thicker lines mean larger shares, which are computed in the next section.

A worked example with two-number vectors

Real vectors have thousands of numbers, but the mechanism is the same with two. In this example the first number means "is a thing" and the second means "is a person". A score is the dot product of a query and a key, which means multiplying the numbers in matching positions and adding the results. The query for "it" is [2, -1], so it wants a thing and is put off by a person.

Attention for the word "it"Use the arrows or ← → keys
for each visible word w:  score[w] = dot(query, key[w])weights = softmax(scores)output = sum of weights[w] * value[w]
  1. word
    0Sam
    1made
    2soup
    3and
    4ate
    5it
    key
    00, 2
    10.5, 0
    22, 0
    30, 0
    41, 0
    50.5, 0
    query
    [2, -1]

    1Each word has a key. "Sam" is mostly a person and "soup" is mostly a thing. The query for "it" is [2, -1].

  2. word
    0Sam
    1made
    2soup
    3and
    4ate
    5it
    key
    00, 2
    10.5, 0
    22, 0
    30, 0
    41, 0
    50.5, 0
    score
    0-2
    1
    2
    3
    4
    5
    query
    [2, -1]

    2The score for Sam is 2 × 0 + (−1) × 2 = −2, because a person is the opposite of what "it" wants.

  3. word
    0Sam
    1made
    2soup
    3and
    4ate
    5it
    key
    00, 2
    10.5, 0
    22, 0
    30, 0
    41, 0
    50.5, 0
    score
    0-2
    1
    24
    3
    4
    5
    query
    [2, -1]

    3The score for soup is 2 × 2 + (−1) × 0 = 4, which is a strong match.

  4. word
    0Sam
    1made
    2soup
    3and
    4ate
    5it
    key
    00, 2
    10.5, 0
    22, 0
    30, 0
    41, 0
    50.5, 0
    score
    0-2
    11
    24
    30
    42
    51
    query
    [2, -1]

    4The other scores are computed the same way and come out as 1 for "made", 0 for "and", 2 for "ate" and 1 for "it" itself.

  5. word
    0Sam
    1made
    2soup
    3and
    4ate
    5it
    score
    0-2
    11
    24
    30
    42
    51
    e^score
    00.14
    12.72
    254.6
    31
    47.39
    52.72
    total
    68.56

    5Softmax first raises e to the power of each score. Every number becomes positive and the gaps grow, so the best match pulls ahead. The total is 68.56.

  6. word
    0Sam
    1made
    2soup
    3and
    4ate
    5it
    weight
    00
    10.04
    20.8
    30.01
    40.11
    50.04
    total
    68.56

    6Softmax then divides each number by the total, so the shares add up to 1. Soup gets 54.6 ÷ 68.56 = 0.80.

  7. word
    0Sam
    1made
    2soup
    3and
    4ate
    5it
    weight
    00
    10.04
    20.8
    30.01
    40.11
    50.04
    value
    00, 1
    10, 0
    21, 0
    30, 0
    40.5, 0
    50, 0

    7Next the values are blended. Only soup [1, 0], ate [0.5, 0] and Sam [0, 1] carry anything. The thing part is 0.80 × 1 + 0.11 × 0.5 = 0.85, and the person part is about 0.00.

  8. word
    0Sam
    1made
    2soup
    3and
    4ate
    5it
    weight
    00
    10.04
    20.8
    30.01
    40.11
    50.04
    output for it
    [0.85, 0.00]

    8The new vector for "it" is about [0.85, 0.00], which means a thing and not a person. It now carries meaning taken from soup, and later layers can use it.

1 / 8

Here is the same computation as code for one word. Real models also divide each score by the square root of the key vector's length before the softmax. Without that, the dot products of long vectors become large and the softmax puts almost all of the share on one word. The step is left out here because the vectors have only two numbers.

const dot = (a, b) => a.reduce((sum, x, i) => sum + x * b[i], 0);
 
function softmax(scores) {
  const biggest = Math.max(...scores); // subtract the max so exp() cannot overflow
  const exps = scores.map((s) => Math.exp(s - biggest));
  const total = exps.reduce((a, b) => a + b, 0);
  return exps.map((e) => e / total);
}
 
function attend(query, keys, values) {
  const weights = softmax(keys.map((k) => dot(query, k))); // match, then share
  const out = new Array(values[0].length).fill(0);
  weights.forEach((w, j) => {
    values[j].forEach((v, i) => { out[i] += w * v; }); // blend the values
  });
  return { weights, out };
}
 
const keys = [[0, 2], [0.5, 0], [2, 0], [0, 0], [1, 0], [0.5, 0]];
const values = [[0, 1], [0, 0], [1, 0], [0, 0], [0.5, 0], [0, 0]];
attend([2, -1], keys, values).out; // about [0.85, 0.00]
import math
 
def dot(a, b):
    return sum(x * y for x, y in zip(a, b))
 
def softmax(scores):
    biggest = max(scores)  # subtract the max so exp() cannot overflow
    exps = [math.exp(s - biggest) for s in scores]
    total = sum(exps)
    return [e / total for e in exps]
 
def attend(query, keys, values):
    weights = softmax([dot(query, k) for k in keys])  # match, then share
    out = [0.0] * len(values[0])
    for w, value in zip(weights, values):
        for i, v in enumerate(value):
            out[i] += w * v  # blend the values
    return weights, out
 
keys = [[0, 2], [0.5, 0], [2, 0], [0, 0], [1, 0], [0.5, 0]]
values = [[0, 1], [0, 0], [1, 0], [0, 0], [0.5, 0], [0, 0]]
attend([2, -1], keys, values)[1]  # about [0.85, 0.00]

The queries, keys and values above were typed in by hand. In a real model each one is produced by multiplying the token's current vector by a matrix of numbers that was learned during training. Nobody writes rules such as "pronouns look for things". Because a token's vector changes as it passes through the layers, the same word can ask different questions in different sentences.

From one attention step to a transformer

A transformer repeats one block many times, and each block does two things to every token. The first is attention, which gathers information from the tokens the current token can see, as described above. The second is a feed-forward network, a small neural network that transforms each token's vector on its own, without looking at other tokens. Each block adds its result to the existing vector instead of replacing it, so information from earlier layers is kept. After the last block, the vector at the final position is turned into probabilities for the next token, and the loop described in What Is an LLM picks one.

Multiple heads

Each block runs several attention steps side by side, which are called heads, and each head has its own learned matrices. This lets a block track several relationships at once, such as which noun a pronoun refers to and which word a verb belongs to. A few heads have a job that people can describe, but most do not, and the model does not need them to.

Attending only to earlier tokens

In the models that generate text, a token can attend to itself and to earlier tokens but never to later ones. This holds during training as well, because the model is trained to predict each next token and must not see the answer. Some other transformer models, such as those that produce embeddings for search, let every token see every other token in both directions, but they are not the ones that generate text. The consequence for a generating model is that when you write a prompt, a word can only use clues that come before it.

Word order

Attention by itself treats the text as a set of tokens, so it cannot tell "dog bites man" from "man bites dog". To fix this, the model mixes information about each token's position into its vector before the first block.

Cost of attention

With n tokens, each token compares itself with up to n others, so one attention step makes about n²/2 comparisons. Doubling the length of the text makes the work about four times larger, and this is one of the reasons why the context window is limited.

ApproachTimeSpaceWhy
Read a whole textO(n²)O(n²)Every token scores every earlier token. The space is for storing the scores, and optimised implementations compute them in blocks to avoid storing them all.
Add one new tokenO(n)O(n)Models keep the keys and values of earlier tokens in memory, so a new token only has to score against them.

Pitfalls

What this changes in practice

Because every token builds its meaning from the tokens before it, the order of a prompt matters. State the task, the definitions and the rules before the material that they apply to, and keep related information close together. When a reference could point to more than one thing, as with "it" or "they", name the thing instead, because the model has to guess otherwise and the guess is based on what is common in its training text. Finally, keep the prompt to the information that the task needs, since every extra token takes part in every attention step.

Try it: Be the attention head

For each sentence, decide which earlier word the last word should attend to most and which one second. Give rough shares that sum to about 1, and name the clue that decides it.

Show a sample answer
  1. them: keys about 0.7 and grabbed about 0.15, with the rest small. The word "them" is plural, and "keys" is the only plural thing in the sentence.
  2. laughed: he about 0.5, Ben about 0.3 and joke about 0.1. The word "laughed" needs someone who does the laughing, and "he" points to Ben, whose meaning an earlier layer may already have moved into "he".
  3. slippery: glass and shelf at around 0.4 each. Either could be slippery, so the model may split its attention or lean on what is common in its training text.

When the text does not decide the answer, no attention pattern can make it certain, and the fix is to rewrite the text so that it does.

Check yourself

Quick check

A query is [1, 3] and a key is [2, 1]. What is the attention score?

Why does attention apply softmax to the scores?

Text A has 1,000 tokens and text B has 2,000. Roughly how much more work is one attention step on B?

Why can it help to put an instruction before the document it applies to, instead of after it?

What to practise next

Compute attention weights, including the square-root scaling, in Pronoun Looks Back. Then Training and Fine-Tuning explains how the numbers behind queries, keys and values are learned.