02.4 Attention and Transformers

Understand LLMsLesson 4 of 1020,902 words12 parts
Module 02 · 0 of 9 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

Almost every modern LLM, from GPT and Claude to Gemini, Llama, Qwen and DeepSeek, is built on one architecture: the transformer (a few recent hybrids replace most of its layers but keep some; see 12.5). At its heart is a single idea called attention, which lets every token in a text look at the other tokens and pull in whatever context it needs. This lesson builds that idea from scratch in plain NumPy, then follows it all the way up to a real model: how attention is computed, why it needs masking and positions, how attention and MLP layers stack into a full LLM, what the numbers in a config.json mean, why long prompts are expensive, and what the KV cache is. By the end you'll be able to read a model card or an architecture diagram the way you read an API reference.

What you'll learn

  • Why context changes meaning, and why a model needs a mechanism to mix context into every token
  • Self-attention from intuition to working code: queries, keys and values, scores, softmax and the √d scaling
  • Causal masking: why a chat model can only look backwards, and the surprising engineering consequences
  • Multi-head attention, what individual heads have been observed to do, and how that connects to in-context learning (why examples in a prompt change behaviour with no weight update)
  • Positional information: why attention can't see word order on its own, plus sinusoidal, learned and RoPE positions, and how they relate to context-length limits
  • The transformer block: attention, MLP, residual connections and normalization (pre-norm, RMSNorm), and how blocks stack
  • The complete forward pass of a decoder-only LLM, mapped onto real config.json fields
  • Inspecting a real model: attention weights in GPT-2, and where the parameters actually live
  • The three architecture variants (encoder-only, decoder-only, encoder-decoder) and what each is used for today
  • Why attention cost grows roughly quadratically with length, and how the KV cache works and how big it gets
  • Modern variants you'll see in model cards: GQA/MQA, MLA, FlashAttention, sliding-window and sparse attention, MoE layers, and alternatives such as Mamba and hybrids
  • That not every LLM generates one token at a time: an emerging family of diffusion and other parallel-decoding language models, and what you give up and gain when you use one

What you don't need

  • Linear algebra beyond "multiply and add" and the dot product from lesson 01, 2.3. Every formula is explained in words.
  • A GPU. Every sample runs on a CPU laptop.
  • To implement or train a transformer yourself. You'll build tiny ones to understand them, but as an applied AI engineer you'll use trained models through APIs and open-weight downloads.

Setup

Most samples (Parts 2–6, sections 7.2 and 7.6, Part 10 and sections 11.3–11B.1) need only NumPy or plain Python. Section 7.5 also needs Hugging Face Transformers (it downloads only a small config file). The real-model demos (Part 8 and section 11.5) need PyTorch and Transformers, and download two small models from Hugging Face the first time they run: gpt2 (about 550 MB) and Qwen/Qwen2.5-0.5B (about 1 GB).

bash
uv add numpy torch transformers        # or: pip install numpy torch transformers

First time? Create a project with uv init llm-basics && cd llm-basics, then run scripts with uv run python file.py.

The outputs in this lesson were produced with Python 3.13, NumPy 2, PyTorch 2.15.0 and Transformers 5.22.1. Transformers 5.x is a recent major version, so a newer major release may rename things again; if a sample fails after an upgrade, check its changelog. No API keys are needed.


What you must be able to do after this lesson#

  • Explain what problem attention solves
  • Describe in plain words how self-attention lets each token use the other tokens (the full step-by-step walkthrough is the Deep-dive Part 2)
  • Explain why decoders need causal masking
  • Describe the parts of a transformer block
  • Explain what the KV cache stores and why it helps
  • Explain why attention cost grows with context length and what that means for limits and price

Why this matters for an AI engineer#

You'll never write an attention layer at work, but transformer vocabulary is everywhere: model cards, provider docs, pricing pages, inference-server settings and conference talks. It also explains behaviours you'll hit in production:

You'll hear... You'll understand it after...
"Self-attention lets the model use context." Part 2: Self-attention, step by step
"It's a decoder-only model, like GPT." Part 9: Architecture variants
"Use a BERT-style encoder for the classifier, it's cheaper." 9.2 Encoder-only models
"The model has 32 query heads and 8 KV heads." 12.1 Grouped-query and multi-query attention
"It uses RoPE with YaRN scaling to reach 128K context." 5.6 Positions and context-length limits
"What do hidden_size and num_hidden_layers mean in this config?" 7.5 Reading a real config.json
"Long prompts are slow and expensive." Part 10: The cost of attention
"The KV cache is eating all our GPU memory." Part 11: The KV cache
"Put the stable part of the prompt first so it can be cached." 11.6 From KV cache to prompt caching
"We serve it with FlashAttention." 12.2 FlashAttention
"It's a hybrid Mamba-transformer model." 12.5 Beyond attention
"It's a diffusion language model — why is it so fast?" 12.7 Beyond next-token prediction
"Few-shot examples work even though the model isn't being trained." 4.4 What attention heads have been observed to do
"Look at the attention map: the model is clearly focusing on X." 8.2 Caveats when reading attention

Part 1: The problem attention solves#

1.1 Context changes meaning#

Read these two sentences:

  • I deposited my salary at the bank.
  • We had a picnic on the river bank.

You understood "bank" differently each time without effort. The word is identical; only the context changed. Language is full of this:

Example What context has to resolve
The bank approved the loan / the river bank flooded Which meaning of a word (a financial institution or the edge of a river)
The trophy didn't fit in the suitcase because it was too big. Which noun a pronoun refers to (coreference). Change "big" to "small" and "it" flips from the trophy to the suitcase.
The keys to the old wooden cabinet are on the table. Grammar across a distance: "are" agrees with "keys", not with the nearer "cabinet".
Apple shares rose after it announced earnings. World knowledge: here Apple is a company, not a fruit.
Not bad at all. "Bad" flips meaning because of "not".

Now recall how text enters a model (lesson 02 and lesson 03): the text is split into tokens, and each token ID is looked up in an embedding table to get a vector. That lookup is context-free: the token "bank" gets exactly the same starting vector in both sentences above, because the table has a single row for it.

So the model needs a mechanism that, for every token, mixes in information from the surrounding tokens, turning a context-free vector ("bank, some meaning") into a contextual one ("bank, the riverside kind, in this sentence"). That mechanism is attention.

1.2 How models handled context before transformers#

Before 2017, language models were mostly recurrent neural networks (RNNs, and the improved LSTM variant). Lesson 01, 8.2 covers them in more detail. In short, an RNN reads one token at a time and carries a fixed-size "memory" vector forward, updating it at every step. This had two problems:

  • The bottleneck: everything the model knows about the text so far must be squeezed into one fixed-size memory vector. Information from early tokens fades as it's overwritten step after step. By the time an RNN reaches "are" in the "keys ... cabinet ... are" example, the "keys" information may have faded.
  • No parallelism: token 50 can't be processed until tokens 1 to 49 have been, so training can't use a GPU's ability to do millions of operations at once.

1.3 The core idea in one sentence#

Attention lets every token look directly at every other token, decide how relevant each one is, and pull in a weighted blend of their information.

There's no fading memory chain: "are" can look straight back at "keys" whatever the distance. And because every token does this at the same time, the whole computation is a few big matrix multiplications that GPUs run in parallel (lesson 01, 3.3).

The rest of this lesson unpacks how "decide how relevant" and "pull in a weighted blend" actually work, and what else is needed to turn this idea into an LLM.


Part 2: Self-attention, step by step#

Deep-dive

2.1 An intuition: a room full of experts#

Imagine every token in the sentence "I sat by the river bank" (the same sentence the code in 2.4 uses) is a person sitting in a meeting room. Each person wants to understand their own role better, so each one does three things:

  1. Asks a question that describes what they're looking for. "Bank" asks: "Is anyone here about water, or about money?"
  2. Wears a name badge that advertises what they can offer. "River" wears a badge saying "I'm about water and nature."
  3. Holds some information they'll share with anyone who listens. "River" shares "riverside, outdoors, water".

Everyone compares their question with everyone's badge. "Bank" finds that "river"'s badge matches its question very well, "the"'s badge doesn't match at all, and so on. Then "bank" listens to everyone at once, but at different volumes: mostly to "river", a little to the others. What it hears gets added to its own understanding, and "bank" now knows it's the riverside kind.

Every person does this simultaneously, so "sat" can be working out who sat while "bank" is working out which bank. This is self-attention: "self" because the tokens attend to other tokens in the same sequence.

2.2 Queries, keys and values#

The three things each person did have standard names:

Name In the meeting room In a library search What it is in the model
Query (Q) The question I'm asking What you type into the search box A vector describing what this token is looking for
Key (K) My name badge The title and catalogue labels on each book A vector describing what this token can offer to others
Value (V) The information I share The actual contents of each book A vector holding the information this token passes on

The library analogy captures the crucial difference between keys and values: you match your search against the labels, but what you take home is the contents. Keeping the two separate lets a token advertise itself one way ("I'm a place-noun") while passing on something else ("here is my detailed meaning").

There's one big difference from a real library or a database lookup. A database returns exactly one matching row (or none). Attention is a soft lookup: it returns a blend of every value, weighted by how well each key matched. A strong match contributes a lot; a weak match contributes a little; nothing is excluded completely.

2.3 The four steps of attention#

For each token, attention does four things:

  1. Score. Compare this token's query with every token's key using the dot product (multiply matching numbers and add them up, exactly as in lesson 01, 2.3). Vectors that point in similar directions give a big score; unrelated ones give a score near zero. You met the same idea as similarity between embeddings in lesson 03.
  2. Scale. Divide every score by √d, the square root of the number of entries in each query and key vector (their dimension, d). Section 2.5 explains why.
  3. Softmax. Turn the row of scores into attention weights: positive numbers that add up to 1, like percentages. This is the same softmax that turns logits into probabilities in lesson 01, 3.6.
  4. Blend. Multiply each token's value by its weight and add them all up. The result is this token's new, context-aware vector.
flowchart LR
    Q["Query of 'bank'"] --> S["1. Score:<br/>dot product with<br/>every key"]
    K["Keys of all tokens"] --> S
    S --> SC["2. Scale:<br/>divide by √d"]
    SC --> SM["3. Softmax:<br/>weights that<br/>sum to 1"]
    SM --> B["4. Blend:<br/>weighted sum<br/>of values"]
    V["Values of all tokens"] --> B
    B --> O["New vector for 'bank'<br/>(now context-aware)"]

2.4 Try it: attention in NumPy#

Here's a complete implementation of scaled dot-product attention, run on a six-token sentence. To make the numbers readable, we hand-write the query, key and value vectors and give each of their four numbers a meaning. In a real model these vectors are learned, and their numbers don't have human-readable meanings (section 2.6).

python
import numpy as np

def softmax(x, axis=-1):
    x = x - x.max(axis=axis, keepdims=True)   # for numerical stability (lesson 01, 3.6)
    e = np.exp(x)
    return e / e.sum(axis=axis, keepdims=True)

def attention(Q, K, V):
    """Scaled dot-product attention."""
    d = Q.shape[-1]                      # size of each query/key vector
    scores = Q @ K.T / np.sqrt(d)        # 1. how well each query matches each key
    weights = softmax(scores, axis=-1)   # 2. turn each row of scores into percentages
    return weights @ V, weights          # 3. blend the values using those percentages

tokens = ["I", "sat", "by", "the", "river", "bank"]

# Hand-made 4-number vectors so we can read them. Real models learn these.
# Key features:   [is-a-place, is-water, is-a-person, is-an-action]
K = np.array([
    [0, 0, 3, 0],   # I      -> "I'm a person"
    [0, 0, 0, 3],   # sat    -> "I'm an action"
    [1, 0, 0, 0],   # by     -> "I relate to places, a little"
    [0, 0, 0, 0],   # the    -> "I advertise nothing"
    [2, 3, 0, 0],   # river  -> "I'm a place, and I'm water"
    [3, 0, 0, 0],   # bank   -> "I'm a place"
], dtype=float)

# The query of "bank" asks: "is there any water or place nearby?"
# The query of "sat" asks: "who did the sitting?"
Q = np.array([
    [0, 0, 0, 0],   # I
    [0, 0, 3, 0],   # sat    -> looks for a person
    [0, 0, 0, 0],   # by
    [0, 0, 0, 0],   # the
    [0, 0, 0, 0],   # river
    [1, 1.5, 0, 0], # bank   -> looks for water (and places)
], dtype=float)

# Values: what each token passes on if attended to.
# Value features: [money-meaning, riverside-meaning, person-meaning]
V = np.array([
    [0, 0, 1],      # I
    [0, 0, 0],      # sat
    [0, 0, 0],      # by
    [0, 0, 0],      # the
    [0, 1, 0],      # river  -> carries "riverside"
    [1, 0, 0],      # bank   -> on its own, the common "money" meaning
], dtype=float)

output, weights = attention(Q, K, V)

np.set_printoptions(precision=2, suppress=True)
print("Attention weights (row = token doing the looking):")
print("        " + "".join(f"{t:>7}" for t in tokens))
for t, row in zip(tokens, weights):
    print(f"{t:>7} " + "".join(f"{w:7.2f}" for w in row))

print("\nNew vector for 'bank'  [money, riverside, person]:", output[5])
print("New vector for 'sat'   [money, riverside, person]:", output[1])
Output11 lines
Attention weights (row = token doing the looking):
              I    sat     by    the  river   bank
      I    0.17   0.17   0.17   0.17   0.17   0.17
    sat    0.95   0.01   0.01   0.01   0.01   0.01
     by    0.17   0.17   0.17   0.17   0.17   0.17
    the    0.17   0.17   0.17   0.17   0.17   0.17
  river    0.17   0.17   0.17   0.17   0.17   0.17
   bank    0.03   0.03   0.05   0.03   0.74   0.13

New vector for 'bank'  [money, riverside, person]: [0.13 0.74 0.03]
New vector for 'sat'   [money, riverside, person]: [0.01 0.01 0.95]

How to read this:

  • Each row is one token's attention, and each row sums to 1. The bank row says: "to build my new vector, take 74% of river's value, 13% of my own, and a few percent of everything else."
  • bank became the riverside kind. On its own, bank's value was pure "money" [1, 0, 0]. After attention, its new vector is [0.13, 0.74, 0.03]: mostly "riverside", with a trace of its original meaning. Put "salary" instead of "river" in the sentence and the same mechanism would pull it towards "money".
  • sat found its subject. Its query looked for a person, I's key advertised a person, so sat took 95% of its information from I.
  • Tokens whose query asks for nothing spread their attention evenly (0.17 = 1/6 each). With all scores equal, softmax gives equal weights. Real models rarely produce such a blank query, but it shows that softmax never gives a weight of exactly 0: every token always gets some share.
  • Attention doesn't replace a token's information; it blends it. In a real model, the attention output is also added to the token's original vector (section 6.3), so nothing is lost.

2.5 Why divide by the square root of d?#

Step 2 divides every score by √d, where d is the dimension of the query and key vectors, meaning how many numbers each one holds (often 64 or 128 per head in real models). Without it, attention breaks down as d grows:

  • A dot product adds up d multiplications. With more numbers being added, the scores get bigger and more spread out. With random vectors, the typical spread grows with √d: about 2 for d = 4, 8 for d = 64, and 23 for d = 512.
  • Softmax is very sensitive to large differences. When scores are spread widely, the biggest one takes nearly all the weight, and the rest get almost none. Attention collapses into "copy one token", and the model can no longer blend information.
  • Worse, when softmax is that extreme, it's almost flat for every input except one, so its slope is nearly zero and training signals barely flow through it (the vanishing gradient problem from lesson 01, 2.5). Training becomes slow and unstable.

Dividing by √d cancels that growth: whatever the vector size, the scores stay in a comfortable range, and softmax stays soft. Let's measure it:

python
import numpy as np

def softmax(x):
    e = np.exp(x - x.max())
    return e / e.sum()

rng = np.random.default_rng(seed=0)
n_keys, trials = 10, 1000

