What this is
What happens between your prompt and the reply?
When you send a prompt to an AI language model, your words become numbers, the numbers pass through a stack of layers, and the reply is written one token at a time. A token is a word or a piece of one. For each new token, the language model scores every token it knows, draws one, adds it to the text and goes round again.
Why it matters: You need this picture the day you set a temperature you can't explain, read a bill that prices input and output tokens differently, or get an answer that stops mid-sentence. Each of those comes from one step of the trip.
At a glance
Key takeaways
- A language model reads your prompt as tokens, turns each token into a vector, and passes the vectors through a stack of transformer blocks.
- Only the last token's vector chooses the next token. It scores every token in the vocabulary, and temperature divides those scores before softmax: low is predictable, high is varied.
- The reply is written one token per trip round the loop. Without a KV cache, every trip re-reads the whole text so far.
- Training is the same forward pass plus a loss: how surprised the model was by each real next token.
How it works, from scratch
Follow one prompt, "Reset your password", through a small language model whose weights are still random. It has learned nothing, so what it writes is gibberish, but it takes the same steps as a trained model, with the same shapes. This is the whole trip:
Figure 1 · Diagram
flowchart LR A[Prompt text] --> B[Tokenizer<br/>text to IDs] B --> C[Embedding lookup<br/>IDs to vectors] C --> D[Add position info] D --> E[Transformer blocks<br/>repeated N times] E --> F[Output layer<br/>score per vocab token] F --> G[Softmax + sampling] G --> H[Next token] H -->|append and repeat| E
Chapter 1
Text to ids: the coat check
A coat check takes your coat and hands you a numbered ticket. A tokenizer does the same to text: it cuts the prompt into pieces called tokens and hands back one number for each, its token id. From then on the model only ever handles the tickets.
The toy tokenizer here has a kit of 400 pieces, and it turns "Reset your
password" into 5 tickets: Re set y our password →
[346, 377, 309, 328, 291]. It learned its kit from text, so a word it saw
often gets a ticket of its own: "password", with the space in front of it, is
one piece. Words it saw less often are split, and "Reset" and "your" take two
tickets each.
Figure 2 · Diagram
flowchart LR T["'Reset your password'"] --> TK["tokenizer<br/>(learned kit of 400 pieces)"] TK --> I["[346, 377, 309, 328, 291]"]
Prompt length, price and context limits are all counted in these tickets, not in words. How a tokenizer learns its kit is the subject of the tokenization lesson (Tokenization).
In code: tok.encode(prompt) makes the tickets; build_pipeline trains the toy tokenizer and builds an untrained primer.ml.transformer.TinyGPT sized to its vocabulary. View source
Chapter 2
Ids to vectors: a lookup, not a computation
A ticket number such as 291 is only a label: token 291 is not more of anything than token 290. So each id fetches a row of numbers, a vector, from the token embedding table. Here the table has 400 rows of 32 numbers, and the 5 ids fetch a 5 × 32 grid.
That grid says what each token is but not where it sits. A second table, the position table, has a row for each seat in the prompt, and row i of it (i = 0 to 4) is added to row i of the grid.
Figure 3 · Diagram
flowchart LR
I["ids (5)"] --> E["token table<br/>400 × 32"]
E --> X["5 × 32: what each token is"]
P["positions 0..4"] --> PT["position table<br/>64 × 32"]
PT --> Y["5 × 32: where each token is"]
X --> ADD(("+"))
Y --> ADD
ADD --> OUT["5 × 32 input to the blocks"]
primer.ml.embeddings).For the token in seat i:
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| a token's position in the prompt, from 0 | 4 (the last token) | |
| the token id at position | = 291 | |
| the token embedding table | 400 × 32 | |
| row of that table | row 291: 32 numbers | |
| row of the position table | row 4: 32 numbers | |
| what the first block receives for position | 32 numbers |
In words: "each token's input vector is its token's row plus its position's row."
With the numbers: , one 32-number list plus another. In miniature, with 3-number rows instead of 32: = (0.2, −0.1, 0.5) and = (0.1, 0.3, −0.2) give = (0.3, 0.2, 0.3).
In Python
# row 291 of the token table (3 numbers, not 32)
E_291 = [0.2, -0.1, 0.5]
# row 4 of the position table
P_4 = [0.1, 0.3, -0.2]
# E_(t_i) + P_i, number by number
x_4 = [round(e + p, 2) for e, p in zip(E_291, P_4)]
x_4 # → [0.3, 0.2, 0.3]
New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.
In code: trace does both lookups and the add (model.wte[ids] + model.wpe[:len(ids)]), keeping every stage's result. View source
This is the only point where the tokens themselves enter the model. Every step after it works on these vectors.
Chapter 3
The transformer blocks: rounds of meeting and desk work
So far each row knows only its own token and its seat. In the transformer blocks the rows learn from each other. Each block works like a meeting followed by desk work. In the meeting, called attention, each token takes in the tokens before it and adds what it hears to its own row. At the desk, the feed-forward layer works on each row alone. The toy model has 2 blocks; large models stack dozens.
The grid leaves each block with the same shape, 5 × 32, and new contents. By the end, the last row, " password", also carries something of "Re", "set", " y" and "our", and that row will choose the next token.
Figure 4 · Diagram
flowchart LR X["5 × 32"] --> B1["block 1<br/>meeting + desk work"] --> B2["block 2"] --> LN["final norm"] --> H["5 × 32<br/>context-aware vectors"]
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| the 5 × 32 input grid from section 2 | ||
| the -th transformer block | = 2 | |
| "and so on, for every block in between" | ||
| the final layer norm | ||
| the context-aware vectors | 5 × 32 |
In words: "run the input through every block in turn, then normalize."
With the numbers: here N = 2, so h = LN(Block₂(Block₁(x))). In miniature, with one 3-number vector and two stand-in blocks that each add an edit: x = (1, 2, 3), Block₁ adds (0, 1, 0) and Block₂ adds (0, 0, 2), giving (1, 3, 5). The final norm subtracts the mean (3) and divides by the spread (1.63), so h = (−1.22, 0, 1.22).
In Python
import statistics
x = [1.0, 2.0, 3.0]
# a stand-in edit
def block_1(v): return [v_i + d for v_i, d in zip(v, [0, 1, 0])]
def block_2(v): return [v_i + d for v_i, d in zip(v, [0, 0, 2])]
def LN(v):
mu, sigma = statistics.fmean(v), statistics.pstdev(v)
# centre, then rescale
return [round((v_i - mu) / sigma, 2) for v_i in v]
h = x
# Block_1 first, then Block_2 ... up to Block_N
for block in [block_1, block_2]:
h = block(h)
h # → [1.0, 3.0, 5.0]
LN(h) # → [-1.22, 0.0, 1.22]
The transformer lesson (The transformer) opens a block up.
Chapter 4
Scores, softmax and temperature
Only the last row has taken in the whole prompt, so only it chooses the next token. It is compared with every row of the token table, which gives a score for each of the 400 tokens. Softmax turns the scores into probabilities that add up to 1, and one token is drawn at random in proportion to them. First, every score is divided by the temperature. Below 1 the gaps between scores widen and the top token wins more often; above 1 they narrow; at 0 the model always takes the top token (greedy decoding). For three candidates scored 2.0, 1.0 and 0.5:
| temperature | p(A) | p(B) | p(C) |
|---|---|---|---|
| 0 (greedy) | 1.000 | 0.000 | 0.000 |
| 0.5 | 0.844 | 0.114 | 0.042 |
| 1 | 0.629 | 0.231 | 0.140 |
| 2 | 0.481 | 0.292 | 0.227 |
Figure 5 · Diagram
flowchart LR H["last row of h<br/>32 numbers"] --> S["× token tableᵀ<br/>400 scores"] S --> T["÷ temperature"] T --> SM["softmax<br/>400 probabilities"] SM --> PICK["draw one token"]
Softmax raises e (≈ 2.718) to the power of each score, so a bigger score gets a disproportionately bigger share, then divides by the total so the shares add up to 1:
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| the score of candidate token | = 2.0 | |
| the temperature | 0.5 | |
| e ≈ 2.718 raised to that power | = 54.6 | |
| number of candidates (the vocabulary size) | 3 here, 400 in the model | |
| add up over every candidate | ||
| probability that token comes next | 0.844 |
In words: "the chance of token i is e to the power of its score over the temperature, divided by the same quantity summed over all tokens."
With the numbers: T = 0.5 doubles every score to (4, 2, 1): e⁴ = 54.6, e² = 7.39, e¹ = 2.72, total 64.7, so p(A) = 54.6 / 64.7 = 0.844. Temperature 0 is the limit case: all probability on the top score.
In Python
import math
z = [2.0, 1.0, 0.5]
T = 0.5
# e^(z_i / T) for each candidate
exps = [math.exp(z_i / T) for z_i in z]
[round(e, 2) for e in exps] # → [54.6, 7.39, 2.72]
# Σ_j e^(z_j / T)
total = sum(exps)
round(total, 1) # → 64.7
# p_i: each share of the total
[round(e / total, 3) for e in exps] # → [0.844, 0.114, 0.042]
The same three scores, across more temperatures:
Figure 6 · Chart
At T = 0.25 token A takes 98% of the probability; at T = 2 the three tokens share it 48%, 29% and 23%
The untrained model's own scores show what random weights give:
Figure 7 · Chart
The untrained model's 12 favourites are random byte fragments, each only 1.25 to 1.4 times the uniform 1-in-400 share
For extraction and tool calls, where you want the most likely answer, use a low temperature; for creative writing, a higher one. Temperature 0 makes the output less random, but on real serving hardware it does not guarantee the same output twice.
Chapter 5
The loop: append and repeat
The drawn token is appended and the whole trip runs again, until the model draws a stop token or the reply reaches a length limit. Done simply, each trip re-reads the whole text so far. With a 2-token prompt and 4 new tokens, the four steps read 2, 3, 4 and 5 tokens: 14 positions to produce 4 tokens.
Figure 8 · Diagram
flowchart LR S["ids so far"] --> M["full forward pass<br/>over ALL ids"] M --> P["probabilities for the next id"] P --> D["draw one id"] D --> A["append it"] A -->|"not done"| S A -->|"stop token or length limit"| OUT["decode ids to text"]
That work is wasted. Each token takes in only the tokens before it (the causal mask), so an earlier token's vectors cannot change when new tokens arrive. A KV cache, named after the keys and values it keeps from attention, stores that work and reuses it, so each later step runs only the new token (Inference).
Without a cache, the work adds up over the steps:
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| prompt length in tokens | 2 | |
| tokens to generate | 4 | |
| the step counter, from 0 to | 0, 1, 2, 3 | |
| tokens re-read at step | 2, 3, 4, 5 | |
| total positions run through the model | 14 |
In words: "each step re-reads the prompt plus everything generated so far; add that up over all steps."
With the numbers: 4 × 2 + (4 × 3) / 2 = 8 + 6 = 14.
In Python
p, n = 2, 4
# Σ over t = 0 .. n-1 of (p + t): 2 + 3 + 4 + 5
sum(p + t for t in range(n)) # → 14
# the closed form gives the same count
n * p + n * (n - 1) // 2 # → 14
The square in that formula is what makes long replies expensive:
Figure 9 · Chart
Without a cache work grows with the square of output length, 23,900 positions at 200 tokens against 219 with a KV cache
In code: generate runs the loop without a cache, and the Generation it returns counts the positions read; naive_vs_cached_work counts both ways for the chart. View source
Even with a cache, each new token costs a trip through the model, while the prompt is read in one pass, so the length of the reply drives both the wait and the bill.
Chapter 6
Training: the same forward pass, plus a loss
So far the untrained model has picked only random byte fragments, because its weights are random. Training sets the weights, using the same pipeline. Run a real sentence through it: at every position the model gives some probability to the token that really comes next, and the lower that probability, the more surprised it was. The loss is the average surprise, and training nudges every weight to make it smaller, one batch of text after another.
Surprise is −ln p, minus the logarithm of the probability. A logarithm answers "to what power must I raise e to get this number?" For a probability, between 0 and 1, it is negative, so the minus sign makes the surprise positive: 0 when p = 1, and huge when p is tiny. A guess that gives the right token 0.5 costs −ln 0.5 = 0.693. The untrained model averages 5.97 on a real sentence, close to ln 400 = 5.99, the loss of a blind guess among 400 tokens.
Figure 10 · Diagram
flowchart LR T["training text"] --> F["forward pass<br/>(this whole lesson)"] F --> P["probabilities at every position"] P --> L["loss: −ln p(actual next token)<br/>averaged over positions"] L --> B["backpropagation<br/>gradient for every weight"] B --> U["optimizer nudges weights"] U -->|next batch| F
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| tokens in the training text | 12 ("The model reads tokens, not words.") | |
| the token at position | ||
| probability the model gave the actual next token, having seen everything before it; the bar reads "given" | ≈ 1/400 when untrained | |
| natural logarithm | ln(1/400) = −5.99 | |
| the average over all guesses | ||
| the loss training pushes down | 5.97 |
In words: "for every position, take the log of the probability the model gave the true next token, average them, and flip the sign."
With the numbers: a uniform guess over 400 tokens gives every true token p = 1/400, so each term is −ln(1/400) = ln 400 = 5.99. The untrained model scores 5.97, so it is still guessing. Perplexity, e raised to the loss, is 393: "as unsure as choosing among 393 equally likely tokens".
In Python
import math
# one guess that gave the true token p = 0.5
round(-math.log(0.5), 3) # → 0.693
n = 12
# a uniform guess gives every true token 1/400
p = [1 / 400] * (n - 1)
# -(1/(n-1)) Σ ln p
L = -sum(math.log(p_i) for p_i in p) / (n - 1)
round(L, 2) # → 5.99
In code: next_token_loss averages cross_entropy over every position of a text. View source
Pretraining is this, run over trillions of tokens. To predict the next token well, a model has to pick up grammar, facts and patterns of reasoning, and that is how the machinery that produced byte fragments here becomes a useful model.
Test yourself
6 questions
Answer each one out loud or on paper before you open it.
Question 1What happens, step by step, when you send a prompt?Think it through, then reveal
Tokenizer turns text into ids; each id looks up an embedding; position information is added; the vectors pass through N transformer blocks; the last position's vector is scored against the whole vocabulary; softmax and sampling pick a token; it's appended and the loop repeats until a stop token.
Question 2Why does only the last position matter when generating?Think it through, then reveal
Its vector has attended to every earlier token and is the one trained to predict what comes next; earlier rows predict tokens we already have.
Question 3What does temperature do to the scores (2, 1, 0.5) at T = 0.5?Think it through, then reveal
Doubles them to (4, 2, 1) before softmax, sharpening the distribution: the top token rises from 0.63 to 0.84.
Question 4How many token positions does the naive loop process for a 2-token prompt and 4 new tokens?Think it through, then reveal
2 + 3 + 4 + 5 = 14. A KV cache avoids re-reading the unchanged prefix.
Question 5What loss does an untrained model get over a 400-token vocabulary, and why?Think it through, then reveal
About ln 400 ≈ 5.99 (perplexity about 400), because with random, tiny weights its predictions are close to uniform.
Question 6How is training different from inference?Think it through, then reveal
Same forward pass, plus a loss comparing predictions to the real next tokens, then backpropagation and a weight update. Inference only runs the forward pass.
Primary sources
The papers behind this lesson
The architecture inside the "transformer blocks" box.
Read on rumblr →The paperThe decoder-only, next-token-prediction recipe this pipeline follows, including learned positions, byte-level BPE and tied embeddings.
The paperShowed that scaling this same loop up produces models that follow instructions from examples in the prompt.
Read on rumblr →The paperIntroduced nucleus (top-p) sampling and explained why pure greedy decoding produces repetitive text.
The paperResearcher's shelf
Further reading
- Andrej Karpathy, Let's build GPT (video): https://www.youtube.com/watch?v=kCc8FmEb1nY
- Karpathy's
nanoGPT: https://github.com/karpathy/nanoGPT - Jay Alammar, The Illustrated GPT-2: https://jalammar.github.io/illustrated-gpt2/
- 3Blue1Brown, But what is a GPT? (video): https://www.youtube.com/watch?v=wjZofJX0v4M
- Hugging Face, How to generate text (decoding strategies): https://huggingface.co/blog/how-to-generate
About this lesson. This is the illustrated edition of a lesson from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it.