BEGINNERCHAPTER 03

Transformers and attention: just enough

Embeddings, one attention head by hand, the stack around it, and the two facts that drive every cost and latency number you will meet: attention is quadratic, and the KV cache is what makes generation affordable

55 MINAI ENGINEERINGUPDATED 2026-11-02
PREDICT

A model's prompt grows from 50,000 to 100,000 tokens. Roughly what happens to the attention computation during prefill, the pass that reads the prompt?

You do not need to train a transformer to build with one, but you do need a working model of what happens inside. It explains why long prompts are slow, why output tokens cost more than input tokens, why a 128K context needs gigabytes of memory, and why the model can attend to a sentence it was given but cannot reliably count its letters. This chapter builds that model from the bottom: one token’s vector, one attention head, one block, then the stack. In the lab you will compute a head by hand, then in numpy, then read a real head out of GPT-2.

The reference throughout is GPT-2 small: 124 million parameters, a 768-wide model, 12 layers of 12 heads, a 50,257-token vocabulary and a 1,024-token context. It is old and small enough to run on a laptop in seconds, and structurally it is the same decoder-only design as the models you call through APIs. Where modern models differ, the text says how.

From tokens to vectors

The model’s input is a list of token ids from the previous chapter. The first layer is a lookup table called the embedding matrix: one row per vocabulary entry, each row a vector of d_model numbers. In GPT-2 small that is 50,257 rows of 768 numbers, 38.6 million parameters, almost a third of the model.

The vectors are learned. Training adjusts them so that tokens used in similar ways end up with similar vectors, which is the property chapter seven builds on. At the input, though, each vector only says which token this is. It carries no information about the tokens around it. Producing vectors that do is the job of the rest of the model.

Position

Attention, as you will see in a moment, compares every token with every other token using dot products. A dot product does not care where the vectors came from. Without extra information, “the dog bit the man” and “the man bit the dog” contain the same bag of tokens and would produce the same comparisons.

So position has to be added. The 2017 paper added a fixed pattern of sines and cosines of different frequencies to each embedding (section 3.5), so that each position has a distinct signature and nearby positions have similar ones. GPT-2 learns a second embedding table instead, with one row per position, 1,024 rows, and adds it to the token embedding. That is also why GPT-2 cannot read past 1,024 tokens: there is no row for position 1,025.

Most current open models, including Llama, use rotary position embeddings (RoPE). Instead of adding a position vector at the input, they rotate each query and key vector by an angle that depends on its position, inside every attention layer. The dot product between a query and a key then depends on the distance between them rather than their absolute positions, which is part of how context windows were stretched from thousands of tokens to hundreds of thousands.

Queries, keys and values

Now the core. After the embedding, each position holds a vector, and the model needs each position to gather information from the others. “Sat” needs to know what sat. “It” needs to find what it refers to. Attention does this with three learned projections of every position’s vector:

  • a query, q: what this position is looking for;
  • a key, k: what this position offers, used for matching;
  • a value, v: what this position hands over if it is chosen.

Each is a matrix multiplication: Q = X·W_Q, K = X·W_K, V = X·W_V, where X is the sequence of vectors, one row per token. In GPT-2 small each head’s projections map 768 numbers down to 64. The matrices are learned, and different heads learn to look for different things.

The analogy is a fuzzy dictionary lookup. A Python dict compares your key with every stored key and returns the one value whose key matches exactly. Attention compares a query with every key, scores how well each matches, and returns a blend of all the values weighted by those scores.

Scaled dot-product attention

The whole operation is one line, equation 1 in the paper:

Attention(Q, K, V) = softmax(Q·Kᵀ / √d_k) · V

Read it in four steps, for a sequence of T tokens and a head size of d_k:

  1. Score. Q·Kᵀ is a T×T matrix. Row i, column j is the dot product of token i’s query with token j’s key: how relevant j is to i.
  2. Scale. Divide by √d_k. If the entries of q and k are roughly independent with variance 1, their dot product has variance d_k, so with 64-dimensional heads the scores spread over a range of about ±16. A softmax over numbers that far apart puts nearly all the weight on one entry, and its gradients vanish, which stalls training. Dividing by √d_k brings the spread back to about ±2 whatever the head size. The lab shows what happens without it.
  3. Mask and normalise. In a decoder-only model, token i may only attend to tokens 0 to i, because during training it is predicting token i+1 and must not see it. The causal mask sets every score above the diagonal to minus infinity. Then softmax each row, so each token’s weights are positive and sum to 1. Masked entries become exactly 0.
  4. Blend. Multiply by V. Each token’s output is the weighted average of the value vectors of the tokens it attended to.