print("Average over 1,000 random queries, each compared with 10 random keys")
for d in [4, 64, 512]:
    spread, top_raw, top_scaled = [], [], []
    for _ in range(trials):
        q = rng.normal(size=d)               # one query with d random numbers
        K = rng.normal(size=(n_keys, d))     # ten keys
        raw = K @ q                          # unscaled dot products
        spread.append(raw.std())
        top_raw.append(softmax(raw).max())                  # biggest weight, no scaling
        top_scaled.append(softmax(raw / np.sqrt(d)).max())  # biggest weight, scaled by sqrt(d)
    print(f"d={d:<4} typical score spread {np.mean(spread):5.1f} | "
          f"top weight unscaled {np.mean(top_raw):.2f} | scaled {np.mean(top_scaled):.2f}")
Output4 lines
Average over 1,000 random queries, each compared with 10 random keys
d=4    typical score spread   1.7 | top weight unscaled 0.49 | scaled 0.31
d=64   typical score spread   7.4 | top weight unscaled 0.86 | scaled 0.32
d=512  typical score spread  20.9 | top weight unscaled 0.95 | scaled 0.32

Without scaling, the single biggest key grabs 49% of the attention at d = 4, 86% at d = 64 and 95% at d = 512. With scaling, it stays at about 32% whatever the size. That's the whole reason for the "scaled" in scaled dot-product attention.

2.6 Where queries, keys and values come from#

In the demo, we hand-wrote Q, K and V. In a real model, each token has a single vector coming into the attention layer (its embedding, or the output of the previous layer), and Q, K and V are produced from it by three learned weight matrices:

  • query = token vector × W_Q
  • key = token vector × W_K
  • value = token vector × W_V

Each is an ordinary dense layer without an activation (lesson 01, 3.3). These three matrices are learned during training, and they're the same for every token in the layer, so every token is projected the same way. Nobody designs features such as "is-water": training discovers whatever query/key/value features make next-token prediction work best, and they're spread across many numbers rather than one readable number each (lesson 01, 3.4).

After blending, the result goes through a fourth learned matrix, the output projection W_O, which maps it back into the model's main vector space. So an attention layer has four weight matrices. With vectors of size d_model, that's about 4 × d_model × d_model parameters per layer (slightly fewer with the grouped-query attention of section 12.1).

Two things make this efficient:

  • All tokens at once. Stack the token vectors into a matrix (one row per token), and one matrix multiplication produces every token's query. Another produces every key, and so on. The score step, Q @ K.T, computes every token-pair score in one go. This is the parallelism that RNNs lacked.
  • The shape is preserved. Six tokens of size d_model go in, and six tokens of size d_model come out. That's what lets layers stack (Part 6).

2.7 Self-attention vs cross-attention#

Self-attention Cross-attention
Queries come from The sequence itself Sequence A (for example the translation being written)
Keys and values come from The same sequence A different sequence B (for example the original sentence being translated)
Used in Every LLM, every layer The decoder of encoder-decoder models such as the original transformer, T5 and Whisper (9.4); some multimodal designs where text attends to image features

Decoder-only chat models, which is almost everything you'll call through an API, use only self-attention. When you put a document in the prompt, the model "reads" it with self-attention over one long sequence containing both your instructions and the document.

What this means for you as an engineer: the model "understands" a word only through what attention pulls in from the rest of your prompt. Ambiguous or missing context leaves it with an ambiguous vector, which is one reason explicit, specific prompts work better than vague ones (Module 04).


Part 3: Causal masking#

Deep-dive

3.1 Why a decoder can't look at future tokens#

In section 2.4, every token could attend to every other token, including the ones after it. A language model that generates text can't be allowed to do that, for two reasons:

  1. At generation time, the future doesn't exist yet. When the model is choosing token 7, tokens 8, 9 and 10 haven't been written. Whatever the model learned to do must work without them.
  2. During training, looking ahead would be cheating. Pretraining turns every sentence into many next-token examples at once (lesson 01, 1.2): position 1 predicts token 2, position 2 predicts token 3, and so on. A transformer computes all of these predictions in a single parallel pass, which is what makes training on trillions of tokens feasible. But if position 2 could see token 3, it would simply copy the answer instead of learning to predict it.

The fix is a causal mask (also called a look-ahead mask): before the softmax, every score where a token would look at a later token is set to minus infinity. Since e^(−∞) = 0, those positions get a weight of exactly 0. Each token can then attend only to itself and the tokens before it.

Models that use this are called causal or autoregressive models, and the transformer stack that uses it is the decoder. Every GPT-style chat model is one.

3.2 Try it: a masked attention matrix#

python
import numpy as np

def softmax(x, axis=-1):
    x = x - x.max(axis=axis, keepdims=True)
    e = np.exp(x)
    return e / e.sum(axis=axis, keepdims=True)

tokens = ["The", "cat", "sat", "on", "the", "mat"]
n = len(tokens)

rng = np.random.default_rng(seed=1)
d = 8
Q = rng.normal(size=(n, d))
K = rng.normal(size=(n, d))
scores = Q @ K.T / np.sqrt(d)

# The causal mask: True above the diagonal = "this is a future token, hide it"
future = np.triu(np.ones((n, n), dtype=bool), k=1)
print("Mask (x = blocked):")
for t, row in zip(tokens, future):
    print(f"{t:>4} " + " ".join("x" if m else "." for m in row))

# Setting a score to -infinity makes its softmax weight exactly 0
masked_scores = np.where(future, -np.inf, scores)
weights = softmax(masked_scores, axis=-1)

print("\nCausal attention weights:")
print("     " + "".join(f"{t:>6}" for t in tokens))
for t, row in zip(tokens, weights):
    print(f"{t:>4} " + "".join(f"{w:6.2f}" for w in row))
print("\nEach row still sums to 1:", weights.sum(axis=1).round(2))
Output18 lines
Mask (x = blocked):
 The . x x x x x
 cat . . x x x x
 sat . . . x x x
  on . . . . x x
 the . . . . . x
 mat . . . . . .

Causal attention weights:
        The   cat   sat    on   the   mat
 The   1.00  0.00  0.00  0.00  0.00  0.00
 cat   0.38  0.62  0.00  0.00  0.00  0.00
 sat   0.32  0.21  0.47  0.00  0.00  0.00
  on   0.21  0.07  0.50  0.22  0.00  0.00
 the   0.19  0.05  0.11  0.63  0.03  0.00
 mat   0.17  0.16  0.16  0.16  0.18  0.17

Each row still sums to 1: [1. 1. 1. 1. 1. 1.]

(The Q and K vectors are random here, so the specific percentages don't mean anything; the pattern is the point.)

  • The mask is a triangle: row i can see columns 1 to i only. Everything above the diagonal is exactly 0.00.
  • The first token can only attend to itself, so its weight is 1.00. It has no context at all.
  • The last token sees everything. That's why, in an LLM, the last position is the one that predicts the next token (section 7.3).
  • Rows still sum to 1, because softmax shares the weight among only the visible tokens.

3.3 Other masks: bidirectional and padding#

Mask What it hides Where it's used
None (bidirectional) Nothing: every token sees every token Encoder models such as BERT and most embedding models (9.2), where the whole text is available and nothing is generated
Causal Future tokens Every decoder and every chat LLM
Padding mask Filler tokens added to make texts in a batch the same length Any model processing a batch of texts with different lengths

The padding mask is the attention_mask you'll see returned by Hugging Face tokenizers: a list of 1s for real tokens and 0s for padding. The model combines it with the causal mask so that no real token attends to padding.

3.4 What causal masking means for you as an engineer#

Causal masking sounds like an implementation detail, but it has real consequences:

  • A token's internal representation depends only on what came before it. When the model processes a long document that comes before your question, it builds its representation of the document without having seen the question yet. The question's tokens can attend back to the document, but the document's tokens never "knew" what you'd ask. So the document is encoded "question-unaware": its tokens can't adjust their representations to what you're going to ask. This is one reason some guidance recommends stating the task or question before a long document as well as after it. OpenAI's long-context guidance, for example, suggests putting instructions at both the beginning and the end of the provided context. Other guidance, such as Anthropic's advice to put long documents near the top and the query at the end, rests on measured results rather than on the mask itself. Lesson 07, 5.5 combines the providers' advice into one layout, and you'll test prompt structure yourself in Module 04.
  • Earlier tokens never change when you add later ones. Appending text to a prompt doesn't alter anything the model computed for the earlier part. This property is the entire basis of the KV cache and of provider prompt caching (Part 11), and it explains why a cache only helps when the beginning of the prompt is identical.
  • Training and generation do the same thing. Because of the mask, the model during training sees exactly the situation it faces during generation: only the past.

Part 4: Multi-head attention#

Deep-dive

4.1 Why one attention isn't enough#

A single attention operation gives each token one set of weights: one way of deciding what's relevant. But a token usually needs several different kinds of information at once. Take "sat" in "The tired cat sat on the mat":

  • Who sat? (the subject, "cat")
  • Where? (the location, "mat")
  • What came just before me? (useful for grammar and word patterns)
  • What's the tense and tone of the sentence?

One set of weights can't point strongly at "cat" and "mat" and the previous word for different purposes. The fix is to run several attention operations side by side, each with its own learned W_Q, W_K and W_V. Each one is called an attention head, and the combination is multi-head attention.

An analogy: instead of one researcher reading a document and answering every question, you have a team of 32 researchers, each looking for something different (one tracks names, one tracks dates, one tracks sentence structure), and at the end they pool their notes.

4.2 How multi-head attention works#

Multi-head attention doesn't make the model bigger. Each head reads the whole token vector, but projects it into a much smaller space of its own:

  1. With d_model = 4096 and 32 heads, each head's slice of W_Q, W_K and W_V maps the full 4,096-number token vector down to just head_dim = 4096 / 32 = 128 numbers. In practice, one big W_Q produces all 32 heads' queries at once, and the result is cut into 32 pieces of 128. That's what split_heads does in 4.3: it splits the projected queries, keys and values, not the token itself.
  2. Each head then computes its own scores, its own softmax weights and its own blended output from its 128-number queries, keys and values, completely independently and in parallel.
  3. The heads' outputs are concatenated (glued end to end) back into one 4,096-number vector.
  4. The output projection W_O mixes the heads' findings together.
flowchart TB
    X["Token vectors<br/>(tokens × d_model)"] --> P["Project with W_Q, W_K, W_V<br/>and split into heads"]
    P --> H1["Head 1<br/>own Q, K, V<br/>own weights"]
    P --> H2["Head 2<br/>own Q, K, V<br/>own weights"]
    P --> H3["..."]
    P --> HN["Head h<br/>own Q, K, V<br/>own weights"]
    H1 --> C["Concatenate heads<br/>(tokens × d_model)"]
    H2 --> C
    H3 --> C
    HN --> C
    C --> O["Output projection W_O"]
    O --> Y["Output<br/>(tokens × d_model)"]

Because each head works in a small space, the 32 heads' projection matrices together are exactly the size of one 4,096-wide projection. Multi-head attention therefore costs about the same as one big head of size d_model, but it gives the model many independent ways to look at the context.

4.3 Try it: multi-head attention in NumPy#

python
import numpy as np

def softmax(x, axis=-1):
    x = x - x.max(axis=axis, keepdims=True)
    e = np.exp(x)
    return e / e.sum(axis=axis, keepdims=True)

rng = np.random.default_rng(seed=0)
n_tokens, d_model, n_heads = 5, 16, 4
head_dim = d_model // n_heads                 # 16 / 4 = 4 numbers per head

X = rng.normal(size=(n_tokens, d_model))      # 5 token vectors (from the embedding layer)

# Learned weights (random here). Each is d_model x d_model.
W_q, W_k, W_v, W_o = (rng.normal(size=(d_model, d_model)) * 0.3 for _ in range(4))

def split_heads(M):
    # (tokens, d_model) -> (heads, tokens, head_dim)
    return M.reshape(n_tokens, n_heads, head_dim).transpose(1, 0, 2)

Q, K, V = split_heads(X @ W_q), split_heads(X @ W_k), split_heads(X @ W_v)
print("Q per head:", Q.shape, " (heads, tokens, head_dim)")

causal = np.triu(np.ones((n_tokens, n_tokens), dtype=bool), k=1)
scores = Q @ K.transpose(0, 2, 1) / np.sqrt(head_dim)   # every head at once
weights = softmax(np.where(causal, -np.inf, scores))
per_head = weights @ V                                    # (heads, tokens, head_dim)

# Glue the heads back together, then mix them with the output projection
concat = per_head.transpose(1, 0, 2).reshape(n_tokens, d_model)
output = concat @ W_o
print("Output:", output.shape, " (same shape as the input X)")

print("\nWhat the last token attends to, in each head:")
for h in range(n_heads):
    print(f"  head {h}:", weights[h, -1].round(2))

print("\nAttention parameters:", 4 * d_model * d_model, "(W_q, W_k, W_v, W_o)")
Output10 lines
Q per head: (4, 5, 4)  (heads, tokens, head_dim)
Output: (5, 16)  (same shape as the input X)

What the last token attends to, in each head:
  head 0: [0.25 0.23 0.12 0.13 0.28]
  head 1: [0.05 0.01 0.14 0.78 0.01]
  head 2: [0.09 0.28 0.26 0.16 0.21]
  head 3: [0.08 0.2  0.22 0.22 0.28]

Attention parameters: 1024 (W_q, W_k, W_v, W_o)

Even with random weights, the four heads attend in four different ways: head 1 focuses 78% on token 4, while head 0 spreads its attention almost evenly. After training, these differences become meaningful specializations. Notice the reshape/transpose lines: splitting into heads is just a reorganization of the same numbers, with no extra parameters. Real implementations do exactly this.

4.4 What attention heads have been observed to do#

Researchers have studied trained models head by head. Some heads turn out to have clear, recognizable jobs:

Head type What it does Where it was found
Previous-token heads Each token attends mostly to the token right before it Common in early layers of GPT-style models
Syntactic heads Verbs attend to their objects, nouns to their determiners ("the"), and so on Clark et al., "What Does BERT Look At?" (2019)
Coreference heads Pronouns attend to the nouns they refer to Also Clark et al. (2019); you'll look for one yourself in section 8.1
Induction heads Spot a repeated pattern: if "A B" appeared earlier and the current token is "A" again, attend to what followed last time ("B") and help predict it Anthropic, Olsson et al., "In-context Learning and Induction Heads" (2022), proposed as an important mechanism behind in-context learning (models picking up patterns from examples in the prompt)
Retrieval heads Copy information from a specific earlier location in a long context Wu et al., "Retrieval Head Mechanistically Explains Long-Context Factuality" (2024)
Sink (no-op) heads and attention sinks Put most of their weight on the very first token when they have nothing useful to do (some papers call such heads "dormant") Xiao et al., "Efficient Streaming Language Models with Attention Sinks" (2023); you'll see this in 8.1

The headline capability tied to these specialised heads is in-context learning: a model with frozen weights performs a task it was never trained on, using only examples placed in the prompt — no gradient update, no fine-tuning. Olsson et al. (2022) argued that induction heads are a key mechanism: the model spots the pattern formed by your examples and continues it for the new input. This is why lesson 01, 7.4's "change the context, not the weights" framing works at all — the examples you send are, in effect, training data delivered per request and billed by the token. Module 04 owns the techniques for writing those examples well.

Three important caveats:

  • Most heads are not this clean. Many have mixed or unreadable roles, and a head's behaviour changes with the input.
  • Heads are redundant. Michel et al., "Are Sixteen Heads Really Better than One?" (2019), removed a large share of heads from trained models with little loss in quality.
  • The real work is done by heads and MLPs together across many layers (this is what interpretability research calls circuits). A single head is rarely the whole story (lesson 01, Part 9).

What this means for you as an engineer: num_attention_heads and num_key_value_heads in a config tell you about memory and speed, not about how intelligent a model is. Few-shot examples and quoting from supplied documents work because some heads specialize in finding and copying earlier patterns, so put the examples and documents you want copied clearly in the context.


Part 5: Positional information#

Deep-dive

5.1 Attention alone is blind to word order#

Look back at the four steps of attention: score, scale, softmax, blend. Nothing in them uses a token's position. The scores depend only on the vectors' contents. That means that if you shuffle the input tokens, every token gets exactly the same output vector as before, just in a different row. The model would see "dog bites man" and "man bites dog" as the same bag of words.

Let's prove it (with bidirectional attention, so the mask doesn't get involved):

