Lecture 3 of 1419 minInteractiveFree lecture

Attention: how context flows

“It” means the animal in one sentence and the street in the next. Attention is the mechanism that lets each token gather information from the others — see it in action, then learn how queries, keys and values make it work.

In this lecture you will

  • Explain why tokens need information from their context
  • Describe self-attention in terms of queries, keys and values
  • Interpret attention weights for a sentence
  • Explain multi-head attention, causal masking and why attention cost grows with context length

After the last lecture, every token has an embedding — but that embedding is the same wherever the token appears. Bank has one vector whether it follows river or loan. It has one vector whether it refers to an animal, a street or a server. To understand language, each token needs to take its context into account. Attention is how it does that.

The core idea

Self-attention lets every token look at the other tokens in the text and build an updated representation that mixes in what is relevant. After an attention layer, the vector for it in “…because it was too tired” carries information about animal; in “…because it was too wide”, about street.

The magic is that nobody programs these relationships. The model learns, during training, where to look for what — because looking in the right places helps it predict the next token.

See attention at work

Below, the arcs show how strongly the selected word attends to each other word. Start with it, then switch the last word from tired to wide and watch the attention move. Click other words to see different patterns.

InteractiveAttention weights from one word to the restClick a word
Loading visual…

Weights are illustrative of patterns found in trained models. Real models have many heads, each with its own pattern.

Queries, keys and values

How does a token decide where to look? Each token’s vector is transformed, by three learned weight matrices, into three new vectors:

Query (Q)
What this token is looking for — “I am a pronoun; which noun could I refer to?”
Key (K)
What this token offers to others — “I am a noun that could be the subject of the sentence.”
Value (V)
The information this token passes on if another token attends to it.

For a given token, the model compares its query with every token’s key using a dot product. High scores mean a good match. Softmax turns the scores into weights that add up to 1, and the output is the weighted sum of the values. In compact form:

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

The division by dk\sqrt{d_k}, the square root of the key size, keeps scores in a range where softmax still spreads attention sensibly instead of locking onto a single token.

Here is one attention step with real numbers, small enough to follow by hand. The vectors have only three numbers each; in a real model they have hundreds or thousands.

AnimationOne attention step, with numbers
Loading animation…
  1. The query“it” needs context: what does it refer to? A learned matrix turns its embedding into a query vector that encodes what it is looking for.
  2. Keys and scoresEvery token has a key. The dot product of the query with each key is a score: “server” matches best (4.08), while “The” scores only 0.56.
  3. Softmax weightsDividing by √3 (the square root of the key size, 3) and applying softmax turns the scores into weights that add up to 100%: 55% for “server”, 16% for “crashed” and 14% for “it” itself.
  4. Weighted valuesEvery token also offers a value vector. Each value counts in proportion to its weight, so the value of “server” dominates and the rest contribute little.
  5. The new vectorThe weighted sum, [0.59, 0.32, 0.46], becomes the new vector for “it”. More than half of it comes from “server”, so later layers know what “it” refers to.

In matrix form, as in the formula above, attention for all tokens at once is a few large matrix multiplications — exactly the kind of work GPUs do extremely fast and in parallel. That efficiency is a big part of why transformers displaced earlier sequential models.

Many heads, many relationships

One attention pattern can’t capture everything. So transformers use multi-head attention: several attention operations run side by side, each with its own query, key and value matrices. In trained models, different heads specialize — one might track which noun a pronoun refers to, another the previous word, another matching brackets in code. Their outputs are combined and passed on.

No peeking at the future

A model that generates text left to right must not use tokens it hasn’t produced yet. Causal masking enforces this: when computing attention for a token, all later positions get a weight of zero. Each token can attend only to itself and what came before it — matching the next-token task the model is trained on.

Why long contexts are expensive

In standard attention, every token compares its query with every other token’s key. With nn tokens that is about n2n^2 comparisons, so doubling the context roughly quadruples the attention work, and the stored keys and values grow with every token. This is why:

  • very long prompts respond more slowly, especially before the first token appears;
  • providers price long contexts carefully and cap their size;
  • researchers invest heavily in faster attention algorithms and memory-saving tricks.

The lab below puts numbers on both costs for a mid-size open model. Drag the context length from a short prompt to a million tokens and compare how fast each cost grows.

InteractiveWhat a long context costsDrag the context length
Loading visual…

The model shape resembles a common open 8-billion-parameter model (32 layers, grouped key–value heads, 16-bit numbers), whose cache needs about 128 KB per token. Every request running at the same time needs its own cache, which is one reason providers cap context length and charge more for long prompts.

Attention is one of two building blocks inside a transformer. In the next lecture we stack them and follow a prompt all the way through the model.

Key takeaways

  • Self-attention lets every token build a context-aware representation by mixing in information from other tokens.
  • Each token asks a question (query), advertises what it contains (key) and offers content (value); weights come from query–key matches.
  • Many attention heads run in parallel, each free to learn a different kind of relationship.
  • Standard attention compares every token with every other one, so its cost grows roughly with the square of the context length.

Check your understanding

3 questions · answers explained

Q1In “The animal didn’t cross the street because it was too wide”, what should attention help the model work out?

A street can be too wide to cross; an animal can’t. Attention lets the representation of “it” draw on “street” so the model can resolve the reference from context.

Q2In self-attention, what determines how much one token attends to another?

Each token’s query is compared with every key. Higher similarity means a larger weight after softmax, so that token’s value contributes more to the result.

Q3Why does doubling the length of a prompt more than double the attention work?

With n tokens there are about n × n query–key comparisons. Doubling n roughly quadruples that work, which is one reason long contexts are slower and more expensive.