The output has the same shape as the input, one vector per token, but each vector now carries information gathered from earlier positions. That is the only place in the whole model where information moves between positions. Everything else operates on each position separately.

Many heads

One head learns one kind of lookup. Multi-head attention runs several in parallel, each with its own W_Q, W_K, W_V, on smaller vectors. GPT-2 small has 12 heads of 64 dimensions; 12 × 64 = 768, so the total cost is about the same as one 768-wide head. The heads’ outputs are concatenated back to 768 numbers and mixed by one more learned matrix, W_O.

Heads specialise. Researchers have found heads that attend to the previous token, heads that find the matching earlier occurrence of the current token and copy what came after it (the “induction heads” that make in-context copying work), and heads that track syntax. Many heads also dump most of their weight on the first token of the sequence, a learned “nowhere to look” default often called an attention sink. You will see one in GPT-2 in the lab.

Modern models change one detail that matters for memory. In grouped-query attention (GQA), several query heads share one key and value head. Llama 3.2 3B has 24 query heads but only 8 key-value heads, which cuts the KV cache below to a third of its size with little loss in quality.

The MLP block

After attention, each position’s vector goes through a small two-layer neural network, the MLP or feed-forward block, applied to every position independently. In GPT-2 it expands 768 numbers to 3,072, applies a non-linearity (GELU), and projects back to 768. Llama uses a gated variant (SwiGLU) with three matrices, but the shape of the idea is the same.

The MLP holds most of the parameters: in GPT-2 small, 4.7 million per layer against 2.4 million for attention. Attention decides which information to move; the MLP decides what to do with it. Interpretability research has located many stored facts in MLP weights, which is a useful intuition: if the model “knows” that Lagos is in Nigeria, that knowledge is mostly in the MLPs, and attention is how the word “Lagos” earlier in the prompt gets to the position where the answer is being produced.

Residuals and layer norm

Two pieces of plumbing make deep stacks trainable.

Residual connections. Each block’s output is added to its input rather than replacing it: x = x + attention(x), then x = x + mlp(x). The running vector at each position, often called the residual stream, is a shared workspace that every block reads from and writes a correction into. Gradients flow straight through the additions, which is why models of 100 layers train at all.

Layer normalisation. Before each sub-block, the vector is rescaled to zero mean and unit variance, then multiplied and shifted by learned parameters. This keeps the numbers in a stable range as dozens of blocks add to them. GPT-2 normalises before each sub-block and once more at the end; Llama uses a cheaper variant called RMSNorm. The original 2017 paper normalised after each sub-block, which is harder to train deep; nearly every model since has moved it before.

The decoder-only stack

Put together, a decoder-only transformer is:

token embedding + position× N blocks(12 in GPT-2 small,28 in Llama 3.2 3B)layer norm → masked multi-head attention+residuallayer norm → MLP (768 → 3,072 → 768)final layer norm → unembed → logitssoftmax over 50,257 tokens → sampler (chapter one)

The final step multiplies the last position’s vector by the vocabulary matrix to get one logit per token. GPT-2 reuses the embedding matrix for this, transposed. Those logits are the distribution the sampler in chapter one draws from. During training, every position predicts its next token at once, which is why the causal mask matters; during generation you only need the prediction at the last position.

Count the parameters and the 124 million in GPT-2 small fall out: 38.6 million in the token embedding, 0.8 million in positions, and about 7.1 million in each of 12 blocks. A model like Llama 3.2 3B is the same recipe, wider (3,072) and deeper (28 blocks), with RoPE, RMSNorm, SwiGLU and grouped-query attention swapped in.

Why attention is quadratic

Count the work per layer for T tokens with width d. The projections (Q, K, V and the output) and the MLP each touch every token once: about 24·T·d² floating-point operations, linear in T. Computing Q·Kᵀ and multiplying by V compares every token with every earlier token: about 4·T²·d operations, quadratic in T.