python
import numpy as np

def softmax(x, axis=-1):
    x = x - x.max(axis=axis, keepdims=True)
    e = np.exp(x)
    return e / e.sum(axis=axis, keepdims=True)

def self_attention(X, W_q, W_k, W_v):
    Q, K, V = X @ W_q, X @ W_k, X @ W_v
    weights = softmax(Q @ K.T / np.sqrt(Q.shape[-1]))
    return weights @ V

rng = np.random.default_rng(seed=0)
d = 8
vocab = {w: rng.normal(size=d) for w in ["dog", "bites", "man"]}   # one vector per word
W_q, W_k, W_v = (rng.normal(size=(d, d)) for _ in range(3))

def run(sentence):
    X = np.stack([vocab[w] for w in sentence.split()])
    return dict(zip(sentence.split(), self_attention(X, W_q, W_k, W_v)))

a = run("dog bites man")
b = run("man bites dog")
for word in ["dog", "bites", "man"]:
    print(f"'{word}' gets the same output vector in both sentences:", np.allclose(a[word], b[word]))
Output3 lines
'dog' gets the same output vector in both sentences: True
'bites' gets the same output vector in both sentences: True
'man' gets the same output vector in both sentences: True

Who bit whom is completely lost. Order matters enormously in language, so every transformer adds positional information in some way. There are three main families.

5.2 Sinusoidal positions (the original transformer)#

The 2017 transformer added a fixed position vector to each token's embedding before the first layer. Each position vector is built from sine and cosine waves at different speeds: the first numbers in the vector oscillate quickly as the position increases, and later numbers oscillate more and more slowly.

Think of a clock: the second hand moves fast, the minute hand slowly and the hour hand very slowly. Read all three together and you know the exact time. Read the fast and slow waves together and you know the exact position.

python
import numpy as np

def sinusoidal_positions(n_positions, d):
    """The original transformer's fixed position vectors."""
    pos = np.arange(n_positions)[:, None]                 # 0, 1, 2, ...
    freq = 1 / 10000 ** (np.arange(0, d, 2) / d)          # from fast waves to very slow waves
    pe = np.zeros((n_positions, d))
    pe[:, 0::2] = np.sin(pos * freq)
    pe[:, 1::2] = np.cos(pos * freq)
    return pe

pe = sinusoidal_positions(n_positions=50, d=8)
np.set_printoptions(precision=2, suppress=True)
for p in [0, 1, 2, 49]:
    print(f"position {p:>2}:", pe[p])
Output4 lines
position  0: [0. 1. 0. 1. 0. 1. 0. 1.]
position  1: [0.84 0.54 0.1  1.   0.01 1.   0.   1.  ]
position  2: [ 0.91 -0.42  0.2   0.98  0.02  1.    0.    1.  ]
position 49: [-0.95  0.3  -0.98  0.19  0.47  0.88  0.05  1.  ]

The first pair of numbers changes a lot from one position to the next (the "second hand"), while the last pair has barely moved even by position 49 (the "hour hand"). Every position gets a unique pattern, and no training is needed.

5.3 Learned absolute positions (GPT-2, BERT)#

A simpler idea: give the model a second embedding table, with one learned vector per position (position 0, position 1, ...), and add it to the token's embedding. GPT-2 and BERT do this. GPT-2's config calls the table size n_positions (1,024), and BERT's calls it max_position_embeddings (512).

The catch is a hard limit: there's simply no row for position 1,025 in GPT-2. The model can't process longer inputs, and you can't fix that without retraining. This is the most direct example of position encoding setting the context window.

5.4 RoPE: rotary position embeddings#

Almost every modern open LLM uses RoPE (rotary position embedding, Su et al., 2021): Llama, Qwen, Mistral, Gemma, DeepSeek and OpenAI's open-weight gpt-oss models all list RoPE settings such as rope_theta in their configs. RoPE works differently from the two approaches above:

  • It doesn't add anything to the token embeddings. Instead, inside every attention layer, it rotates each query and key vector by an angle that grows with the token's position. Values aren't rotated.
  • The vector is split into pairs of numbers, and each pair is rotated like a clock hand, with each pair spinning at its own speed (fast for the first pairs, slow for the last, just like the sinusoidal waves).

Here's the key property. The attention score between a query and a key is a dot product. When both are rotated, their dot product depends on their contents and on the difference between their rotation angles, never on the two angles themselves. Rotate the query by "position 10" and the key by "position 8", and the difference is "2 positions' worth". Rotate them by 1,000 and 998 and the difference is still "2 positions' worth". So RoPE makes attention scores depend on how far apart two tokens are, not on where they are in absolute terms. That matches how language works: "the" right before "cat" means the same thing at the start of a document as on page 40.

The analogy: two clock hands. What a rotation-based score "sees" is the angle between the hands, which is the same at 3:10 as at 9:10.

python
import numpy as np

def rope(x, position, base=10000.0):
    """Rotate each pair of numbers in x by an angle that grows with the position."""
    d = x.shape[-1]
    freq = 1 / base ** (np.arange(0, d, 2) / d)    # one rotation speed per pair
    angle = position * freq
    cos, sin = np.cos(angle), np.sin(angle)
    x1, x2 = x[0::2], x[1::2]                       # split into pairs
    out = np.empty_like(x)
    out[0::2] = x1 * cos - x2 * sin                 # standard 2-D rotation of each pair
    out[1::2] = x1 * sin + x2 * cos
    return out

rng = np.random.default_rng(seed=0)
q = rng.normal(size=8)   # a query vector (before positions are added)
k = rng.normal(size=8)   # a key vector

def score(q_pos, k_pos):
    return rope(q, q_pos) @ rope(k, k_pos)

print("Query and key 2 positions apart:")
for q_pos, k_pos in [(2, 0), (10, 8), (1000, 998)]:
    print(f"  query at {q_pos:>4}, key at {k_pos:>4}: score = {score(q_pos, k_pos):.4f}")

print("Same query and key, different distances:")
for gap in [0, 1, 5, 50]:
    print(f"  {gap:>2} positions apart: score = {score(100 + gap, 100):.4f}")

print("Rotation keeps the vector's length:",
      round(np.linalg.norm(q), 4), "->", round(np.linalg.norm(rope(q, 37)), 4))
Output10 lines
Query and key 2 positions apart:
  query at    2, key at    0: score = -1.7631
  query at   10, key at    8: score = -1.7631
  query at 1000, key at  998: score = -1.7631
Same query and key, different distances:
   0 positions apart: score = -1.4680
   1 positions apart: score = -1.6954
   5 positions apart: score = -1.1427
  50 positions apart: score = -0.8792
Rotation keeps the vector's length: 1.8627 -> 1.8627
  • Same distance, same score, whether the tokens are at positions 2 and 0 or 1,000 and 998.
  • Different distance, different score: the model can tell "right next to me" from "50 tokens back".
  • Rotation doesn't change a vector's size (its norm, which is what "length" means in the code), so RoPE injects position without distorting the content signal.

The base (10,000 here) sets how slowly the slowest pairs rotate. In configs it's called rope_theta: 10,000 in Mistral 7B v0.1, 500,000 in Llama 3.1 and 1,000,000 in Qwen2.5 and Qwen3. A larger base means slower rotation, so the angles stay distinguishable over longer distances, which is one ingredient in supporting long contexts.

5.5 Other positional schemes#

Scheme How it works Used by
Sinusoidal Fixed sine/cosine waves added to embeddings Original 2017 transformer
Learned absolute A trained vector per position added to embeddings GPT-2, BERT, early GPT-3-era models
Relative position bias A learned bonus or penalty added to each score, based on the distance between tokens (grouped into "buckets") T5 (its config has relative_attention_num_buckets)
ALiBi A fixed penalty on each score that grows with distance, so far-away tokens get slightly less attention BLOOM, MPT (Press et al., "Train Short, Test Long", 2021)
RoPE Rotate queries and keys by position; scores depend on relative distance Most modern LLMs
NoPE No explicit positions; rely on the causal mask Some layers of recent models: Llama 4 (Meta's "iRoPE" design; Llama 4 Scout's config marks every fourth of its 48 layers as position-free in no_rope_layers) and IBM Granite 4.0-H

5.6 Positions and context-length limits#

Every model has a maximum context length (lesson 07 covers what it means for your application). Positional encoding is one of the reasons:

  • Learned absolute positions set a hard limit: no table row, no position. GPT-2 stops at 1,024 tokens, and BERT at 512.
  • RoPE has no table, but it still has a practical limit. During training, the model only ever sees rotation angles up to its training length. Feed it a position far beyond that and the query–key angles are combinations it has never encountered, and quality usually collapses. So a RoPE model's context is limited by what it was trained on, not by a number in a table.
  • Context extension. Labs train most of a model on shorter sequences (which is far cheaper, see Part 10) and then extend it. The common trick is to rescale the rotation angles so that long positions map onto angles the model already knows, followed by a short phase of training on long texts. The methods have names you'll see in configs and model cards: position interpolation (Chen et al., 2023), NTK-aware scaling, YaRN (Peng et al., 2023) and Llama 3's own llama3 variant. They appear in config.json as a rope_scaling entry. Some models also let you switch scaling on at inference with no further training: Qwen2.5-Instruct's model card describes adding a YaRN rope_scaling entry yourself, and warns that this static scaling may reduce quality on shorter texts, so it advises enabling it only when you need the long context.

Real configs show this clearly:

Model rope_scaling in its config.json What it means
Llama 3.1 8B / 70B rope_type: llama3, factor: 8.0, original_max_position_embeddings: 8192 Pretrained at 8,192 tokens, extended 8× to 131,072 (max_position_embeddings)
DeepSeek-V3 type: yarn, factor: 40, original_max_position_embeddings: 4096 Extended from 4,096 with YaRN to 163,840
gpt-oss-20b rope_type: yarn, factor: 32.0, original_max_position_embeddings: 4096 Extended with YaRN to 131,072
Qwen2.5-7B-Instruct none (max_position_embeddings: 32768) The model card says the config is set for 32,768 tokens, and you add a YaRN rope_scaling entry yourself to use up to 131,072

Positional reach is only one of three limits on context length. The other two come later in this lesson: compute, which grows roughly quadratically with length (Part 10), and memory, because the KV cache grows with every token (Part 11). On top of all three, models often use long contexts less reliably than short ones, a quality problem covered in lesson 07, 10.2.

What this means for you as an engineer: a context window is partly a property of the positional scheme and the length a model was trained on. Treat any claim of "extended context" (rope_scaling, YaRN) as something to test at the lengths you'll actually use (lesson 07, 10.2).


Part 6: The transformer block#

Attention is one ingredient. A transformer block (also called a transformer layer or decoder layer) combines it with three more: an MLP, residual connections and normalization. An LLM is mostly the same block repeated dozens of times.

6.1 Two jobs: communicate, then compute#

Each block does two things, one after the other:

  1. Attention: tokens exchange information. This is the only place in the whole model where information moves between tokens. "Bank" learns about "river" here.
  2. MLP: each token processes what it gathered, on its own. The same small neural network is applied to every token's vector separately. There's no mixing between tokens in this step.

A common way to put it is "communication, then computation". Back in the meeting room, attention is the discussion, and the MLP is each person going back to their desk to think about what they heard and update their notes.

6.2 The MLP (feed-forward network)#

The MLP is a small neural network: dense layers with an activation in between (see lesson 01, 3.1, an optional lesson, for the background). In a transformer it's usually called the feed-forward network (FFN) or MLP block, and its shape is always:

  1. Expand: a dense layer that widens each token's vector from hidden_size to a larger intermediate_size. In GPT-2 that's 768 → 3,072 (4×), and in Llama 3.1 8B 4,096 → 14,336 (3.5×).
  2. Activate: a non-linear activation (lesson 01, 2.5). GPT-2 uses GELU (its config says "activation_function": "gelu_new", a GELU approximation).
  3. Contract: a dense layer that projects back down to hidden_size.

Most modern LLMs use a gated variant called SwiGLU (Shazeer, "GLU Variants Improve Transformer", 2020). It has three matrices instead of two:

  • gate_proj and up_proj both expand the vector to intermediate_size.
  • The gate path goes through the SiLU activation (configs say "hidden_act": "silu") and is multiplied, number by number, with the up path. The gate learns to decide how much of each expanded feature to let through.
  • down_proj contracts back to hidden_size.

Because SwiGLU uses three matrices instead of two, the original recipe shrinks intermediate_size to about two-thirds of a classic 4× MLP (about 2.7 × hidden_size) to keep the parameter count the same. In practice, models choose a range of ratios: 3.5× in Llama 3.1 8B and 5.4× in Qwen2.5-0.5B.

The MLPs hold most of a transformer's parameters, around two-thirds or more in typical modern LLMs with a billion parameters or more, as you'll measure in section 7.6. Research suggests they store much of the model's factual knowledge: Geva et al., "Transformer Feed-Forward Layers Are Key-Value Memories" (2021), found MLP neurons that respond to specific input patterns and push the prediction towards related output tokens.

6.3 Residual connections: the residual stream#

Each sublayer doesn't replace a token's vector; its output is added to it:

text
x = x + attention(x)
x = x + mlp(x)

This is a residual connection (or skip connection, from the 2015 ResNet image models). It looks like a small detail, but it's what makes deep transformers work:

  • Layers make edits, not rewrites. Each sublayer only has to compute a change to add. If a layer has nothing useful to contribute for some token, it can output something close to zero and the token passes through unchanged.
  • Training signals flow freely. During backpropagation (lesson 01, 5.3), the "+ x" gives gradients a direct path from the output back to the earliest layers, avoiding the vanishing gradient problem. Without residual connections, stacks of 30 to 100+ layers would be close to untrainable.

Interpretability researchers call the vector that flows through this chain of additions the residual stream (Elhage et al., "A Mathematical Framework for Transformer Circuits", Anthropic, 2021). A good mental image is a shared whiteboard for each token: the embedding writes the first notes, and then every attention and MLP sublayer in every block reads the whiteboard and adds its own notes. The final whiteboard is what predicts the next token.

6.4 Layer normalization: LayerNorm, RMSNorm, pre-norm#

Numbers flowing through dozens of layers can drift: some vectors grow huge, others shrink, and training becomes unstable. Normalization rescales each token's vector to a standard size before it's used.

LayerNorm RMSNorm
What it does Shifts each token's vector so its numbers average 0, then scales them to a standard spread, then applies a learned gain and bias Only scales the vector to a standard size (its root mean square, "RMS"), then applies a learned gain. No centring, no bias
Cost Slightly more computation Slightly cheaper, and works as well in practice
Used by Original transformer, GPT-2, BERT Llama, Qwen, Mistral, Gemma, DeepSeek and most modern LLMs (Zhang and Sennrich, 2019)
Config field layer_norm_epsilon / layer_norm_eps rms_norm_eps

(The eps value is a tiny number added to avoid dividing by zero.)

Where the normalization goes matters even more than which kind:

  • Post-norm (the original 2017 transformer): normalize after adding the residual: x = norm(x + attention(x)). Deep post-norm models are hard to train and need careful learning-rate warmup.
  • Pre-norm (GPT-2 onwards, and almost every modern LLM): normalize the input of each sublayer and leave the residual stream itself untouched: x = x + attention(norm(x)). This keeps a clean path through the additions and makes deep models train much more stably (Xiong et al., "On Layer Normalization in the Transformer Architecture", 2020). Pre-norm models add one final norm after the last block, because the residual stream itself was never normalized.

6.5 One block, end to end#

Here is a modern pre-norm decoder block, as used in Llama, Qwen and Mistral-style models:

