Mikhail Mikhasenko · Lecture 4A
A classifier learns : which label for this input?
A generative model learns the distribution of the data itself, , and can sample new examples from it.
With a condition, it samples :
Language models are generative models of text.

“A painted picture of a crocodile in the house drinking tea and waiting for a turtle to visit”
Split text into tokens . By the chain rule of probability,
So one task is enough: given the text so far, give a probability for every possible next token.
Generate by sampling a token, appending it, and repeating.
GPT-2 (124 M parameters, 2019):
| text so far | next token |
|---|---|
| The American flag is red, white, and | blue 0.93 |
| When Mary and John went to the store, John gave a drink to | Mary 0.68 |
| The capital of France is | the 0.08, now 0.05, … Paris 0.03 |
Llama 3.2 (1.2 B, 2024) gives Paris 0.39.
| Unit | Vocabulary | Length of a text | Problem |
|---|---|---|---|
| characters | ~100 (bytes: 256) | long: one step per letter | the model must learn spelling before meaning |
| words | millions | short | new words, typos, names and other languages are unknown |
| subword tokens | 50 k – 200 k | ~4 characters per token in English | a compromise, learned from data |
Frequent words become single tokens (·the, ·electron); rare words are split into pieces (·Bo ch um).
GPT-2: 256 bytes + 50 000 merges + 1 end-of-text token = 50 257.
Split new text into bytes, then apply the learned merges in the order they were learned.
Starting from bytes, nothing is ever “unknown”: any text, any language, any emoji can be encoded.
The tokenizer is trained once, before the network, and is not changed by gradient descent.
| text | GPT-2 tokens |
|---|---|
strawberry |
st raw berry |
·Bochum |
·Bo ch um |
·Energieerhaltungssatz |
9 pieces |
·12345678 |
·123 45 678 |
·SolidGoldMagikarp |
1 token |
The model never sees letters: counting the r’s in strawberry is hard.
Each token id selects one row of the embedding matrix :
A one-hot vector times a matrix: a lookup table, trained by backpropagation like any other weight.
GPT-2: , , so has 38.6 M of the 124 M parameters.
Training moves tokens that are used in similar contexts to similar vectors:
Monday: Tuesday, Thursday, Wednesday, Fridayelectron: electrons, photon, neutronking − man + woman ≈ queenParis − France + Germany ≈ BerlinThe same idea as AlexNet’s fc7 embedding in Lecture 3B.
Attention (next slides) compares tokens by content only. Shuffle the input and each token gets the same result: “dog bites man” = “man bites dog”.
So add information about the position to each token vector:
| model | position encoding |
|---|---|
| Transformer (2017) | fixed: |
| GPT-2 (2019) | learned per position, up to 1024 |
| Llama, most since 2023 | RoPE (rotary), below |
RoPE. Attention compares a query and a key (next slides) by the dot product . Instead of adding , rotate each coordinate pair by the angle :
with , and the same for . Rotations keep lengths, so the score changes only through the angle : it depends on the distance between the two tokens.
The meaning of a token depends on other tokens, sometimes far away:
Each position must collect information from the relevant other positions, whose number and location change from text to text.
A dense layer has one fixed weight per input position: it cannot route information by content.
Recurrent networks (before 2017) passed a single state vector along the text: slow, one step at a time, and forgetful over long distances.
Attention: every token asks a question, every token offers an answer, and the weights are computed from the data.
From each token vector compute three vectors with learned matrices:
Similarity is the dot product , the same similarity score as a CNN kernel on an image patch.
The output for token is a weighted average of values:
Weights , : a softmax over all tokens.
GPT-2: , per head.
Dividing by : for random vectors , and large scores would saturate the softmax.
One attention pattern can express one kind of relation. So run heads in parallel, each with its own of size :
Heads specialize: previous word, subject of the verb, matching bracket, earlier copy of the current word…
| GPT-2 small | GPT-3 | DeepSeek-R1 | |
|---|---|---|---|
| layers | 12 | 96 | 61 |
| heads per layer | 12 | 96 | 128 |
| width | 768 | 12 288 | 7 168 |
| attention patterns | 144 | 9 216 | 7 808 |
Parameters per attention layer: (plus biases).

