
language modeling from scratch
how a language model really works, piece by piece: tokens, embeddings, attention, training, and what it costs to run. ends with building a tiny lm yourself.
- 13 short video lessons, more coming in unit 2
- study kit: one page per lesson (pdf, with ad-free)
- 52 practice questions with answer key: try them right here, free
- free to watch, with ads
- unit 1: how models read and learn
- 01what is a token?
- 02how tokens become numbers
- 03how tokens pay attention
- 04one block, stacked
- 05guess the next token
- 06learning from surprise (loss)
- 07walking downhill (optimizers)
- 08counting flops
- 09where memory goes
- 10the knobs that matter
- 11build a tiny lm
- unit 2: making it fast
- 01why gpus?
- 02memory is the bottleneck
try it yourself
pick a lesson, then pick an answer. wrong answers are how the knobs learn: a missed one comes back at the end.
lesson 01 · what is a token?
question 1 of 4

texts: "low", "lower", "lowest". what is the first bpe merge?
answer key · all 52
01 · what is a token?
texts: "low", "lower", "lowest". what is the first bpe merge?
"l" + "o" → "lo". "l" + "o" appears 3 times, more than any other pair, so it merges first.
how does a bpe tokenizer handle a word it never saw in training?
it splits the word into smaller known pieces. every word can be built from smaller pieces, down to single bytes, so nothing is unknown.
why does a chatbot’s context limit count tokens rather than words?
the model only ever sees tokens, and one word can be several tokens. the model only ever sees tokens, and one word can be several tokens.
what is the gpt-2 vocabulary size?
50,257 tokens. gpt-2 has 50,257 tokens.
02 · how tokens become numbers
a model has a 32,000-token vocabulary and 512-number vectors. how many numbers are in its embedding table?
16,384,000. 32,000 × 512 = 16,384,000.
after training, the vectors for "cat" and "dog" are…
close together. words used in similar ways drift close together.
why isn’t the token id enough on its own?
it’s an arbitrary label: 9246 and 9247 aren’t related in meaning. the id is just a label. the vector carries the meaning.
how do the embedding rows learn?
training nudges each row in whatever direction helps predict the next token. training nudges each row in whatever direction helps predict the next token better.
03 · how tokens pay attention
attention checks every pair of tokens. 4 tokens = 16 checks. how many for 16 tokens?
256. 16 × 16 = 256 checks (4× the text, 16× the work).
which vector answers "what am i looking for?"
query. the query asks; keys are matched against it.
in "the cat sat because it was tired", what can the token "sat" attend to?
"the", "cat" and "sat" itself. a token sees itself and the words before it, never the later words.
why use many heads instead of one?
each head can track a different pattern at the same time. each head can track a different pattern (who "it" is, nearby words, grammar, the topic) at the same time.
04 · one block, stacked
inside one block, what comes first?
attention. tokens first gather context (attention), then each thinks alone (mlp).
which is the residual connection for an attention step with pre-norm?
out = x + attention(norm(x)). out = x + attention(norm(x)): normalize, attend, then add back the input.
how many blocks does gpt-2 small stack, and do they share weights?
12 blocks, each with its own weights. 12 blocks, each with its own weights.
gpt-2’s output layer scores every vocabulary token. how many scores per position?
50,257. one score per vocabulary token: 50,257.
05 · guess the next token
odds: mat 51%, floor 25%, sofa 12%, rug 10%, moon 2%. which tokens does top-p 0.9 keep?
mat, floor, sofa, rug. 51 + 25 + 12 = 88% is under 90%, so rug is added to reach 98%. moon is dropped.
you raise the temperature from 0.7 to 1.5. the outputs become…
more varied and surprising. a high temperature flattens the odds, so unlikely tokens get picked more.
why do chatbot answers appear a few words at a time?
each token needs its own full pass through the model. each token needs its own full pass through the model, so they come out one by one.
what is the problem with greedy decoding for long text?
it tends to repeat itself. it always takes the same top choice, so it tends to repeat itself.
06 · learning from surprise (loss)
the model gives the right token 50%. what is the loss? (ln 2 ≈ 0.69)
about 0.69. −ln(0.5) = ln 2 ≈ 0.69.
which prediction has the highest loss?
right token at 1%. the less probability on the right answer, the bigger −log(p).
losses in a batch: 0.1, 2.3, 0.4, 4.6, 0.9, 1.2, 3.1, 2.6. what single number summarizes it?
1.9 (the average). the average: 15.2 ÷ 8 = 1.9.
training loss falls but loss on unseen text stays flat or rises. what does that mean?
the model is memorizing instead of learning patterns. the model is memorizing the training text instead of learning patterns that generalize.
07 · walking downhill (optimizers)
w = 1.0, grad = −4, lr = 0.05. what is w after one step?
1.2. 1.0 − 0.05 × (−4) = 1.2.
what does adam add on top of plain sgd?
a separate step size for every weight. adam adapts each weight’s step size from its recent gradients.
what is the "w" in adamw?
weight decay: gently shrinking the weights each step. weight decay gently shrinks the weights each step so none grow too big.
what does a typical learning-rate schedule for an lm look like?
warm up to a peak, then slowly cool down. warm up from small to the peak over the first steps, then slowly cool down (often a cosine decay).
08 · counting flops
a 1-billion-parameter model trains on 20 billion tokens. about how many flops?
1.2 × 10²⁰. 6 × 10⁹ × 2 × 10¹⁰ = 1.2 × 10²⁰ flops.
that run on a gpu that really delivers 10¹⁴ flops per second. about how long?
about 14 days. 1.2 × 10²⁰ ÷ 10¹⁴ = 1.2 × 10⁶ seconds ≈ 14 days.
why is it 6 flops per parameter per token, not 2?
2 for the forward pass, plus about 4 for the backward pass. the backward pass costs roughly twice the forward: 2 + 4 = 6.
a gpu is rated at 1,000 tflop/s. what should you plan for?
about 40% of it, or less. real runs rarely hit peak; around 40% is often considered good.
09 · where memory goes
how much memory does a 7-billion-parameter model need for weights, gradients and adam state?
about 112 gb. 7 × 10⁹ × 16 bytes = 112 gb (before activations).
how many 80 gb gpus does that take at minimum, just for that state?
2. 112 ÷ 80 = 1.4, so at least 2 gpus.
which piece grows when you use longer text?
activations. activations scale with batch size and sequence length.
for running a trained model (no training), what can you drop?
gradients, optimizer state and the master copy. you mainly need the weights (plus a working cache).
10 · the knobs that matter
a model has width 1,024 and 16 heads. what is the head size, and the usual mlp width?
64 per head, mlp 4,096. 1,024 ÷ 16 = 64 per head; mlp ≈ 4 × 1,024 = 4,096.
your loss suddenly spikes and training diverges. what do you change first?
lower the learning rate. the learning rate is the most common culprit.
is the learning rate learned by the model?
no: it’s a hyperparameter you choose before training. it’s a hyperparameter you choose before training.
why tune on small models first?
experiments are cheap and fast, and good settings largely carry over. experiments are cheap and fast there, and good settings largely carry over when you scale up.
11 · build a tiny lm
which order is right for building a tiny lm?
train a tokenizer → tokenize the data → build the model → train the loop → sample text. train a tokenizer → tokenize the data → build the model (+ loss, optimizer) → train the loop → sample text.
why save checkpoints?
so a crash doesn’t wipe out hours of work. you can resume from the last save instead of starting over.
which loss and optimizer does the tiny lm use?
cross-entropy loss and adamw. cross-entropy loss; adamw (with warmup and a cosine schedule).
why is tinystories a good first dataset?
its language is simple, so even a small model can write real sentences. its language is simple, so even a small model can learn to write real sentences.
u2·01 · why gpus?
why are gpus good at training neural networks?
they run the same simple math on thousands of cores at once. the work is mostly matrix multiplies, which split perfectly across many simple cores.
what makes tensor cores fastest?
low-precision numbers, like 16-bit or 8-bit. low-precision numbers, like 16-bit or 8-bit, run fastest.
an h100 does about 10¹⁵ operations per second. how many in one minute?
6 × 10¹⁶. 10¹⁵ × 60 = 6 × 10¹⁶.
what is "the catch" with all those cores?
they need data fast enough, or they sit idle. if data arrives slowly, the cores sit idle.
u2·02 · memory is the bottleneck
an operation does 600 million operations and moves 4 million bytes. on an h100 (break-even ~300 ops/byte), is it memory-bound?
yes: 150 ops/byte is below ~300. 600m ÷ 4m = 150 ops/byte. below ~300, so it’s memory-bound.
which is usually memory-bound?
adding two vectors. an add does one operation per number loaded: very low intensity.
why has moving data become the expensive part?
compute speed grew much faster than memory speed. compute speed grew much faster than memory speed, so cores often wait on data.
what does "fusion" aim to do?
combine several steps into one kernel so data is loaded once. combining steps means data is loaded once and reused, moving less data.
loading…