flowchart TB
    IN["Residual stream in<br/>(tokens × hidden_size)"] --> N1["RMSNorm"]
    N1 --> ATT["Multi-head causal self-attention<br/>(Q, K, V projections, RoPE on Q and K,<br/>causal mask, softmax, W_O)"]
    ATT --> ADD1(("+"))
    IN --> ADD1
    ADD1 --> N2["RMSNorm"]
    N2 --> MLP["MLP / FFN<br/>(SwiGLU: gate_proj, up_proj,<br/>SiLU, down_proj)"]
    MLP --> ADD2(("+"))
    ADD1 --> ADD2
    ADD2 --> OUT["Residual stream out<br/>(same shape)"]

The two lines going straight down the right of each "+" are the residual connections: the stream flows past each sublayer, and each sublayer's output is added to it.

6.6 Try it: a transformer block in NumPy#

This is a complete, working pre-norm block with RMSNorm, multi-head causal attention, a SwiGLU MLP and residual connections. It's the same computation real LLMs perform, minus RoPE (to keep it short) and with tiny sizes.

python
import numpy as np

rng = np.random.default_rng(seed=0)
d_model, n_heads, d_ff = 16, 4, 64
head_dim = d_model // n_heads

def softmax(x, axis=-1):
    x = x - x.max(axis=axis, keepdims=True)
    e = np.exp(x)
    return e / e.sum(axis=axis, keepdims=True)

def rms_norm(x, gain, eps=1e-6):
    # Rescale each token's vector to a typical size of 1, then apply a learned gain
    return x / np.sqrt(np.mean(x**2, axis=-1, keepdims=True) + eps) * gain

def silu(x):
    return x / (1 + np.exp(-x))

def causal_self_attention(x, p):
    n = x.shape[0]
    def heads(M):  # (tokens, d_model) -> (heads, tokens, head_dim)
        return M.reshape(n, n_heads, head_dim).transpose(1, 0, 2)
    Q, K, V = heads(x @ p["W_q"]), heads(x @ p["W_k"]), heads(x @ p["W_v"])
    scores = Q @ K.transpose(0, 2, 1) / np.sqrt(head_dim)
    scores = np.where(np.triu(np.ones((n, n), dtype=bool), k=1), -np.inf, scores)
    out = softmax(scores) @ V
    return out.transpose(1, 0, 2).reshape(n, d_model) @ p["W_o"]

def swiglu_mlp(x, p):
    # Expand to d_ff, gate one path with the other, then project back to d_model
    return (silu(x @ p["W_gate"]) * (x @ p["W_up"])) @ p["W_down"]

def transformer_block(x, p):
    x = x + causal_self_attention(rms_norm(x, p["norm1"]), p)   # 1. tokens share information
    x = x + swiglu_mlp(rms_norm(x, p["norm2"]), p)              # 2. each token "thinks" on its own
    return x

def init_block():
    s = 0.2
    return {
        "norm1": np.ones(d_model), "norm2": np.ones(d_model),
        "W_q": rng.normal(size=(d_model, d_model)) * s, "W_k": rng.normal(size=(d_model, d_model)) * s,
        "W_v": rng.normal(size=(d_model, d_model)) * s, "W_o": rng.normal(size=(d_model, d_model)) * s,
        "W_gate": rng.normal(size=(d_model, d_ff)) * s, "W_up": rng.normal(size=(d_model, d_ff)) * s,
        "W_down": rng.normal(size=(d_ff, d_model)) * s,
    }

block = init_block()
x = rng.normal(size=(6, d_model))         # 6 tokens, each a 16-number vector
y = transformer_block(x, block)
print("Input shape: ", x.shape)
print("Output shape:", y.shape, "(a block never changes the shape)")

attn = sum(block[k].size for k in ["W_q", "W_k", "W_v", "W_o"])
mlp = sum(block[k].size for k in ["W_gate", "W_up", "W_down"])
norms = block["norm1"].size + block["norm2"].size
print(f"Parameters: attention {attn}, MLP {mlp}, norms {norms}")
print(f"The MLP holds {mlp / (attn + mlp + norms):.0%} of this block's parameters")
Output4 lines
Input shape:  (6, 16)
Output shape: (6, 16) (a block never changes the shape)
Parameters: attention 1024, MLP 3072, norms 32
The MLP holds 74% of this block's parameters

Look at transformer_block: the entire architecture of a modern LLM layer is two lines. Everything else is the helper functions those lines call. Notice too that even in this toy, the MLP has three times as many parameters as attention.

6.7 Stacking blocks#

Because a block's output has exactly the same shape as its input, blocks can be stacked: the output of block 1 is the input of block 2, and so on. Every block has the same structure but its own weights. The number of blocks is the num_hidden_layers field in a config: 12 in GPT-2 small, 24 in Qwen2.5-0.5B, 32 in Llama 3.1 8B, 61 in DeepSeek-V3 and 80 in Llama 3.1 70B.

What happens across the depth, broadly (as in lesson 01, 3.4):

Depth What research suggests tends to happen
Early blocks Surface features: which word piece this is, the previous tokens, simple syntax
Middle blocks Meaning in context, relationships between entities, recalling facts
Late blocks Shaping the representation into a prediction of the next token

These are tendencies, not strict rules. One technique you may see, the logit lens, applies the model's final output layer to the residual stream in the middle of the model, to see what it would predict at that depth. Predictions typically sharpen gradually from block to block, which fits the "each layer adds notes to the whiteboard" picture.

What this means for you as an engineer: num_hidden_layers and hidden_size are the two numbers that most determine a model's size, latency and memory. You can read them, and estimate what they imply, before downloading anything.


Part 7: The full forward pass of a decoder-only LLM#

Deep-dive

7.1 From text to next-token probabilities#

Here's everything an LLM does to process a prompt, end to end. This is the forward pass from lesson 01, 3.2, now with real parts:

flowchart TB
    T["Text: 'The cat sat on'"] --> TOK["1. Tokenizer (lesson 02)<br/>text → token IDs"]
    TOK --> EMB["2. Embedding lookup (lesson 03)<br/>each ID → a vector of hidden_size numbers<br/>table size: vocab_size × hidden_size"]
    EMB --> POS["Positions: added here for GPT-2-style models;<br/>RoPE models apply them inside each attention layer"]
    POS --> B1["3. Transformer block 1"]
    B1 --> B2["Transformer block 2"]
    B2 --> BD["... num_hidden_layers blocks in total ..."]
    BD --> FN["4. Final norm"]
    FN --> HEAD["5. LM head (unembedding)<br/>hidden_size → vocab_size scores (logits)<br/>for every position"]
    HEAD --> SM["6. Softmax on the last position's logits<br/>→ a probability for every token in the vocabulary"]
    SM --> SAMP["7. Pick the next token (lesson 05)"]

Step by step, with the shapes for a 4-token prompt and Llama 3.1 8B's sizes:

Step What happens Shape of the data
1. Tokenize Text becomes token IDs (lesson 02) 4 integers
2. Embed Each ID selects one row of the embedding table (lesson 03) 4 × 4,096
3. Blocks 32 blocks, each with attention (tokens share information) and an MLP (each token processes) 4 × 4,096 throughout
4. Final norm One last RMSNorm on the residual stream 4 × 4,096
5. LM head A dense layer from 4,096 numbers to 128,256 scores, one per vocabulary token: the logits 4 × 128,256
6. Softmax The last row of logits becomes probabilities that sum to 1 (lesson 01, 3.6) 128,256 probabilities
7. Choose One token is picked from those probabilities, appended, and the loop repeats (lesson 05) 1 token ID

The LM head (language-modelling head) is also called the unembedding, because it does the reverse of the embedding: the embedding turns a token into a vector, and the LM head turns a vector into a score for every possible token.

7.2 Try it: a tiny LLM forward pass#

Add this below the code from 6.6, in the same file. It builds a complete (untrained) decoder-only language model out of the block you just wrote:

python
# --- Add this below the code from 6.6, in the same file ---
vocab = ["<bos>", "the", "cat", "sat", "on", "mat", "dog", "ran", "."]
vocab_size, n_layers = len(vocab), 3

embedding = rng.normal(size=(vocab_size, d_model))      # one row per token (lesson 03)
blocks = [init_block() for _ in range(n_layers)]        # N identical-shaped blocks
final_norm = np.ones(d_model)
lm_head = embedding.T                                   # weight tying: reuse the embedding matrix

token_ids = [vocab.index(w) for w in ["<bos>", "the", "cat", "sat", "on"]]

x = embedding[token_ids]                                # 1. look up token vectors
print("after embedding:  ", x.shape)
for i, blk in enumerate(blocks):                        # 2. run every block in order
    x = transformer_block(x, blk)
print(f"after {n_layers} blocks:   ", x.shape)
x = rms_norm(x, final_norm)                             # 3. final norm
logits = x @ lm_head                                    # 4. a score for every vocabulary entry
print("logits:           ", logits.shape, "(one row per position, one column per vocab entry)")

probs = softmax(logits[-1])                             # 5. only the LAST row predicts what comes next
for i in np.argsort(probs)[::-1][:3]:
    print(f"  next token '{vocab[i]}': {probs[i]:.1%}")
Output · after the 6.6 output6 lines
after embedding:   (5, 16)
after 3 blocks:    (5, 16)
logits:            (5, 9) (one row per position, one column per vocab entry)
  next token 'on': 90.6%
  next token 'the': 8.3%
  next token 'ran': 1.0%

That's a real decoder-only language model: tokens in, a probability for every vocabulary entry out. Its prediction is meaningless, because the weights are random and it has never been trained (lesson 06 covers how training sets them). It happens to predict "on" again, most likely because its last input token was "on": with random blocks that make only small edits, the residual stream is still dominated by that token's own embedding, and with tied weights the LM head scores the token most similar to its own embedding highest. Training is what turns this machinery into something that predicts "the" after "The cat sat on".

7.3 Every position predicts, but only the last one matters for generation#

The LM head produces logits for every position, not just the last: a 5 × 9 table in the demo. What happens to them depends on the phase:

  • During training, every row is used. Row 1 is scored against the real token 2, row 2 against the real token 3, and so on. Thanks to the causal mask, one forward pass over a sequence of n tokens yields n training examples at once (3.1).
  • During generation, only the last row matters: it's the model's prediction of the next token. The other rows are discarded.

This leads to the two phases of serving a request, which lesson 05, 1.2 measures on your laptop, and which you'll meet again in Parts 10 and 11 and in lesson 07:

Phase What happens What it determines
Prefill The whole prompt is processed in one parallel forward pass The time to first token (TTFT): a long prompt means a longer wait before anything appears
Decode The model generates one token at a time, each needing its own forward pass The tokens per second while the answer streams in

7.4 Weight tying#

Some models reuse the embedding matrix as the LM head, a trick called weight tying (lesson 03, 1.5 explains the idea). In config.json it's the tie_word_embeddings field:

  • true for GPT-2 and Qwen2.5-0.5B. For Qwen2.5-0.5B the shared matrix is 151,936 × 896 = 136 million parameters, more than a quarter of the whole model, so tying saves a lot.
  • false for larger models such as Qwen2.5-7B and Llama 3.1 8B, where the vocabulary matrices are a smaller share of the total. The parameter count in 7.6 adds a separate LM head only when this field is false.

7.5 Reading a real config.json#

Every open-weight model on Hugging Face ships a config.json (lesson 01, 4.7) that describes its architecture. You can load one without downloading the weights:

python
from transformers import AutoConfig

config = AutoConfig.from_pretrained("Qwen/Qwen2.5-0.5B")   # downloads only config.json (a few KB)

fields = ["vocab_size", "hidden_size", "num_hidden_layers", "num_attention_heads",
          "num_key_value_heads", "intermediate_size", "max_position_embeddings",
          "hidden_act", "rms_norm_eps", "tie_word_embeddings", "rope_parameters"]
for f in fields:
    print(f"{f:<25} {getattr(config, f)}")
print(f"{'head_dim (derived)':<25} {config.hidden_size // config.num_attention_heads}")
Output12 lines
vocab_size                151936
hidden_size               896
num_hidden_layers         24
num_attention_heads       14
num_key_value_heads       2
intermediate_size         4864
max_position_embeddings   32768
hidden_act                silu
rms_norm_eps              1e-06
tie_word_embeddings       True
rope_parameters           {'rope_theta': 1000000.0, 'rope_type': 'default'}
head_dim (derived)        64

Every field maps onto a piece of the diagram in 7.1:

Field Qwen2.5-0.5B What it is Where it lives What it affects for you
vocab_size 151,936 Number of distinct tokens Embedding table rows and LM head outputs Tokenizer efficiency (lesson 02); embedding and LM-head size
hidden_size 896 Length of each token's vector (d_model) Everywhere: the width of the residual stream Model size; KV cache size
num_hidden_layers 24 Number of transformer blocks The stack in the middle Model size; time per token
num_attention_heads 14 Query heads per attention layer Inside attention head_dim = 896 / 14 = 64
num_key_value_heads 2 Key/value heads per layer (fewer than query heads means GQA) Inside attention KV cache size (12.1)
intermediate_size 4,864 Expanded width inside the MLP Inside each MLP The bulk of the parameters
max_position_embeddings 32,768 Longest sequence the positional setup is configured for Positional encoding An upper bound on context, but check the model card (5.6)
hidden_act silu MLP activation (SiLU means a SwiGLU MLP in Qwen/Llama-style models) Inside each MLP Recognizing the design
rms_norm_eps 1e-06 The tiny constant in RMSNorm (its presence tells you the model uses RMSNorm) Norms Recognizing the design
tie_word_embeddings True Whether the LM head reuses the embedding matrix Embeddings and LM head Parameter count
rope_theta (inside rope_parameters in Transformers 5) 1,000,000 RoPE base (5.4) Inside attention Long-context behaviour

7.6 Try it: count the parameters from the config#

With the config fields, you can compute a model's exact parameter count with nothing but multiplication, and see where the parameters live. This works for Llama- and Qwen-style dense models:

python
def count_params(c):
    """Parameter count of a Llama/Qwen-style dense decoder, from config.json values."""
    d, layers, vocab = c["hidden_size"], c["num_hidden_layers"], c["vocab_size"]
    head_dim = c.get("head_dim") or d // c["num_attention_heads"]
    q_dim = c["num_attention_heads"] * head_dim
    kv_dim = c["num_key_value_heads"] * head_dim
    bias = c.get("qkv_bias", False)

    attention = (d * q_dim + (q_dim if bias else 0)            # W_q
                 + 2 * (d * kv_dim + (kv_dim if bias else 0))  # W_k and W_v (smaller with GQA)
                 + q_dim * d)                                  # W_o
    mlp = 3 * d * c["intermediate_size"]                       # gate, up and down projections
    norms = 2 * d                                              # two RMSNorms per block
    embeddings = vocab * d
    lm_head = 0 if c["tie_word_embeddings"] else vocab * d
    total = embeddings + layers * (attention + mlp + norms) + d + lm_head   # + d: final norm
    return total, {"embeddings + LM head": embeddings + lm_head,
                   "attention": layers * attention, "MLP": layers * mlp}

models = {
    "Qwen2.5-0.5B": dict(hidden_size=896, num_hidden_layers=24, num_attention_heads=14,
                         num_key_value_heads=2, intermediate_size=4864, vocab_size=151936,
                         tie_word_embeddings=True, qkv_bias=True),
    "Llama-3.1-8B": dict(hidden_size=4096, num_hidden_layers=32, num_attention_heads=32,
                         num_key_value_heads=8, intermediate_size=14336, vocab_size=128256,
                         tie_word_embeddings=False),
    "Llama-3.1-70B": dict(hidden_size=8192, num_hidden_layers=80, num_attention_heads=64,
                          num_key_value_heads=8, intermediate_size=28672, vocab_size=128256,
                          tie_word_embeddings=False),
}
for name, cfg in models.items():
    total, parts = count_params(cfg)
    shares = ", ".join(f"{k} {v / total:.0%}" for k, v in parts.items())
    print(f"{name:<14} {total:>15,}  ({shares})")
Output3 lines
Qwen2.5-0.5B       494,032,768  (embeddings + LM head 28%, attention 9%, MLP 64%)
Llama-3.1-8B     8,030,261,248  (embeddings + LM head 13%, attention 17%, MLP 70%)
Llama-3.1-70B   70,553,706,496  (embeddings + LM head 3%, attention 17%, MLP 80%)

