rumblr Work in progressWIP

● The AI Primer · Lesson 1 · Part 1: how a language model works

What happens when you send a prompt

the big picture, end to end

This lesson covers From your words to numbers, through the layers, to a reply one word at a time

Free lesson 25 min10 figures and diagrams6 interactive

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

  1. A language model reads your prompt as tokens, turns each token into a vector, and passes the vectors through a stack of transformer blocks.
  2. 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.
  3. The reply is written one token per trip round the loop. Without a KV cache, every trip re-reads the whole text so far.
  4. 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

Reading it: read left to right, then follow the arrow back. The prompt is cut into tokens, and each token's number fetches a list of numbers from a table, with its position added so that order counts. The lists pass through the transformer blocks, where the tokens share information. Then the last token's list becomes a score for every token the model knows, the scores become probabilities, and one token is drawn. It is appended, and the loop runs again until the model draws a stop token or reaches a length limit. Training runs the same boxes and adds a loss at the end.

Chapter 1

Text to ids: the coat check

Try the first step before reading about it. Type anything, or press an example, and see what the model is handed.

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

Reading it: one box: text goes in, whole numbers come out.

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

Reading it: two lookups and one add. Rows are fetched, not multiplied, which is why this step costs almost nothing. Both tables are learned in training, and similar tokens end up with similar rows (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.

Move a ticket to another seat and watch which rows change. Then press Leave it out and move it again.

Chapter 3

The transformer blocks: rounds of meeting and desk work

Step the grid through the two transformer blocks and watch how much of the prompt each row ends up carrying.

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

Reading it: the grid passes through two blocks, then a final norm that rescales each row on its own.
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

Take three candidates for the next token, scored 2.0, 1.0 and 0.5. Drag the temperature, then press Draw to pick tokens the way the model does.

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

Reading it: follow one row of 32 numbers to one drawn token: 400 scores, divided by the temperature, turned into 400 probabilities.

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

token A (score 2.0) token B (1.0) token C (0.5) 0.0 0.2 0.4 0.6 0.8 1.0 probability Temperature: low sharpens, high flattens T = 0.25 T = 0.5 T = 1.0 T = 2.0

At T = 0.25 token A takes 98% of the probability; at T = 2 the three tokens share it 48%, 29% and 23%

Reading it: three groups of bars, one per candidate token; within each group the bars run from low temperature (left) to high (right). For token A the bars fall as temperature rises, and for tokens B and C they rise. At T = 0.25, A takes almost everything; at T = 2 the three are much closer.

The untrained model's own scores show what random weights give:

Figure 7 · Chart

'b' 'q' '3' ' s' ' i' '�' 'set' 'N' ' b' 0.0000 0.0005 0.0010 0.0015 0.0020 0.0025 0.0030 0.0035 probability of being next Untrained model: 'The cat sat on the' → ? uniform guess 1/400

The untrained model's 12 favourites are random byte fragments, each only 1.25 to 1.4 times the uniform 1-in-400 share

Reading it: the bars are the untrained model's 12 likeliest next tokens after "The cat sat on the"; the dashed line is a uniform guess, 1 in 400 (0.25%). The top one gets about 0.35%, 1.4 times uniform, and the twelfth about 1.25 times; across all 400 tokens every probability stays between 0.74 and 1.39 times uniform. The favourites are random byte fragments: every step works, but nothing has been learned yet.

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

Run the loop and count what the model reads at each step, first without a cache and then with one.

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

Reading it: the expensive arrow is "full forward pass over ALL ids": every step re-reads text that has not changed.

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

0 25 50 75 100 125 150 175 200 tokens generated (after a 20-token prompt) 0 5000 10000 15000 20000 25000 token positions run through the model Why the naive loop is too slow no cache: re-read everything KV cache: one new token per step

Without a cache work grows with the square of output length, 23,900 positions at 200 tokens against 219 with a KV cache

Reading it: the x-axis is how many tokens have been generated after a 20-token prompt; the y-axis is total work in token positions. The red curve bends upward: it grows with the square of the output length. The blue line (with a KV cache) grows by one per token. At 200 tokens the gap is more than a hundredfold.

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

Reading it: the first two boxes are the trip a prompt takes. Training adds the loss; backpropagation (Neural networks) works out each weight's share of it, and the optimizer (Optimizers) adjusts the weights. One pass over n tokens gives n − 1 guesses at once, in parallel, which is a large part of why transformers train fast.
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.

Here is the loss one guess at a time, on the sentence “The model reads tokens, not words.” Pick a guess and lower its probability to see what one bad guess does to the average.

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

Vaswani et al. (2017), Attention Is All You Need.

The architecture inside the "transformer blocks" box.

Read on rumblr →The paper
Radford et al. (2019), Language Models are Unsupervised Multitask Learners (GPT-2).

The decoder-only, next-token-prediction recipe this pipeline follows, including learned positions, byte-level BPE and tied embeddings.

The paper
Brown et al. (2020), Language Models are Few-Shot Learners (GPT-3).

Showed that scaling this same loop up produces models that follow instructions from examples in the prompt.

Read on rumblr →The paper
Holtzman et al. (2019), The Curious Case of Neural Text Degeneration.

Introduced nucleus (top-p) sampling and explained why pure greedy decoding produces repetitive text.

The paper

Researcher'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.