The two are equal when T is about 6d. For GPT-2 small that is about 4,600 tokens, beyond its own context limit, so in GPT-2 attention never dominates. For a 3,072-wide model it is about 18,000 tokens. Past that point every doubling of the prompt roughly quadruples the time spent in attention. At 100,000 tokens there are 10 billion scores per head per layer; Llama 3.2 3B has 24 heads and 28 layers.

Memory is the other half. Stored naively in 16-bit floats, one head’s 100,000 × 100,000 score matrix is 20 GB. Real implementations never store it: FlashAttention and its successors compute attention in tiles that fit in fast on-chip memory and keep only running totals, which brings memory back to linear in T. The compute is still quadratic.

What this means when you build:

  • Time to first token grows faster than prompt length. A 100K-token prompt is not ten times slower to start than a 10K-token one; on a model where attention dominates, it is closer to a hundred times for the attention part.
  • Long context is priced linearly but is not free to serve. Providers absorb the quadratic part into their per-token price and their limits. On your own hardware, it is your latency.
  • Retrieval is partly a compute decision. Sending the 5,000 relevant tokens instead of the 100,000-token document is 20 times fewer tokens and up to 400 times less attention work.

The KV cache: why generation works at all

Now the generation loop from chapter one, with the transformer inside. To produce token t+1, the model needs the attention of position t over positions 0 to t. That needs the keys and values of every earlier position, in every layer.

Without a cache, each step re-runs the whole model on the whole sequence so far. Generating n tokens then does about n²/2 token-passes of linear work and on the order of n³ attention work in total. A 1,000-token answer would cost roughly 500 times what it does.

But the keys and values of earlier tokens never change: the causal mask means position 5 never sees position 6, so its vectors are final once computed. So inference engines compute them once and keep them, the KV cache. Each new step runs the model on one new token: compute its q, k and v, append k and v to the cache, attend over the cache, and continue. The per-step cost becomes linear in the context length instead of quadratic, and the sequence of steps becomes affordable.

The cost moves from compute to memory:

KV cache bytes per token = 2 (K and V) × layers × KV heads × head size × bytes per number
Model Per token At 4,096 tokens At full context
GPT-2 small (12 × 12 × 64, 32-bit) 72 KiB beyond its limit 72 MiB at 1,024
Llama 3.2 3B (28 × 8 × 128, 16-bit) 112 KiB 448 MiB 14 GiB at 131,072
Llama 3.2 3B without GQA (24 KV heads) 336 KiB 1.3 GiB 42 GiB at 131,072

That table explains the previous chapter’s Ollama default. The 3B model’s weights are 2.0 GB as Ollama ships them; its full-context cache is seven times that. It also explains a choice you will meet in production: Ollama can quantise the cache with OLLAMA_KV_CACHE_TYPE=q8_0 (about half the memory) or q4_0 (about a quarter), with flash attention enabled, at some cost in precision.

The KV cache also explains the price split from chapter two. Prefill processes the prompt in one parallel pass and fills the cache; the accelerator is busy with arithmetic. Decode reads every weight and the whole cache from memory to produce one token, so its speed is bounded by memory bandwidth: tokens per second is at most bandwidth divided by bytes read per token. A laptop with 100 GB/s of bandwidth reading a 2 GB model can produce at most about 50 tokens per second, whatever its arithmetic speed. Serving systems batch many users’ decode steps together to share each read of the weights, and the cache for all those users is what fills the GPU. The serving chapter in module four (ai-engineering/serving-and-inference) picks up from here: paged caches, continuous batching, prefix caching, speculative decoding and quantisation.

LAB One attention head, three ways ~40 MIN
YOU NEEDPen and paper, or a spreadsheetPython 3.12 with uvAbout 1.5 GB of disk and a few minutes of download for PyTorch and GPT-2 small (548 MB of weights)

You will compute one attention row by hand, then a full head in numpy with random weights, then read real attention weights out of GPT-2 small for the same sentence. No API calls; everything runs locally.

1. One row by hand.

Take the sentence “the cat sat on the mat”, lower-cased, six tokens. To keep it small, the head size is 2, positions are ignored, and someone has already computed the keys and values. Compute the attention of the last token, “mat”, whose query is q = [2, 1].