The config values come from each model's config.json. (Qwen2 models add small bias terms to their Q, K and V projections, hence qkv_bias=True; Llama has none.) These totals are exact: in section 8.3 you'll load Qwen2.5-0.5B and count 494,032,768 parameters directly. "0.5B", "8B" and "70B" are these numbers rounded.

Three patterns worth remembering:

  • The MLPs dominate: 64% to 80% of the parameters in these three models. (Small models with large vocabularies are the exception: GPT-2 small is only 45% MLP, as 8.3 shows.)
  • The vocabulary matrices matter a lot in small models (28% of Qwen2.5-0.5B, because a 152K vocabulary is expensive relative to a 896-wide model) and very little in big ones (3% of Llama 3.1 70B).
  • Attention weights are a modest share (9% to 17%), partly because GQA makes the key and value projections small. Attention's real cost is elsewhere: compute and memory that grow with sequence length, not with parameters (Parts 10 and 11).

7.7 Reading a model's spec sheet#

Here are the key architecture numbers of some well-known open models, all taken from their config.json files on Hugging Face (checked on 11 November 2026). Being able to read a row of this table is the practical goal of this lesson.

Model Layers hidden_size Query heads / KV heads head_dim MLP width Vocabulary max_position_embeddings Notable features
GPT-2 small (2019) 12 768 12 / 12 64 3,072 50,257 1,024 Learned positions, LayerNorm, GELU, tied weights
BERT-base (2018) 12 768 12 / 12 64 3,072 30,522 512 Encoder-only, bidirectional
Qwen2.5-0.5B 24 896 14 / 2 64 4,864 151,936 32,768 GQA, RoPE, RMSNorm, SwiGLU, tied weights
Mistral 7B v0.1 32 4,096 32 / 8 128 14,336 32,000 32,768 Sliding-window attention (4,096)
Llama 3.1 8B 32 4,096 32 / 8 128 14,336 128,256 131,072 GQA, RoPE scaled 8× from 8,192
Llama 3.1 70B 80 8,192 64 / 8 128 28,672 128,256 131,072 Same design, larger
Qwen3-8B 36 4,096 32 / 8 128 12,288 151,936 40,960 GQA, QK-norm
Gemma 3 4B 34 2,560 8 / 4 256 10,240 262,208 131,072 5 local (1,024-token window) : 1 global layers
Qwen3-30B-A3B 48 2,048 32 / 4 128 768 per expert 151,936 40,960 MoE: 128 experts, 8 active per token
gpt-oss-20b 24 2,880 64 / 8 64 2,880 per expert 201,088 131,072 MoE (32 experts, 4 active); alternating 128-token sliding-window and full attention; YaRN
DeepSeek-V3 61 7,168 128 heads, MLA 192 (Q/K) / 128 (V) 2,048 per expert 129,280 163,840 MoE (256 routed experts, 8 active per token, plus 1 always-active shared expert; first 3 layers dense); MLA compresses the KV cache

Every column is something you now know how to interpret, and the "notable features" are explained in Part 12. Closed models (GPT, Claude, Gemini) don't publish this information; for those, you rely on the provider's documentation of context length, pricing and behaviour (lesson 09).

What this means for you as an engineer: from config.json alone you can work out a model's parameter count, its weight memory (lesson 01, 4.4) and its KV-cache memory (11.4): the first three numbers in any self-hosting decision.


Part 8: Looking inside a real model#

Deep-dive

8.1 Try it: attention weights in GPT-2#

Now let's look at real attention weights. This script loads GPT-2 small (124M parameters, 12 layers × 12 heads = 144 heads) and asks it to return its attention weights with output_attentions=True. We give it sentences with a pronoun, and look for a head whose pronoun token attends to the right noun.

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

tok = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2", attn_implementation="eager")  # eager = return weights
model.eval()

def attention_from(sentence, word):
    """Attention weights from `word` to every earlier token, for every layer and head."""
    ids = tok(sentence, return_tensors="pt")
    tokens = tok.convert_ids_to_tokens(ids["input_ids"][0])
    with torch.no_grad():
        out = model(**ids, output_attentions=True)
    # out.attentions: one tensor per layer, shape (batch, heads, tokens, tokens)
    att = torch.stack(out.attentions)[:, 0]              # (layers, heads, tokens, tokens)
    pos = tokens.index("Ġ" + word)                         # "Ġ" marks a leading space in GPT-2 tokens
    return [t.replace("Ġ", "") for t in tokens], pos, att[:, :, pos, :]

examples = [
    ("Mary thanked John because he had helped her.", "he", "John", "Mary"),
    ("John thanked Mary because she had helped him.", "she", "Mary", "John"),
    ("The waiter brought the soup, but it was cold.", "it", "soup", "waiter"),
]

# Find the head that, across all examples, puts the most weight on the right noun
score = 0
for sentence, word, right, wrong in examples:
    tokens, pos, att = attention_from(sentence, word)
    score = score + att[:, :, tokens.index(right)] - att[:, :, tokens.index(wrong)]
layer, head = divmod(int(score.argmax()), score.shape[1])
print(f"Best coreference-like head: layer {layer}, head {head}\n")

for sentence, word, right, wrong in examples:
    tokens, pos, att = attention_from(sentence, word)
    row = att[layer, head, : pos + 1]
    top = sorted(zip(tokens, row.tolist()), key=lambda x: -x[1])[:3]
    print(f"{sentence}\n  '{word}' attends to: " + ", ".join(f"{t} {w:.0%}" for t, w in top))

# Sentences the head was NOT chosen on: does the pattern hold?
for sentence, word in [("Peter emailed Anna because she was late.", "she"),
                       ("Yesterday Peter emailed Anna because she was late.", "she")]:
    tokens, pos, att = attention_from(sentence, word)
    top = sorted(zip(tokens, att[layer, head, : pos + 1].tolist()), key=lambda x: -x[1])[:3]
    print(f"\nHeld-out: {sentence}\n  '{word}' attends to: " + ", ".join(f"{t} {w:.0%}" for t, w in top))
    print(f"  share on the first token ('{tokens[0]}'), averaged over all 144 heads: {att[:, :, 0].mean():.0%}")
Output16 lines
Best coreference-like head: layer 6, head 0

Mary thanked John because he had helped her.
  'he' attends to: John 41%, because 28%, Mary 13%
John thanked Mary because she had helped him.
  'she' attends to: Mary 49%, because 24%, John 12%
The waiter brought the soup, but it was cold.
  'it' attends to: The 40%, soup 26%, the 11%

Held-out: Peter emailed Anna because she was late.
  'she' attends to: Peter 26%, because 25%, Anna 21%
  share on the first token ('Peter'), averaged over all 144 heads: 63%

Held-out: Yesterday Peter emailed Anna because she was late.
  'she' attends to: Anna 29%, because 23%, Yesterday 21%
  share on the first token ('Yesterday'), averaged over all 144 heads: 60%

(Layers and heads are numbered from 0.) There's a lot to learn from this small experiment:

  • A coreference-like head exists. In layer 6, head 0, "he" attends most to "John" and "she" most to "Mary": the gender cue led the pronoun to the right name, in both directions. For "it", "soup" beats "waiter".
  • Causal masking shapes what's possible. At the position of "it", GPT-2 hasn't yet seen "was cold", so it can't use the words after the pronoun. In the famous "The animal didn't cross the street because it was too tired", a causal model has to decide what "it" means before reading "tired", and refine its understanding at later positions. An encoder like BERT sees both directions at once.
  • The first token is an attention sink. Averaged over all 144 heads, about 60% of the pronoun's attention lands on the first token, whatever that token is. This is the attention sink from 4.4: when a head has nothing useful to do, it parks its weight on the first position. In the "waiter" sentence, the 40% on "The" is the sink, not coreference.
  • The held-out tests show why you must be careful. We chose layer 6, head 0 because it scored best on the first three sentences. On the first new sentence, "Peter" scores highest, but "Peter" is also the first token, where the sink lives, so this tells us nothing. When we add "Yesterday" so that the sink moves, "Anna" correctly wins, but only narrowly (29% versus 23%). The head is a real but weak, noisy coreference signal, which is typical for a small model.

8.2 Caveats when reading attention weights#

Attention visualizations are popular in demos and blog posts. Treat them with care:

  • Attention weights are not explanations. A high weight means information could flow from that token, not that it decided the output. Researchers debated this in "Attention is not Explanation" (Jain and Wallace, 2019) and "Attention is not not Explanation" (Wiegreffe and Pinter, 2019). The consensus: attention is a useful clue, not proof.
  • Values matter too. A token can get a high weight but carry a near-zero value vector, contributing almost nothing.
  • Information is already mixed. After the first layer, the vector at the "John" position contains information from earlier tokens as well. "Attending to John" in layer 6 really means "attending to whatever has accumulated at John's position".
  • Sinks distort averages, as you saw.
  • You can't do this with hosted models. OpenAI, Anthropic and Google APIs don't expose attention weights. The closest you get is per-token log probabilities on some APIs (lesson 05, 5.4). Attention inspection is an open-weights tool.

What this means for you: use attention maps for curiosity and debugging intuition, not to justify a model's decision to a customer or a regulator. If you need to know why a model answered something, test its behaviour (Module 10A) or have it cite its sources (Module 07).

8.3 Try it: where the parameters live#

Now count the parameters in two real models, grouped by component:

python
from collections import defaultdict
from transformers import AutoModelForCausalLM

def component(name):
    """Map a parameter's name to the part of the transformer it belongs to."""
    if "embed" in name or name.startswith(("transformer.wte", "transformer.wpe")):
        return "embeddings (token + position)"
    if "attn" in name:
        return "attention"
    if "mlp" in name:
        return "MLP / feed-forward"
    if "norm" in name or ".ln_" in name:
        return "normalization"
    return "other (" + name + ")"

for model_id in ["gpt2", "Qwen/Qwen2.5-0.5B"]:
    model = AutoModelForCausalLM.from_pretrained(model_id)
    counts = defaultdict(int)
    for name, p in model.named_parameters():   # tied weights (embedding = LM head) are listed once
        counts[component(name)] += p.numel()
    total = sum(counts.values())
    print(f"{model_id}: {total:,} parameters")
    for part, n in sorted(counts.items(), key=lambda kv: -kv[1]):
        print(f"  {part:<31} {n:>12,}  {n / total:5.1%}")
    print("  LM head shares the embedding matrix:",
          model.get_output_embeddings().weight is model.get_input_embeddings().weight)
Output12 lines
gpt2: 124,439,808 parameters
  MLP / feed-forward                56,669,184  45.5%
  embeddings (token + position)     39,383,808  31.6%
  attention                         28,348,416  22.8%
  normalization                         38,400   0.0%
  LM head shares the embedding matrix: True
Qwen/Qwen2.5-0.5B: 494,032,768 parameters
  MLP / feed-forward               313,786,368  63.5%
  embeddings (token + position)    136,134,656  27.6%
  attention                         44,067,840   8.9%
  normalization                         43,904   0.0%
  LM head shares the embedding matrix: True
  • Qwen2.5-0.5B's 494,032,768 matches the formula from 7.6 exactly. The architecture really is fully described by its config.
  • GPT-2's attention share (22.8%) is much bigger than Qwen's (8.9%). GPT-2 has a full key and value head for every query head (12/12), while Qwen shares 2 KV heads among 14 query heads, so its K and V matrices are 7× smaller. The MLP takes up the freed budget.
  • The "embeddings" row includes GPT-2's learned position table (1,024 × 768 = 786,432 parameters). Qwen has none, because RoPE has no parameters.
  • GPT-2's MLP share (45.5%) is lower than in the modern models of 7.6, because its 50,257 × 768 embedding table takes almost a third of such a small model.
  • Normalization is negligible in parameters (well under 0.1%), even though it's essential for stable training.

Part 9: Architecture variants#

Reference

9.1 The original transformer: encoder and decoder#

The 2017 transformer was built for translation, and had two halves:

  • An encoder reads the whole source sentence (say, English) with bidirectional self-attention, producing a contextual vector for every source token.
  • A decoder writes the translation (say, German) one token at a time, using causal self-attention over what it has written so far, plus cross-attention (2.7) to look at the encoder's vectors.

Its base configuration had 6 encoder blocks and 6 decoder blocks, a d_model of 512, 8 heads, an MLP width of 2,048, sinusoidal positions and post-norm. Since then, the field has used three variants: keep both halves, keep only the encoder, or keep only the decoder.

flowchart LR
    subgraph enc ["Encoder-only (BERT)"]
        E1["Text in"] --> E2["Encoder blocks<br/>bidirectional attention"]
        E2 --> E3["A contextual vector<br/>per token"]
    end
    subgraph encdec ["Encoder-decoder (T5, Whisper)"]
        D1["Input in"] --> D2["Encoder blocks<br/>bidirectional"]
        D2 -- "cross-attention" --> D3["Decoder blocks<br/>causal"]
        D3 --> D4["Output text,<br/>token by token"]
    end
    subgraph dec ["Decoder-only (GPT, Llama, Claude...)"]
        G1["Prompt in"] --> G2["Decoder blocks<br/>causal attention"]
        G2 --> G3["Next token,<br/>then repeat"]
    end

9.2 Encoder-only models (BERT and friends)#

BERT (Google, Devlin et al., 2018) kept only the encoder. With no causal mask, every token sees the whole text in both directions, so its contextual vectors are excellent for understanding text. BERT was pretrained with masked language modelling: hide about 15% of the tokens and predict them from both sides. (Lesson 06 covers the next-token objective used by decoder LLMs; MLM is specific to encoders and is fully described here.)

Encoder-only models don't generate text. They output vectors, which you use for:

  • Embeddings for search: most sentence-embedding models, such as all-MiniLM-L6-v2 from lesson 03, are BERT-style encoders with a pooling step (Module 06).
  • Classification: sentiment, spam, intent detection, content moderation. A small encoder fine-tuned on your labels is often far cheaper and faster than prompting an LLM.
  • Token labelling: named-entity recognition (finding names, places, products).
  • Rerankers (cross-encoders): score how well a document answers a query by reading both together (Module 07).

They're still very much alive. ModernBERT (Answer.AI, LightOn and others, December 2024) brought modern techniques to encoders: RoPE, 8,192-token context, and alternating local attention (128-token window) with global attention every third layer, according to its config. Meanwhile, some of the strongest embedding models are now built by adapting decoder-only LLMs, so the line is blurring.

9.3 Decoder-only models (GPT-style)#

OpenAI's GPT (2018) kept only the decoder, removed cross-attention and trained it on plain next-token prediction. That's the architecture of every model in this lesson's spec sheet apart from BERT, and of essentially every chat LLM.

Closed models: OpenAI, Anthropic and Google don't publish the full architectures of their current frontier models. They're widely understood to be decoder-only transformers (Google's Gemini technical reports describe Transformer decoders, with mixture-of-experts from Gemini 1.5 onwards, and OpenAI's open-weight gpt-oss models are decoder-only MoE transformers), but exact details such as layer counts and attention variants are unpublished.

9.4 Encoder-decoder models#