All 144 attention patterns of GPT-2 for “The American flag is red, white, and” (rows: layers 0–11, columns: heads 0–11).
Some roles are known:
Most heads have no simple description.
A two-head circuit:
Pattern: … A B … A → predict B.
Random words shown twice: GPT-2’s loss falls from 11.8 to 0.73 nats per token.
Attention: tokens exchange information.
MLP: each token processed on its own, with GELU. Two thirds of the block’s weights; much of the model’s factual knowledge seems to live here.
LayerNorm (LN): rescale each token vector to mean 0 and spread 1 before it enters attention or the MLP (next slide).
Residual connections: each block adds to , as in ResNet (Lecture 3B):
GPT-2 small stacks 12 blocks, GPT-3 96.
Take one token vector , . Compute its mean and spread over the features:
Standardize, then scale and shift each feature :
Why? Every block adds to the residual stream, so its scale grows. GPT-2, last token of “The American flag is red, white, and”:
| entering | largest | ||
|---|---|---|---|
| block 1 | 0.00 | 0.17 | 1.2 |
| block 2 | 0.01 | 1.96 | 26 |
| block 7 | −0.02 | 2.73 | 30 |
| block 12 | 0.16 | 7.59 | 98 |
After LN: , at every depth. Attention and the MLP always see inputs of the same size; the stream itself keeps growing.
GPT-2 has 25 LayerNorms (2 per block + 1 before the unembedding): parameters.
Each block adds a little to a running vector per token: the residual stream.
Logit lens: read the stream out early with the final unembedding.
After “negative”, GPT-2’s guess moves from pressure to impact, value, spin and finally charge (0.47) in the last layer.
The 2017 Transformer translated: an encoder read the German sentence, a decoder wrote the English one and looked at the encoder through cross-attention. GPT kept only the decoder, and one objective, next-token prediction, turned out to cover almost every task.
The causal mask lets one forward pass train all predictions at once: no labels needed, the text is its own target.
| training text | |
|---|---|
| GPT-2 (2019) | ~40 GB of web text, ~10 B tokens |
| GPT-3 (2020) | ~300 B tokens |
| Llama 3 (2024) | ~15 T tokens |
Unembedding: logits , then
GPT-2, “The capital of France is …”
T = 0: the capital of the French Republic, and the capital of the French Republic is the capital of the French Republic…
T = 0.7: still the biggest producer of oil and gas. (Reuters)…
T = 1.5: Barville ,“A vice801 noted.”Mr Wallace wanted ahead standpoint…
| GPT-2 small | parameters |
|---|---|
| token embedding 50 257 × 768 | 38.6 M |
| position embedding 1024 × 768 | 0.8 M |
| attention, 12 × ( + biases) | 28.3 M |
| MLP, 12 × ( + biases) | 56.7 M |
| layer norms | 0.04 M |
| total | 124.4 M |
Per block: . For a deep model
GPT-3: , reported 175 B.
Generating one token costs about floating-point operations: 250 M for GPT-2, 350 G for GPT-3.
The full attention pattern has entries: a 100 000-token context compares every pair of words of a book. When generating, earlier keys and values do not change, so they are cached. The cache, not the weights, often limits how many users and how long a context a server can handle; DeepSeek’s multi-head latent attention compresses it 57-fold.
GPT2_under_the_hood.py:
From the Lecture_4A folder:
CPU only; the first start downloads GPT-2 (~550 MB). The tiny GPT (0.8 M parameters) trains in about a minute.
Anything that can be cut into tokens:
Shared embedding spaces connect them: CLIP maps images and captions to the same vectors.
2017 Transformer: attention is all you need
2018 GPT, BERT
2019 GPT-2: 1.5 B parameters
2020 GPT-3: 175 B; scaling laws; ViT
2022 ChatGPT
2024–25 reasoning models, open weights (Llama, DeepSeek-R1)
Trained on one task, next-token prediction, with the cross-entropy, backpropagation and Adam of the previous lectures.
Lecture 4B: from a text predictor to a chat assistant and an agent: context windows, latency, “thinking”, tools and harnesses.
Thank you for the attention