token key k value v score q·k score / √2 exp weight
the [0, 1] [1, 0]
cat [1, 1] [0, 2]
sat [0, 0] [1, 1]
on [-1, 0] [0, 0]
the [0, 1] [1, 0]
mat [1, 0] [2, 1]

Fill the columns left to right: the dot product, divided by √2 ≈ 1.414, then e to that power, then each exp divided by the column’s sum. Finally compute the output, the sum of weight × value over the six rows.

Scores 1, 3, 0, -2, 1, 2. Scaled: 0.71, 2.12, 0, -1.41, 0.71, 1.41. Exp: 2.03, 8.34, 1.00, 0.24, 2.03, 4.11, summing to 17.75. Weights: 0.11, 0.47, 0.06, 0.01, 0.11, 0.23, summing to 1. Output: about [0.75, 1.23]. “mat” attends mostly to “cat” and itself. Notice the two “the” rows get identical weight: with positions ignored, the head cannot tell them apart. That is the problem the position encoding solves.

2. A whole head in numpy.

From the root of your ATLAS checkout (the labs/ai uv project comes from the first chapter’s lab):

cd labs/ai && uv add numpy
mkdir -p attention && cd attention

Create attention.py:

import numpy as np

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

tokens = ["The", " cat", " sat", " on", " the", " mat"]
T, d_model, d_k = len(tokens), 8, 4

# 1. Embeddings: one row per token (learned in a real model; random here).
E = rng.normal(size=(T, d_model))