T5 (Google, Raffel et al., 2019) and BART (Facebook AI, now Meta, 2019) kept both halves and framed every task as "text in, text out" (T5's config even lists task prefixes such as "translate English to German: "). Encoder-decoder models are a natural fit when an input is fully available and must be transformed into a different output:

  • Translation (many dedicated translation systems)
  • Speech recognition: OpenAI's Whisper is an encoder-decoder transformer: the encoder reads audio, and the decoder writes the transcript (Module 09)
  • Summarization and other rewriting tasks, especially with smaller, fine-tuned models

9.5 Which variant is used for what today#

Variant Attention Pretraining task Typical examples What you'd use it for today
Encoder-only Bidirectional self-attention Masked language modelling BERT, RoBERTa, ModernBERT, most sentence-embedding models Embeddings, semantic search, classification, NER, reranking; cheap, fast, often self-hosted
Decoder-only Causal self-attention Next-token prediction GPT, Claude, Gemini, Llama, Qwen, Mistral, DeepSeek, Gemma, gpt-oss Chat, generation, reasoning, coding, agents, extraction: almost every LLM API call
Encoder-decoder Bidirectional encoder + causal decoder + cross-attention Span corruption / denoising, then tasks T5, Flan-T5, BART, Whisper Speech-to-text, translation, fine-tuned summarization; less common for new general-purpose models

9.6 Why decoder-only won for general-purpose LLMs#

  • One simple objective that scales. Next-token prediction turns every piece of text into training data (lesson 01, 1.2), and quality kept improving predictably with scale (lesson 06).
  • One model, every task. A decoder can do translation, summarization, classification and coding just by being prompted. There's no need for a separate head or output format per task.
  • Generation is efficient. Causal attention means earlier tokens never need recomputing, which is what makes the KV cache possible (Part 11).
  • Simplicity. One stack of identical blocks is easier to scale, parallelize and optimize than two stacks joined by cross-attention.

What this means for you: use decoder-only LLMs (through APIs or open weights) for generation and reasoning, and consider a small encoder model whenever the task is "turn text into a vector or a label" at high volume and low cost.

9.7 Transformers beyond text#

The same block works on anything you can turn into a sequence of vectors:

  • Images: the Vision Transformer (ViT, Dosovitskiy et al., 2020) cuts an image into small patches (for example 16 × 16 pixels) and treats each patch as a token.
  • Audio: short slices of a spectrogram become tokens (as in Whisper).
  • Multimodal LLMs: an image or audio encoder turns the input into vectors placed into the LLM's sequence alongside text tokens, so the same attention layers can look across both. This is why images consume tokens from your context window. Module 09 covers the practical side.

Part 10: The cost of attention#

10.1 Every token against every token#

Attention compares every token with every other token. For a sequence of n tokens, that's n × n scores per head per layer: double the length and you get four times as many scores. Mathematicians call this growth quadratic, and it's the most important cost fact about transformers.

The rest of the model doesn't grow that way. The Q/K/V/O projections and the MLP process each token separately, so their cost grows linearly: double the tokens, double the work.

Let's estimate the compute for one layer of Llama 3.1 8B as the prompt gets longer, using the rough rule from lesson 01, 7.1 (about 2 operations per weight per token) for the linear parts, plus the score and blend steps of attention:

python
# Llama 3.1 8B shapes, from its config.json
d, d_ff, n_heads, kv_dim = 4096, 14336, 32, 8 * 128

# Per layer, the weight matrices cost about 2 operations per weight per token (lesson 01, 7.1)
weights_per_layer = (2 * d * d) + (2 * d * kv_dim) + (3 * d * d_ff)   # Q,O + K,V + MLP

def layer_ops(n):
    """Rough operations for one layer processing n tokens at once (the prompt)."""
    matmuls = 2 * weights_per_layer * n        # grows in a straight line with n
    attention_core = 4 * n * n * d             # every token scored against every token: grows with n * n
    return matmuls, attention_core

print(f"{'tokens':>8} {'pairs scored':>16} {'attention share':>16} {'cost vs 1K':>11}")
base = sum(layer_ops(1_024))
for n in [1_024, 8_192, 32_768, 131_072]:
    m, a = layer_ops(n)
    print(f"{n:>8,} {n * n:>16,} {a / (m + a):>15.0%} {(m + a) / base:>10.0f}x")

n = 131_072
score_matrix_bytes = n * n * n_heads * 2       # every head's full score table at 16-bit
print(f"\nStoring all of one layer's attention scores at 128K tokens: {score_matrix_bytes / 1e12:.1f} TB")
Output7 lines
  tokens     pairs scored  attention share  cost vs 1K
   1,024        1,048,576              4%          1x
   8,192       67,108,864             24%         10x
  32,768    1,073,741,824             55%         69x
 131,072   17,179,869,184             83%        730x

Storing all of one layer's attention scores at 128K tokens: 1.1 TB

What the numbers say:

  • At short lengths, attention is cheap. At 1K tokens, the score-and-blend part of attention is only 4% of the layer's work; the weight matrices dominate, and cost grows roughly in line with length.
  • At long lengths, attention dominates. Somewhere around 30K tokens for a model of this size, the quadratic part overtakes everything else, and at 128K it's 83% of the work.
  • 128× more tokens costs about 730× more compute for processing the prompt, not 128×.
  • The full score table is enormous. Storing every head's scores for one layer at 128K tokens would take about 1.1 TB. Real systems never store it in full; FlashAttention computes it in small pieces.

(These are rough estimates that ignore details such as the causal mask halving the needed scores, but the shape of the growth is what matters.)

10.2 Prefill vs decode: two different bottlenecks#

The quadratic cost hits the two phases from 7.3 (defined and measured in lesson 05, 1.2) differently:

Prefill (processing your prompt) Decode (generating each new token)
Work All prompt tokens at once, in big parallel matrix multiplications One new token at a time, attending to all earlier tokens through the KV cache (Part 11)
Attention cost Quadratic in prompt length Linear in context length per generated token: token 10,001 compares itself with 10,000 cached keys
Bottleneck Compute: the GPU's arithmetic speed Memory bandwidth: every step must read all the model's weights and the whole KV cache from GPU memory just to produce one token
You notice it as Time to first token (TTFT) Tokens per second while streaming

Serving engines batch many users into each decode step, so one read of the weights serves everyone in the batch. Each user's KV cache, though, must still be read separately, which is why long contexts reduce how many users a GPU can serve (11.4).

Long contexts therefore slow down both phases: a long prompt takes longer to prefill, and every token generated after it is slightly slower because there's more cache to read.

10.3 What this means for you as an engineer#

  • Context isn't free. Each extra token in the prompt costs money (input-token pricing), adds latency (prefill), and makes every output token a little slower. "Just put everything in the context" has a real price, even with a 1M-token window. Lesson 07, 6.3 covers the cost, latency and quality trade-offs in practice.
  • Long-context capability is expensive to build and serve, which is why the longest context windows are a selling point, why serving them takes engineering effort, and why some providers price very long prompts differently. Check current pricing pages rather than assuming (lesson 09).
  • Shorter, well-chosen context usually beats more context. Retrieving the right 2,000 tokens (Module 07) is often faster, cheaper and more accurate than sending 200,000.

Part 11: The KV cache#

11.1 The waste in naive generation#

LLMs generate one token at a time (lesson 05): run the forward pass, pick a token, append it, and run the forward pass again on the longer sequence. Done naively, generating token 1,001 means re-processing all 1,000 previous tokens through every layer, even though nothing about them has changed. Generating a 1,000-token answer would repeat nearly the same work a thousand times.

11.2 The insight: past keys and values never change#

Thanks to the causal mask (3.4), a token's key and value in every layer depend only on that token itself and the tokens before it. Appending new tokens can never change them. So:

  • Compute each token's keys and values once, in every layer, and store them. This store is the KV cache.
  • For each new token, compute only its own query, key and value, add its key and value to the cache, and attend over the whole cache.
  • Queries are not cached. A query is only needed by the token that asks it, at the moment it's processed. Past tokens never need to ask again.

Back in the meeting room: when a newcomer arrives, the others don't re-introduce themselves. Everyone's name badge (key) and notes (value) stay on the table, and the newcomer just asks their question (query) and reads them.

flowchart LR
    P["Prefill:<br/>process the whole prompt once"] --> C[("KV cache:<br/>keys and values for every token,<br/>every layer, every KV head")]
    C --> D1["Decode step 1:<br/>new token's Q, K, V;<br/>attend over the cache"]
    D1 -- "append its K and V" --> C
    C --> D2["Decode step 2:<br/>same again"]
    D2 -- "append its K and V" --> C

11.3 Try it: the KV cache gives identical results with less work#

This demo generates outputs for six tokens arriving one at a time, first by recomputing everything at each step, then with a KV cache, and checks that the results are identical:

python
import numpy as np

def softmax(x, axis=-1):
    x = x - x.max(axis=axis, keepdims=True)
    e = np.exp(x)
    return e / e.sum(axis=axis, keepdims=True)

rng = np.random.default_rng(seed=0)
d = 8
W_q, W_k, W_v = (rng.normal(size=(d, d)) for _ in range(3))
X = rng.normal(size=(6, d))     # 6 token vectors, arriving one at a time during generation

# Way 1: no cache. At every step, recompute Q, K, V for the WHOLE sequence so far.
no_cache_outputs, kv_computations = [], 0
for t in range(1, len(X) + 1):
    seen = X[:t]
    Q, K, V = seen @ W_q, seen @ W_k, seen @ W_v
    kv_computations += t                                  # K and V recomputed for t tokens
    w = softmax(Q @ K.T / np.sqrt(d) + np.triu(np.full((t, t), -np.inf), k=1))
    no_cache_outputs.append((w @ V)[-1])                  # we only need the newest token's output

# Way 2: KV cache. Compute K and V once per token, keep them, and reuse them.
k_cache, v_cache, cached_outputs, cache_computations = [], [], [], 0
for t in range(len(X)):
    x = X[t]
    q = x @ W_q                                           # query: only for the new token
    k_cache.append(x @ W_k)                               # key and value: computed once, stored
    v_cache.append(x @ W_v)
    cache_computations += 1
    K, V = np.stack(k_cache), np.stack(v_cache)
    w = softmax(q @ K.T / np.sqrt(d))                     # no mask needed: the cache only holds the past
    cached_outputs.append(w @ V)

print("Same outputs with and without the cache:", np.allclose(no_cache_outputs, cached_outputs))
print("K/V computations without cache:", kv_computations)
print("K/V computations with cache:   ", cache_computations)
print("Cache now holds", len(k_cache), "keys and", len(v_cache), "values")
Output4 lines
Same outputs with and without the cache: True
K/V computations without cache: 21
K/V computations with cache:    6
Cache now holds 6 keys and 6 values

Same answers, a fraction of the work. With 6 tokens the saving is 21 versus 6 key/value computations. With n tokens, the no-cache approach does about n²/2 of them and the cache does n. For a 2,000-token conversation, that's about 2 million versus 2,000. Notice too that the cached version needs no mask: the cache only ever contains past tokens, so there's nothing in the future to hide.

11.4 How big the KV cache gets#

For every token, in every layer, for every KV head, the cache stores one key vector and one value vector of head_dim numbers. In words:

KV cache size = 2 (a key and a value) × layers × KV heads × head_dim × bytes per number × tokens × concurrent sequences

Every one of those numbers is in the model's config.json. The formula assumes every layer uses full attention. Models with sliding-window layers (12.3) cache at most a window's worth of tokens in those layers, so the estimator below takes an optional count of local layers and a window size. Here it is with real configs:

python
# Values copied from each model's config.json on Hugging Face
CONFIGS = {
    "Qwen2.5-0.5B":  dict(num_hidden_layers=24, num_attention_heads=14, num_key_value_heads=2,
                          hidden_size=896,  max_position_embeddings=32768),
    "Qwen3-8B":      dict(num_hidden_layers=36, num_attention_heads=32, num_key_value_heads=8,
                          hidden_size=4096, head_dim=128, max_position_embeddings=40960),
    "Llama-3.1-8B":  dict(num_hidden_layers=32, num_attention_heads=32, num_key_value_heads=8,
                          hidden_size=4096, max_position_embeddings=131072),
    "Llama-3.1-70B": dict(num_hidden_layers=80, num_attention_heads=64, num_key_value_heads=8,
                          hidden_size=8192, max_position_embeddings=131072),
    # Gemma 3: every 6th layer is global ("sliding_window_pattern": 6), the other 29 of 34
    # layers only ever look at the last 1,024 tokens ("sliding_window": 1024)
    "Gemma-3-4B":    dict(num_hidden_layers=34, num_attention_heads=8, num_key_value_heads=4,
                          hidden_size=2560, head_dim=256, max_position_embeddings=131072,
                          local_layers=29, sliding_window=1024),
}

def kv_cache_bytes(cfg, n_tokens, batch=1, bytes_per_value=2):
    """Memory for the KV cache. bytes_per_value=2 means 16-bit (BF16/FP16) storage."""
    head_dim = cfg.get("head_dim") or cfg["hidden_size"] // cfg["num_attention_heads"]
    per_token_per_layer = (2                              # one key AND one value...
                           * cfg["num_key_value_heads"]   # ...for every KV head...
                           * head_dim                     # ...each head_dim numbers long...
                           * bytes_per_value)             # ...at this many bytes per number
    local = cfg.get("local_layers", 0)                    # sliding-window layers (if any)
    full = cfg["num_hidden_layers"] - local               # full-attention layers
    local_tokens = min(n_tokens, cfg.get("sliding_window", n_tokens))
    return per_token_per_layer * (full * n_tokens + local * local_tokens) * batch

GB = 1e9
print(f"{'model':<14} {'4K tokens':>10} {'32K tokens':>11} {'128K tokens':>12}")
for name, cfg in CONFIGS.items():
    row = []
    for n in [4_096, 32_768, 131_072]:
        fits = n <= cfg["max_position_embeddings"]
        row.append(f"{kv_cache_bytes(cfg, n) / GB:.2f} GB" if fits else "n/a")
    print(f"{name:<14} {row[0]:>10} {row[1]:>11} {row[2]:>12}")

llama = CONFIGS["Llama-3.1-8B"]
print(f"\nLlama-3.1-8B per token: {kv_cache_bytes(llama, 1) / 1e3:.0f} KB")

# What grouped-query attention saves: the same Llama 3.1 8B with one KV head per query head
no_gqa = dict(llama, num_key_value_heads=32)
print(f"Llama-3.1-8B at 128K tokens, with GQA (8 KV heads):     {kv_cache_bytes(llama, 131_072) / GB:5.1f} GB")
print(f"Llama-3.1-8B at 128K tokens, without GQA (32 KV heads): {kv_cache_bytes(no_gqa, 131_072) / GB:5.1f} GB")

# What sliding-window layers save: Gemma 3 4B if all 34 layers used full attention
gemma_all_full = dict(CONFIGS["Gemma-3-4B"], local_layers=0)
print(f"Gemma-3-4B at 128K tokens, if every layer were global:  "
      f"{kv_cache_bytes(gemma_all_full, 131_072) / GB:5.1f} GB")

print(f"Llama-3.1-8B, 32K tokens for each of 20 users at once:  "
      f"{kv_cache_bytes(llama, 32_768, batch=20) / GB:5.1f} GB")
Output12 lines
model           4K tokens  32K tokens  128K tokens
Qwen2.5-0.5B      0.05 GB     0.40 GB          n/a
Qwen3-8B          0.60 GB     4.83 GB          n/a
Llama-3.1-8B      0.54 GB     4.29 GB     17.18 GB
Llama-3.1-70B     1.34 GB    10.74 GB     42.95 GB
Gemma-3-4B        0.21 GB     0.79 GB      2.81 GB

Llama-3.1-8B per token: 131 KB
Llama-3.1-8B at 128K tokens, with GQA (8 KV heads):      17.2 GB
Llama-3.1-8B at 128K tokens, without GQA (32 KV heads):  68.7 GB
Gemma-3-4B at 128K tokens, if every layer were global:   18.3 GB
Llama-3.1-8B, 32K tokens for each of 20 users at once:   85.9 GB

("n/a" means the length is beyond the model's max_position_embeddings without extra scaling.)

What to take from this:

  • The cache grows linearly with tokens, layers and KV heads. Double any of them, double the cache.
  • At long contexts, the cache can outgrow the model. Llama 3.1 8B's weights take about 16 GB at BF16 (lesson 01, 4.4). Its KV cache at 128K tokens is 17 GB, for a single conversation.
  • It's per sequence. Twenty users with 32K-token conversations need 86 GB of cache on top of the weights. When you self-host, the KV cache, not the weights, usually decides how many users you can serve at once and how long their contexts can be.
  • Grouped-query attention is the reason these numbers are manageable. The same model with a KV head for every query head would need 68.7 GB at 128K tokens, 4× more (12.1).
  • Sliding-window layers change the picture completely. Gemma 3 4B needs 2.8 GB at 128K tokens, because only 5 of its 34 layers keep every token. The plain formula, treating all layers as global, gives 18.3 GB, 6.5× too much.

11.5 Try it: the KV cache in Hugging Face#

Transformers uses a KV cache automatically during generate(). Here we peek inside it, and time generation with the cache switched off:

python
import time
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

torch.manual_seed(0)
tok = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2")
model.eval()

prompt = tok("The history of the printing press begins", return_tensors="pt")

# 1. Look inside the cache after processing the prompt once
with torch.no_grad():
    out = model(**prompt, use_cache=True)
cache = out.past_key_values
k, v = cache.layers[0].keys, cache.layers[0].values
print("Prompt tokens:", prompt["input_ids"].shape[1])
print("Layers in the cache:", len(cache.layers))
print("Layer 0 keys shape:", tuple(k.shape), "= (batch, heads, tokens, head_dim)")

# 2. Generate 200 tokens with and without the cache (greedy, so both give the same text)
for use_cache in [True, False]:
    start = time.perf_counter()
    with torch.no_grad():
        ids = model.generate(**prompt, max_new_tokens=200, min_new_tokens=200, do_sample=False,
                             use_cache=use_cache, pad_token_id=tok.eos_token_id)
    print(f"use_cache={use_cache!s:<5}: {time.perf_counter() - start:5.2f} s")
Output · timings depend on your machine5 lines
Prompt tokens: 7
Layers in the cache: 12
Layer 0 keys shape: (1, 12, 7, 64) = (batch, heads, tokens, head_dim)
use_cache=True :  3.21 s
use_cache=False:  9.82 s
  • The cache has one entry per layer (12), and each layer's keys have exactly the shape the formula predicts: 1 sequence × 12 KV heads × 7 tokens × 64 numbers. The values have the same shape.
  • Without the cache, generating 200 tokens took about 3× longer, even for this tiny model and short text, and the gap widens as sequences get longer, because the no-cache version redoes more and more work at every step.

11.6 From KV cache to prompt caching#

The KV cache described so far lives inside one request: it's built during prefill, grows during decode, and is thrown away when the response finishes. Prompt caching (the provider feature; self-hosted engines such as vLLM call the same idea prefix caching, and Google's name is context caching) is the natural next step: keep the KV cache of a prompt's beginning after the request ends, and reuse it when a later request starts with exactly the same tokens.

This works only because of causal attention: the keys and values of a token depend on everything before it and nothing after it. So:

  • If two requests share the first 10,000 tokens (say, the same system prompt, tool definitions and document), the cached keys and values for those tokens are valid for both, and only the new part needs prefilling.
  • If anything changes early in the prompt, even one token, everything after that point has different keys and values, and the cache can't be used from there on. A timestamp at the top of your system prompt silently defeats caching.

OpenAI's prompt-caching documentation says this explicitly: its cache stores key-value (KV) tensors, not the tokens themselves, and reuse requires the whole prefix to match.

All four providers used in this path (OpenAI, Anthropic Claude, Google Gemini and OpenRouter) support prompt caching, with different defaults, minimum lengths and prices. Lesson 07, 7.3 compares them, and 7.4 shows how to design prompts that hit the cache.

What this means for you: put stable content first and changing content last (system prompt, tools and documents at the top; the user's latest message at the end), and keep that stable prefix byte-for-byte identical between requests, so cached tokens are billed at a discount and prefill faster (lesson 07, 7.4). The pricing details, cache lifetimes and how to measure hit rates belong to lesson 07, 7.3 and Module 03.


Part 12: Going deeper: modern variants and alternatives#

Deep-dive

The transformer in Parts 2 to 7 is the core design. Here are the variations you'll meet in model cards, configs and serving documentation, and why each exists. Most of them attack the costs from Parts 10 and 11.

12.1 Grouped-query and multi-query attention (GQA and MQA)#

In the original multi-head attention (MHA), every query head has its own key head and value head. But the KV cache stores keys and values, so its size is proportional to the number of KV heads. The observation behind GQA and MQA: query heads can share keys and values with surprisingly little loss in quality.

  • Multi-query attention (MQA) (Shazeer, "Fast Transformer Decoding: One Write-Head is All You Need", 2019): all query heads share a single key head and value head. The KV cache shrinks by the number of heads (32× for a 32-head model), but quality can suffer.
  • Grouped-query attention (GQA) (Ainslie et al., 2023): query heads are split into groups, and each group shares one key head and one value head. It's the middle ground, and it's what most modern open models use.
flowchart TB
    subgraph mha ["Multi-head (MHA): 8 query heads, 8 KV heads"]
        q1["Q1"] --- kv1["KV1"]
        q2["Q2"] --- kv2["KV2"]
        q3["..."] --- kv3["..."]
        q8["Q8"] --- kv8["KV8"]
    end
    subgraph gqa ["Grouped-query (GQA): 8 query heads, 2 KV heads"]
        g1["Q1"] --- gkv1["KV1"]
        g2["Q2"] --- gkv1
        g3["Q3"] --- gkv1
        g4["Q4"] --- gkv1
        g5["Q5"] --- gkv2["KV2"]
        g6["Q6"] --- gkv2
        g7["Q7"] --- gkv2
        g8["Q8"] --- gkv2
    end
    subgraph mqa ["Multi-query (MQA): 8 query heads, 1 KV head"]
        m1["Q1 ... Q8"] --- mkv["KV1"]
    end

You can read the choice straight from a config: num_key_value_heads equal to num_attention_heads means MHA (GPT-2: 12/12), 1 means MQA, and anything in between is GQA (Llama 3.1 8B: 32/8, so groups of 4; Qwen2.5-0.5B: 14/2, groups of 7). In 11.4, GQA cut Llama 3.1 8B's 128K-token cache from 68.7 GB to 17.2 GB.

Multi-head latent attention (MLA), introduced in DeepSeek-V2 (2024) and used in DeepSeek-V3, goes further: instead of caching full keys and values, it caches a small compressed vector per token per layer, from which the keys and values are rebuilt when needed. DeepSeek-V3's config shows a kv_lora_rank of 512 plus a 64-number RoPE part (qk_rope_head_dim), so each token needs 576 cached numbers per layer. Across 61 layers at 16-bit, that's about 70 KB per token, for a 671B-parameter model, less than a quarter of the roughly 328 KB per token that Llama 3.1 70B needs (2 × 80 layers × 8 KV heads × 128 numbers × 2 bytes).

12.2 FlashAttention: same maths, better memory use#

The textbook implementation of attention builds the full n × n score table, writes it to the GPU's main memory, reads it back for the softmax, writes the weights, and reads them back again for the blend. As 10.1 showed, that table is enormous, and on modern GPUs moving data in and out of main memory is often slower than the arithmetic itself.

FlashAttention (Dao et al., 2022, followed by FlashAttention-2 in 2023 and FlashAttention-3 in 2024) computes exactly the same result in small tiles that fit in the GPU's small, very fast on-chip memory, using a running-total trick to compute the softmax piece by piece. The full score table is never written to main memory.

  • It is not an approximation: the output is the same attention (up to tiny floating-point rounding differences).
  • It cuts attention's memory from quadratic to linear in sequence length, and makes it several times faster in practice.
  • The amount of arithmetic is still quadratic. FlashAttention makes long contexts practical, but not free.

In Transformers, this is the attn_implementation setting: "sdpa" uses PyTorch's built-in fused attention (which can use FlashAttention-style kernels), "flash_attention_2" requires the separate flash-attn package and a supported GPU, and "eager" is the plain version that can return attention weights (8.1). Serving engines such as vLLM use fused attention kernels by default.

12.3 Sliding-window and sparse attention#

If full attention costs n × n, one fix is to let each token attend to only some of the others.

  • Sliding-window attention (local attention): each token attends only to the previous W tokens. Cost and KV cache per layer are capped at W tokens, however long the text. Information can still travel further, by hopping through layers: after L layers, a token can be influenced by tokens up to roughly L × W back. Mistral 7B v0.1's config sets "sliding_window": 4096.
  • Interleaving local and global layers: most layers use a cheap sliding window, and every few layers one uses full ("global") attention to connect distant information directly. From their configs: Gemma 3 has 5 local layers with a 1,024-token window for every global layer ("sliding_window_pattern": 6), gpt-oss alternates 128-token sliding-window layers with full-attention layers, and ModernBERT uses a 128-token local window with a global layer every third layer.
  • Sparse attention patterns: fixed patterns combining local windows, a few global tokens and some random connections, from the Sparse Transformer (OpenAI, Child et al., 2019), Longformer (Beltagy et al., 2020) and BigBird (Zaheer et al., 2020).
  • Learned sparse attention: the model learns which earlier tokens are worth attending to. DeepSeek-V3.2-Exp (2025), for example, uses a small "indexer" to pick a limited set of earlier tokens for each query; its config sets "index_topk": 2048.

The trade-off: restricting attention saves compute and memory, but a token can no longer look directly at any position, which can hurt tasks such as quoting an exact detail from far back. Interleaving a few full-attention layers is the usual compromise.

12.4 MoE layers replacing the MLP#

Lesson 01, 4.6 introduced mixture-of-experts. Now you can see exactly where it sits: an MoE model replaces the MLP in each block (or in most blocks) with a router plus many smaller MLPs called experts. Attention, the norms and the residual stream are unchanged.

flowchart TB
    IN["Residual stream in"] --> N1["RMSNorm"] --> ATT["Attention<br/>(unchanged)"] --> A1(("+"))
    IN --> A1
    A1 --> N2["RMSNorm"]
    N2 --> R["Router: scores every expert<br/>for this token, picks the top k"]
    R --> X1["Expert 3 (an MLP)"]
    R --> X2["Expert 17 (an MLP)"]
    R --> X3["... k experts in total ..."]
    X1 --> MIX["Weighted sum of the<br/>chosen experts' outputs"]
    X2 --> MIX
    X3 --> MIX
    MIX --> A2(("+"))
    A1 --> A2
    A2 --> OUT["Residual stream out"]

The router chooses per token, per layer, so different tokens in the same prompt use different experts. In configs, look for these fields:

Field Meaning Qwen3-30B-A3B gpt-oss-20b DeepSeek-V3
num_experts / num_local_experts / n_routed_experts Experts per MoE layer 128 32 256 (+ 1 shared expert, n_shared_experts)
num_experts_per_tok Routed experts active for each token 8 4 8 (plus the shared expert, which every token uses)
moe_intermediate_size (or intermediate_size in gpt-oss) MLP width of each expert 768 2,880 2,048

The "A3B" in Qwen3-30B-A3B means about 3 billion active parameters per token out of about 30 billion total. As lesson 01 explained, compute per token follows the active parameters, while memory follows the total. The KV cache is unaffected by MoE, since attention doesn't change.

12.5 Beyond attention: state-space models and hybrids#

Because attention's cost grows with context, researchers keep looking for alternatives that process sequences with a fixed-size state, like an RNN, but can still be trained in parallel.

  • State-space models (SSMs), most famously Mamba (Gu and Dao, 2023) and Mamba-2 (2024), process tokens with a learned, input-dependent recurrence. Generation needs only a fixed-size state per layer (Mamba-2.8B's config shows "state_size": 16), so memory doesn't grow with context, and cost per token stays constant. The trade-off: a fixed-size state is a compressed summary, so pure SSMs tend to be weaker than attention at exactly recalling a specific detail from far back, such as copying a phone number from page 3.
  • Linear attention variants (such as Gated DeltaNet) reformulate attention so it can also run with a fixed-size state.
  • Hybrids combine both: mostly cheap SSM or linear-attention layers, with a few full-attention layers for precise recall. Published examples include AI21's Jamba (2024), IBM's Granite 4.0 "H" models (the config of granite-4.0-h-small lists 40 layers, of which 36 are Mamba layers and 4 are attention), and Qwen3-Next ("full_attention_interval": 4, so one full-attention layer for every three linear-attention layers).

As of October 2026, attention-based transformers remain the dominant architecture for frontier LLMs, but hybrids are a growing family, particularly for long contexts and efficient serving. For you as an application engineer, the architecture mostly shows up as behaviour you can measure (speed, memory, long-context accuracy), so evaluate on your own tasks (Module 10A).

12.6 Other details you'll see in configs#

Config field or term What it means
attention_bias: false, mlp_bias: false No bias terms in those layers. Most modern LLMs drop biases (lesson 01, 2.2); they add little and complicate training at scale
q_norm, k_norm weights (QK-norm) Queries and keys are normalized before the dot product, to keep attention scores in a stable range. Qwen3's checkpoints include q_norm and k_norm weights in every attention layer
query_pre_attn_scalar Gemma's custom scaling of scores instead of √head_dim (2.5)
pre_feedforward_layernorm, post_feedforward_layernorm weights (sandwich norm) Gemma 2 and 3 normalize both the input and the output of each sublayer, a variation on the pre-norm design of 6.4
attn_logit_softcapping, final_logit_softcapping Gemma 2 squashes attention scores (cap 50) and final logits (cap 30) smoothly into a fixed range, for training stability
sinks weights in each attention layer gpt-oss's learned attention sink per head (8.1)
partial_rotary_factor RoPE applied to only part of each head (5.4)
layer_types Which kind of attention (or Mamba) each layer uses, in hybrid and interleaved models
sliding_window Window size for local attention layers (12.3); some configs include it with use_sliding_window: false, meaning it's switched off
rope_scaling Context-extension settings (5.6)
torch_dtype / dtype The precision the weights are stored in, usually bfloat16 (lesson 01, 4.4)

12.7 Beyond next-token prediction: diffusion and parallel-decoding LMs#

Every generative model in this lesson works autoregressively: one token at a time, each conditioned on all the tokens before it (the causal mask of Part 3). A small but growing family of models drops that constraint. Diffusion language models (dLLMs) — also called masked-diffusion or parallel-decoding models — start from a sequence in which every output position is hidden (masked or replaced by noise) and then refine the whole sequence over a handful of denoising steps, predicting many tokens at once and revising earlier guesses as the context firms up. Think "editor revising a full draft" rather than "typewriter".

The idea borrows from image generation. Discrete diffusion for text builds on the D3PM framework (Austin et al., 2021); SEDD (Lou et al., 2023) showed a score-entropy objective could train discrete diffusions competitive with GPT-2-scale autoregressive models; masked diffusion (Sahoo et al., 2024) and then LLaDA (Nie et al., 2025, arXiv:2502.09992) brought it to LLM scale — an 8B model trained from scratch that the authors report as comparable to similar-size autoregressive baselines (a NeurIPS 2025 oral). Block-diffusion hybrids (Arriola et al., 2025, arXiv:2503.09573) interpolate between the paradigms: autoregressive across blocks of tokens, diffusion within each block.

You can already meet these models in the wild — treat availability as of November 2026 and check each provider's current pages:

  • Open weights: LLaDA (8B base and instruct) and Google's DiffusionGemma (released in June 2026; the model card on Google's own Hugging Face page, google/diffusiongemma-26B-A4B-it, lists the licence as Apache 2.0, while some redistributed quantised variants carry the Gemma terms instead, so check the card of the exact variant you download): a 26B-total / ~4B-active MoE built on Gemma 4 that denoises ~256-token "canvases" in parallel, with bidirectional attention inside each canvas, claimed on its model card at over 1,100 tokens per second per user at low batch size (H100, FP8) and small enough to run quantized on a consumer GPU.
  • Hosted APIs: Inception Labs' Mercury family (vendor-claimed 1,000+ tokens/second) and Google DeepMind's Gemini Diffusion (experimental research preview announced May 2025).

The engineering trade-offs are real but different from Parts 10 and 11:

  • Speed: parallel refinement means far more tokens per second and quicker long outputs — the vendor numbers above are best-case claims; benchmark on your own prompts and hardware.
  • Revision-friendly: because tokens inside a canvas attend to each other in both directions, the model can fix earlier draft tokens — useful for editing, infilling and structured layouts.
  • Quality: as of November 2026, reasoning, math and code still generally trail frontier autoregressive models, though the gap is closing (DiffusionGemma's model card lists a configurable thinking mode). Evaluate on your own tasks (Module 10A) before believing either marketing page.
  • Different controls: the knobs are denoising steps and canvas or block size rather than per-token temperature and top-p, and support for structured output, tool calling and streaming varies by provider. Most provider APIs remain autoregressive, so for now this is mainly a "know it exists" topic rather than a daily driver.

Common misconceptions#

Misconception Reality
"Attention means the model focuses on the important words, like a human does." Attention is a learned weighted average. A high weight means information can flow from that token, not that the model "considered it important" in a human sense. Many heads park their attention on the first token simply because they have nothing to do (8.1).
"Attention maps explain why the model gave its answer." They're a clue, not an explanation. Values, MLPs, residual mixing and dozens of layers all contribute (8.2).
"Each word has one fixed vector inside the model." Only at the input. From the first attention layer onwards, every token's vector is contextual: "bank" in "river bank" and in "bank loan" become different vectors.
"The transformer reads text from left to right like an RNN." During prefill, all prompt tokens are processed in parallel. The causal mask only restricts what each token can see, not the order of computation. Generation is sequential, one new token at a time.
"Most of a model's parameters are in attention." The MLPs hold the largest share: 64–80% in the modern models counted in 7.6. Small models with big vocabularies are the exception (GPT-2 small: 45% MLP, 32% embeddings, 8.3). Attention's cost is mainly compute and memory that grow with sequence length.
"A bigger context window is free to use." Attention compute grows roughly quadratically with length, and the KV cache grows linearly with it, per user. Long prompts cost more, run slower and are often used less reliably (Part 10, lesson 07).
"max_position_embeddings is the model's context window." Often, but not always. Some models need rope_scaling enabled to reach their advertised context, and some handle less than the field suggests. Check the model card (5.6).
"The KV cache makes the model remember previous conversations." The KV cache lasts for one request. Provider prompt caching reuses an identical prefix for a few minutes to hours (5 minutes to 24 hours depending on provider and setting; see lesson 07, 7.3), as a speed and cost optimization. Neither one is memory: the application still re-sends the conversation (lesson 01, 7.2).
"FlashAttention is an approximation that trades quality for speed." It computes exactly the same attention, just with smarter memory access (12.2). Sliding-window and sparse attention, by contrast, do change what the model can see.
"Transformers are only for text." The same blocks process image patches, audio frames and mixtures of them (9.7).
"BERT-style models are obsolete." Encoders remain the standard for embeddings, classification and reranking, where they're cheaper and faster than LLMs (9.2).
"Every LLM generates one token at a time." Most do (autoregressive), but diffusion language models refine a whole block of tokens in parallel over a few denoising steps, which is why they can be far faster (12.7).

Key takeaways#

  • A token's input embedding is context-free. Attention mixes in information from other tokens to make every vector contextual.
  • Each token produces a query (what I'm looking for), a key (what I offer) and a value (what I pass on). Attention scores queries against keys with dot products, scales by √d so softmax stays soft, turns the scores into weights with softmax, and blends the values. Q, K and V come from learned projection matrices.
  • Causal masking stops each token from seeing later tokens. It lets training predict every position in parallel, and it means earlier tokens' keys and values never change, which is the basis of the KV cache and prompt caching.
  • Multi-head attention runs many small attention heads in parallel, each projecting every token into its own small query/key/value space and learning its own pattern (previous-token, syntactic, coreference, induction heads...). Individual heads are often noisy and redundant.
  • Attention is order-blind, so position must be added: sinusoidal, learned absolute (a hard length limit) or RoPE (rotating queries and keys so scores depend on relative distance), used by most modern LLMs. Context extension rescales RoPE (rope_scaling, YaRN).
  • A transformer block = attention (communication between tokens) + MLP (computation within each token), each wrapped in a residual connection with pre-norm (usually RMSNorm). An LLM stacks num_hidden_layers of them.
  • The decoder-only forward pass: tokens → embeddings → N blocks → final norm → LM head → logits → softmax → next token. Every number in it is in config.json, and you can compute the exact parameter count from the config. MLPs hold most of the parameters.
  • Encoder-only models (BERT) are for embeddings, classification and reranking; decoder-only models are every chat LLM; encoder-decoder models (T5, Whisper) suit translation and speech recognition.
  • Attention compute grows roughly quadratically with sequence length. Prefill is compute-bound (time to first token), and decode is memory-bandwidth-bound (tokens per second).
  • The KV cache stores every token's keys and values in every layer, so generation never recomputes the past. For full-attention layers its size is 2 × layers × KV heads × head_dim × bytes × tokens, per sequence (sliding-window layers cap at their window), and at long contexts it can exceed the model's weights.
  • GQA/MQA/MLA shrink the KV cache, FlashAttention makes exact attention memory-efficient, sliding-window/sparse attention limits what each token sees, MoE replaces the MLP, and SSM hybrids replace most attention layers with fixed-size-state layers.
  • Autoregressive, one-token-at-a-time generation is the dominant paradigm but not the only one: diffusion / parallel-decoding LMs refine a whole block of tokens bidirectionally over a few denoising steps, trading some quality and ecosystem maturity for much higher decode speed (12.7).

Terms introduced in this lesson#

Term One-line definition
Transformer The neural network architecture behind modern LLMs, built from stacked attention + MLP blocks
Attention / self-attention A mechanism where each token takes a weighted blend of information from other tokens in the same sequence
Contextual embedding A token's vector after it has been updated with information from surrounding tokens
Query, key, value (Q, K, V) Three vectors each token produces: what it looks for, what it offers, and what it passes on
Attention score / attention weight The query–key dot product for a pair of tokens; the softmax of a row of scores
Scaled dot-product attention Attention computed as softmax of query–key dot products divided by √d, used to blend values
Projection matrices (W_Q, W_K, W_V, W_O) Learned weights that produce queries, keys, values, and map the attention output back
Cross-attention Attention where queries come from one sequence and keys/values from another
Causal mask Blocks each token from attending to later tokens
Autoregressive / causal model A model that generates one token at a time, each depending only on earlier tokens
Padding mask / attention mask Marks filler tokens so the model ignores them
Attention head / multi-head attention One independent attention computation; several run side by side and are combined
head_dim The vector size each attention head works with (hidden_size / number of heads, unless set explicitly)
Induction head An attention head that continues a pattern seen earlier in the context
In-context learning A model with frozen weights performing a new task from examples placed in the prompt, with no weight update
Attention sink A position (usually the first token) where heads park attention when they have nothing to do
Positional encoding Information about token order added to the model
Sinusoidal / learned absolute positions Fixed wave-based or trained per-position vectors added to embeddings
RoPE (rotary position embedding) Rotating queries and keys by position so scores depend on relative distance
rope_theta / rope_scaling RoPE's base rotation speed; settings for extending context beyond the training length
Context extension (position interpolation, YaRN) Techniques that rescale positions so a model handles longer contexts than it was pretrained on
Transformer block / layer Attention + MLP, each with a residual connection and normalization
Feed-forward network (FFN) / MLP block The per-token two- or three-matrix network inside each block
SwiGLU A gated MLP design with gate, up and down projections, used by most modern LLMs
Residual connection / residual stream Adding each sublayer's output to its input; the running vector those additions build
LayerNorm / RMSNorm Rescaling each token's vector to a standard size (RMSNorm skips centring)
Pre-norm / post-norm Normalizing the input of each sublayer vs normalizing after the residual addition
LM head / unembedding The final layer mapping each vector to a score for every vocabulary token
Weight tying (preview; defined in lesson 03) Reusing the embedding matrix as the LM head
config.json fields hidden_size, num_hidden_layers, num_attention_heads, num_key_value_heads, intermediate_size, vocab_size, max_position_embeddings
Prefill / decode (preview; defined in lesson 05) Processing the prompt in parallel / generating tokens one at a time
Time to first token (TTFT) (preview; defined in lesson 05) How long before the first output token appears, driven mainly by prefill
Encoder-only / decoder-only / encoder-decoder The three transformer variants (BERT / GPT / T5-style)
Masked language modelling Pretraining by hiding tokens and predicting them from both sides (BERT)
Quadratic attention cost Attention compute growing with the square of sequence length
KV cache Stored keys and values of past tokens, reused at every generation step
Prompt caching / prefix caching Reusing the KV cache of an identical prompt prefix across requests
PagedAttention vLLM's technique of storing the KV cache in fixed-size blocks
MQA / GQA / MLA Attention variants that share or compress keys and values to shrink the KV cache
FlashAttention An exact attention algorithm that avoids materializing the full score matrix
Sliding-window / local attention Each token attends only to a fixed number of recent tokens
Sparse attention Each token attends to a selected subset of positions
Router / expert (MoE) In an MoE block, the network that picks experts per token, and the MLPs it picks from
State-space model (SSM) / Mamba Sequence layers with a fixed-size recurrent state, trainable in parallel
Hybrid model A model mixing attention layers with SSM or linear-attention layers
Diffusion language model (dLLM) / masked diffusion A language model that generates by iteratively unmasking and refining many tokens in parallel instead of one token at a time
QK-norm Normalizing queries and keys before the attention dot product
Sandwich norm Normalizing both the input and the output of each sublayer (Gemma 2 and 3)
Logit soft-capping Smoothly squashing attention scores or final logits into a fixed range (Gemma 2)
Vision Transformer (ViT) A transformer that treats image patches as tokens

All terms are also collected in the glossary.


Exercises#

Run the code from this lesson and experiment:

  1. Attention (2.4): change the sentence to "I paid my salary into the bank": add tokens for "paid" and "salary", give "salary" a key that advertises money (add a fifth "is-money" feature to every key and query), and change "bank"'s query to look for money. Does the new vector for "bank" move towards the "money" meaning?
  2. Scaling (2.5): add d = 4096 to the loop. Predict the unscaled top weight before running it. Then replace np.sqrt(d) with d (dividing by d instead of its square root). What happens to the scaled top weight as d grows, and why is that also bad?
  3. Causal mask (3.2): change k=1 to k=0 in np.triu. What goes wrong in the first row, and why? (Hint: what is softmax of a row of only −∞?)
  4. Order blindness (5.1): add sinusoidal position vectors from 5.2 to the word vectors before attention. Do "dog bites man" and "man bites dog" now give different outputs for "dog"?
  5. RoPE (5.4): change base from 10,000 to 1,000,000. How does the score change between 0, 1, 5 and 50 positions apart? Relate it to rope_theta in long-context models.
  6. Block (6.6): remove the residual connections (x = attention(...) instead of x = x + attention(...)), stack 50 blocks, and print the size (np.linalg.norm) of the vectors after each block. Compare with the residual version. What does this suggest about why residuals matter?
  7. Config reading (7.5): load the configs of Qwen/Qwen3-8B, google-bert/bert-base-uncased and openai-community/gpt2 with AutoConfig. For each one, identify the number of layers, the hidden size, the number of query and KV heads, and whether it uses GQA. Which field names differ?
  8. Parameter count (7.6): extend count_params with Qwen2.5-7B's config (hidden_size=3584, num_hidden_layers=28, num_attention_heads=28, num_key_value_heads=4, intermediate_size=18944, vocab_size=152064, tie_word_embeddings=False, qkv_bias=True). Does the total match the "7B" name? What share is the vocabulary?
  9. Attention inspection (8.1): write five new pronoun sentences of your own and run the chosen head on them. How often does it pick the right noun? Then pick the best head on your sentences instead. Is it the same head?
  10. KV cache (11.4): your team wants to self-host Llama 3.1 8B at BF16 on one 80 GB GPU, with 32K-token contexts. After the weights (about 16 GB), how many full-length conversations fit in the remaining memory? How does the answer change with an FP8 KV cache (bytes_per_value=1)?
Hints and what you should see
  1. It should: with a "money" feature in the keys and queries, "salary" advertises money, "bank"'s query asks for it, and most of "bank"'s weight moves to "salary", so the new vector leans towards the money value. If it doesn't, check that every key and query has the new fifth number and that the value vectors still carry a money component.
  2. Unscaled, the top weight at d = 4096 should be about 0.97 or higher, continuing the 0.49, 0.86, 0.95 trend. Dividing by d instead of sqrt(d) shrinks the scores so far that they become almost equal: the top weight falls towards 1/10 (there are ten keys), and attention turns into a uniform average that cannot focus on anything. Too little scaling saturates softmax; too much flattens it.
  3. With k=0 the diagonal is masked too, so the first token has no visible position and its whole row is -inf. Subtracting the row maximum gives -inf - (-inf), which is nan, so the whole row (and anything computed from it) becomes nan. A token must always be allowed to see itself.
  4. Yes. Once the position vectors are added, the "dog" input vector differs between the two sentences and so do the other tokens' vectors, so the outputs are no longer identical (np.allclose returns False).
  5. A larger base makes the slowest pairs rotate even more slowly, so the score changes less between nearby positions and the angle between far-apart tokens stays distinguishable over longer distances. That is why long-context models raise rope_theta (Llama 3.1 uses 500,000).
  6. Print the norms for both versions and look at how they evolve, rather than assuming. In the residual version each block only adds an edit to the stream, so the norm changes gradually; without the residual, each block replaces the stream, and the size is multiplied by whatever that block does, so it can drift towards zero or grow very large over 50 blocks depending on the weight scale. Residuals also give gradients a direct path during training (6.3), which this forward-only demo cannot show.
  7. Qwen/Qwen3-8B: 36 layers, hidden size 4,096, 32 query heads and 8 KV heads, so GQA (and an explicit head_dim of 128). google-bert/bert-base-uncased: 12 layers, hidden size 768, 12 heads, and no num_key_value_heads field because it uses full multi-head attention. openai-community/gpt2: 12 layers, 768, 12 heads, full multi-head attention, with n_layer, n_embd and n_head instead of the usual names, as the warning in 7.5 says.
  8. The total is 7,615,616,512, about 7.6 billion, which Qwen names "7B". The two vocabulary matrices (152,064 × 3,584 each, untied) are about 14% of the total, the MLPs about 75% and attention about 11%.
  9. Count hits and misses honestly. Expect the original head to be right more often than not on short sentences with a clear gender or number cue, and to fail when the first token is the right answer (the sink) or when no cue exists. Choosing the best head on your own five sentences will probably pick a different head, which shows how fragile a head chosen on a handful of examples is.
  10. Per conversation at 32K tokens, the cache is about 4.29 GB (see the table in 11.4), so (80 - 16) / 4.29 gives about 14 conversations in the best case, and fewer in practice because activations and the serving engine's own overhead also need memory. With an FP8 KV cache (bytes_per_value=1) each conversation needs about 2.15 GB, so about 29 fit, roughly double.

Check yourself#

  1. Why does a token need attention at all, if it already has an embedding?
  2. In your own words, what are a query, a key and a value? Why are keys and values kept separate?
  3. What does softmax do in attention, and why can an attention weight never be exactly 0 without a mask?
  4. Why are attention scores divided by √d?
  5. What does the causal mask do, and give two reasons a decoder needs it.
  6. A 32-head attention layer has hidden_size 4,096. What is head_dim? Does multi-head attention have more parameters than single-head attention of the same hidden_size?
  7. Why can't plain attention tell "dog bites man" from "man bites dog"?
  8. What property makes RoPE attractive, and why does a RoPE model still have a practical context limit?
  9. What are the two sublayers of a transformer block, and what job does each do?
  10. What does a residual connection do, and why do deep transformers need it?
  11. What's the difference between pre-norm and post-norm, and which do modern LLMs use?
  12. A config says num_attention_heads: 64, num_key_value_heads: 8. What attention variant is this, and what does it save?
  13. Which part of a transformer holds most of its parameters?
  14. Which architecture variant would you use for (a) semantic search embeddings, (b) a chat assistant, (c) speech-to-text?
  15. Prompt length goes from 10K to 40K tokens. Roughly how does attention's compute change? And the KV cache size?
  16. Why can a provider reuse a cached prompt prefix, but not a cached "middle" of a prompt whose beginning changed?
  17. What is in-context learning, and why doesn't it count as the model "learning" in the weight-update sense?
  18. How does a masked-diffusion LLM generate text differently from an autoregressive one, and what are the main trade-offs an engineer should weigh before adopting one?

Further resources#


← 02.3 — Embeddings | Module 02 overview | 02.5 — Generation and Sampling →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close