# 2. Positional information: sinusoidal encoding from the 2017 paper, section 3.5.
pos = np.arange(T)[:, None]
i = np.arange(d_model)[None, :]
angle = pos / np.power(10000, (2 * (i // 2)) / d_model)
P = np.where(i % 2 == 0, np.sin(angle), np.cos(angle))
X = E + P

# 3. One head's projection matrices.
W_q = rng.normal(size=(d_model, d_k)) / np.sqrt(d_model)
W_k = rng.normal(size=(d_model, d_k)) / np.sqrt(d_model)
W_v = rng.normal(size=(d_model, d_k)) / np.sqrt(d_model)
Q, K, V = X @ W_q, X @ W_k, X @ W_v

# 4. Scaled dot-product scores, T x T.
scores = Q @ K.T / np.sqrt(d_k)

# 5. Causal mask: token t may only look at tokens 0..t.
mask = np.triu(np.ones((T, T), dtype=bool), k=1)
scores[mask] = -np.inf

# 6. Softmax over each row (subtract the row max for numerical stability).
w = np.exp(scores - scores.max(axis=1, keepdims=True))
A = w / w.sum(axis=1, keepdims=True)

# 7. Output: each token's new vector is a weighted average of value vectors.
out = A @ V

print("attention weights (row = query token, column = key token):")
print(" " * 6 + "".join(f"{t.strip():>7}" for t in tokens))
for t, row in zip(tokens, A):
    print(f"{t.strip():>6}" + "".join(f"{x:7.2f}" for x in row))
print("row sums:", A.sum(axis=1))
print("output shape:", out.shape)
uv run python attention.py
attention weights (row = query token, column = key token):
          The    cat    sat     on    the    mat
   The   1.00   0.00   0.00   0.00   0.00   0.00
   cat   0.75   0.25   0.00   0.00   0.00   0.00
   sat   0.39   0.49   0.12   0.00   0.00   0.00
    on   0.34   0.28   0.21   0.17   0.00   0.00
   the   0.33   0.17   0.08   0.03   0.40   0.00
   mat   0.04   0.01   0.00   0.00   0.05   0.90
row sums: [1. 1. 1. 1. 1. 1.]
output shape: (6, 4)

The upper triangle is all zeros: the causal mask at work. The first token can only attend to itself, so its row is 1.00. Every row sums to 1. The pattern itself means nothing, because the weights are random; a trained head’s pattern is what step 3 shows. The fixed seed makes your numbers match these.

3. A real head in GPT-2 small.

uv add transformers torch matplotlib

Create gpt2_attention.py:

import sys
import torch
import matplotlib.pyplot as plt
from transformers import AutoTokenizer, AutoModel

name = "openai-community/gpt2"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModel.from_pretrained(name, attn_implementation="eager").eval()

inputs = tok("The cat sat on the mat", return_tensors="pt")
tokens = tok.convert_ids_to_tokens(inputs["input_ids"][0])
with torch.no_grad():
    out = model(**inputs, output_attentions=True)
att = torch.stack(out.attentions)[:, 0]          # (layers, heads, T, T)
print("tokens:", tokens, " attention tensor:", tuple(att.shape))

T = att.shape[-1]
sink = att[:, :, 1:, 0].mean(-1)                 # weight on the first token
prev = torch.stack([att[:, :, i, i - 1] for i in range(1, T)], -1).mean(-1)
for label, score in (("first-token (sink)", sink), ("previous-token", prev)):
    top = torch.topk(score.flatten(), 3)
    found = [f"L{int(i) // 12}H{int(i) % 12}={v:.2f}" for v, i in zip(top.values, top.indices)]
    print(f"strongest {label} heads:", ", ".join(found))

layer, head = (int(sys.argv[1]), int(sys.argv[2])) if len(sys.argv) == 3 else (4, 11)
A = att[layer, head]
print(f"\nlayer {layer} head {head}:")
for t, row in zip(tokens, A):
    print(f"{t:>6}" + "".join(f"{x:7.2f}" for x in row.tolist()))
plt.imshow(A, cmap="Greys")
plt.xticks(range(T), tokens); plt.yticks(range(T), tokens)
plt.title(f"GPT-2 small, layer {layer}, head {head}")
plt.colorbar(); plt.savefig(f"gpt2_L{layer}H{head}.png", dpi=120, bbox_inches="tight")
uv run python gpt2_attention.py
The first run downloads about 550 MB of weights. Then tokens: ['The', 'Ġcat', 'Ġsat', 'Ġon', 'Ġthe', 'Ġmat']: six tokens, and Ġ is GPT-2’s marker for the leading space from chapter two. The tensor shape is (12, 12, 6, 6): 12 layers, 12 heads, a 6×6 matrix each. The upper triangle of every matrix is zero, as in your numpy version. Many heads put most of each row’s weight on The, the attention sink; the script names the strongest of those, with sink scores near 1. It also names the heads whose weight sits on the diagonal one step below the main one, previous-token heads, typically in the lower and middle layers with scores well above 0.5.

Re-run with the layer and head of the strongest previous-token head, for example uv run python gpt2_attention.py 4 11 if that is what was printed, and open the PNG.

A dark stripe one step below the diagonal: each token looks at the one before it. Ġmat attends to Ġthe, Ġsat to Ġcat. Nobody programmed that; training found that knowing the previous token is useful for predicting the next one, and dedicated a head to it. Compare with the random head from step 2, which has no structure at all.
In attention.py, set d_model, d_k = len(tokens), 512, 64 (the width of a real head) and run it: the rows stay spread across several tokens. Now delete / np.sqrt(d_k) from the scores line and run again. Nearly every row collapses to a single 1.00, because unscaled 64-dimensional dot products are about eight times larger and the softmax turns them into a one-hot choice. A head in that state passes on one token’s value and ignores the rest, and during training its gradients are close to zero, so it stops learning. One division keeps attention soft.
ARTEFACT Write the model's known-limitations note ~45 MIN
YOU PRODUCEA known-limitations note for support and product staff

Template

# Known limitations: <product and model>, <date>
Owner: <product manager>. Approved by: <head of product>. Read by: support, product. Review on: <date>.
Decision needed: <what, from whom, by when>. Out of scope: <what this note does not cover>.

## Limitations
| # | What the user sees | Why it happens (one sentence) | Evidence (lab output, table or assumption) | What the product does | Owner | What support says |
|---|---|---|---|---|---|---|

## Not tested
<behaviours you suspect but the chapter did not show, so nobody quotes them as fact>

## How this could be wrong
<one way, and what would show it>
WORKED EXAMPLE

A product manager writes this with the support lead; the head of product approves it. The setting is the Why’s team: a self-hosted open model reviewing documents, raised from 8K to 128K tokens of context. The model is Llama 3.2 3B.

Owner: product manager. Approved by: head of product. Decision needed: whether to cap context at 8,192 tokens and add retrieval, by Friday. Out of scope: answer quality on any task the lab did not measure.

# What the user sees Why Evidence What the product does Owner
1 The first long contract crashes the server with an out-of-memory error The KV cache grows with every token 112 KiB per token; 14 GiB at 131,072 tokens Cap context at 8,192 tokens Head of engineering
2 A minutes-long wait before any text appears, and short requests time out behind it Attention is quadratic: doubling the prompt roughly quadruples that work Chapter body; no timing of our own Retrieve about 5,000 tokens instead of 100,000: 20 times fewer tokens Platform lead
3 The model cannot reliably count letters in a word It sees tokens, not letters Chapter body only Support macro says so; product sends counting to code Support lead

Support says: for #1, “Documents are cut to the sections most relevant to your question.” For #2, “Long documents are slow to start, so we send the relevant parts.” For #3, “It cannot count letters reliably; we use a tool for that.”

Not tested: whether retrieval misses the right clause. How this could be wrong: 8,192 tokens costs about 0.9 GiB of cache (8,192 × 112 KiB = 896 MiB, arithmetic on the chapter table), but if real requests exceed it, users see truncated answers; complaints citing missing clauses would show it.

Now you

You are the product manager at Wrenpost, which has about 12 people in support. Engineering has built an internal assistant on llama3.2:3b through Ollama, running on support laptops with 16 GB of memory. Agents paste a customer’s whole ticket history into it, often about 90,000 tokens, and ask what was promised. Complaints so far: laptops freeze on long histories, agents wait a long time before any reply, and answers sometimes come from the oldest tickets only.

Write the known-limitations note. Reuse the chapter’s table for the memory arithmetic (112 KiB per token for this model), and the chapter’s quadratic reasoning for the waiting. Mark anything the chapter does not show as not tested. The support lead and head of engineering read it, and it supports one decision: which context limit the assistant ships with and what agents are told.

Self-check

DECIDE

A legal team wants a question-answering tool over 300-page contracts, about 150,000 tokens each. Policy says contract text may not leave the lawyers' laptops, which have 16 GB of unified memory. The current prototype runs llama3.2:3b through Ollama with the default context and answers from the first few pages only. What do you change?

READING
  1. PAPER
    Attention Is All You Need Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser, Polosukhin, 2017

    The paper that introduced the transformer. Section 3 is eight pages and defines every component in this chapter; the encoder-decoder framing is for translation, and modern LLMs keep only the decoder half. Read: section 3 (model architecture), especially 3.2 on attention and 3.5 on positional encoding; skip the translation results in sections 5 and 6.

  2. POST
    The Illustrated Transformer Jay Alammar, 2018

    The paper's architecture drawn step by step, with the Q, K and V matrices shown as actual coloured grids. Read it alongside section 3 of the paper; the encoder half is more than you need for decoder-only models.

  3. TALK
    Transformers, the tech behind LLMs (Deep Learning, chapter 5) 3Blue1Brown (Grant Sanderson), 2024

    Embeddings, the unembedding and softmax, animated with real GPT-3 dimensions. The clearest visual account of what the vectors mean before attention touches them.

  4. TALK
    Attention in transformers, step-by-step (Deep Learning, chapter 6) 3Blue1Brown (Grant Sanderson), 2024

    Queries, keys, values, masking and multiple heads as geometry, at the level of this chapter. Watch it after the lab's step 1; it will confirm what your hand-computed table did.

  5. PAPER
    Efficiently Scaling Transformer Inference Pope, Douglas, Chowdhery, Devlin, Bradbury, Levskaya, Heek, Xiao, Agrawal, Dean, 2022

    Puts numbers on prefill versus decode, memory bandwidth limits and KV cache size for real models. The source for the reasoning in this chapter's last section. Read: sections 2 and 3.1 (the cost model and the KV cache memory analysis); the partitioning strategies after that are for the serving chapter.

  6. CODE
    BertViz Jesse Vig

    Interactive views of every head in every layer for GPT-2 and most Hugging Face models, in a notebook. Use it after the lab to browse all 144 heads instead of one at a time.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Pretraining, fine-tuning, RLHF: how a model got its behaviour →