Part 13 / Stage 4
How LLMs work
Goal: Just enough LLM theory to make good engineering decisions: tokens, next-token prediction, sampling, context, limits. Time: ~2.5 hours · Needs: Part 12 (transformer)
What you will learn
- Tokens and tokenization: byte-pair encoding
- Next-token prediction, from bigrams up
- Sampling: temperature, top-k, top-p
- Context windows, and what they cost
- How models are trained: pretraining, instruction tuning, RLHF
- Limitations: hallucination, cut-offs, wording sensitivity
Topics in this part
Practice
Exercise 1: More merges
Extend the lesson's BPE to 10 merges on the same corpus and print the token sequence for every word. Which words become a single token first, and why?
Show the solution to Exercise 1
# Exercise 1: More merges
from collections import Counter
corpus = ["low", "lower", "lowest", "newer", "newest", "wider"]
words = [list(w) + ["</w>"] for w in corpus]
def merge_once(words):
pairs = Counter((a, b) for w in words for a, b in zip(w, w[1:]))
if not pairs:
return words, None, 0
(a, b), n = pairs.most_common(1)[0]
merged = []
for w in words:
out, i = [], 0
while i < len(w):
if i < len(w) - 1 and (w[i], w[i + 1]) == (a, b):
out.append(a + b); i += 2
else:
out.append(w[i]); i += 1
merged.append(out)
return merged, a + b, n
for step in range(1, 11):
words, token, n = merge_once(words)
if token is None:
break
print(f"merge {step}: '{token}' ({n}x)")
print()
for original, tokens in zip(corpus, words):
print(f"{original:8s} -> {tokens}")
# The most frequent whole words ('low', 'newer'-family stems) merge into
# single tokens first — frequency decides what earns its own token.
Exercise 2: Trigram upgrade
Upgrade the bigram model to trigrams (condition on the previous TWO words) on the same text. Generate 8 words from "the cat". Is it more or less repetitive than the bigram output, and why does data get scarce?
Show the solution to Exercise 2
# Exercise 2: Trigram upgrade
import random
from collections import Counter, defaultdict
text = ("the cat sat on the mat . the dog sat on the rug . "
"the cat saw the dog . the dog saw the cat .").split()
counts = defaultdict(Counter)
for a, b, c in zip(text, text[1:], text[2:]):
counts[(a, b)][c] += 1
random.seed(1)
context, out = ("the", "cat"), ["the", "cat"]
for _ in range(8):
nxt = counts.get(context)
if not nxt:
break
word = random.choices(list(nxt), weights=nxt.values())[0]
out.append(word)
context = (context[1], word)
print("generated:", " ".join(out))
print("contexts seen:", len(counts))
# Trigrams copy the training text more faithfully (each 2-word context has
# few continuations) — but most possible 2-word contexts were never seen at
# all. That sparsity is why counting stops scaling and neural models took over.
Exercise 3: Greedy vs sampled
Using the lesson's logits [5.0, 2.5, 2.0, 0.5], generate 20 picks at T=0.5 and T=2.0 (seeded) and print the counts per token. How often did "pizza" appear at each temperature?
Show the solution to Exercise 3
# Exercise 3: Greedy vs sampled
from collections import Counter
import numpy as np
tokens = ["Paris", "Lyon", "London", "pizza"]
logits = np.array([5.0, 2.5, 2.0, 0.5])
def probs(temperature):
z = logits / temperature
e = np.exp(z - z.max())
return e / e.sum()
rng = np.random.default_rng(0)
for t in [0.5, 2.0]:
picks = rng.choice(tokens, size=20, p=probs(t))
print(f"T={t}: {dict(Counter(picks.tolist()))}")
Exercise 4: Context budget
A model costs $4 per million input tokens. You have 40 documents of ~2,000 tokens each and 500 questions to answer. Print the cost of (a) stuffing all documents into every question vs (b) retrieving the best 2 documents per question. (Pure arithmetic — write it as code.)
Show the solution to Exercise 4
# Exercise 4: Context budget
PRICE_PER_M = 4.00
DOCS, DOC_TOKENS, QUESTIONS, QUESTION_TOKENS, TOP_K = 40, 2000, 500, 50, 2
stuff_tokens = QUESTIONS * (DOCS * DOC_TOKENS + QUESTION_TOKENS)
retrieve_tokens = QUESTIONS * (TOP_K * DOC_TOKENS + QUESTION_TOKENS)
print(f"stuff everything : {stuff_tokens:,} tokens = ${stuff_tokens / 1e6 * PRICE_PER_M:,.2f}")
print(f"retrieve top {TOP_K} : {retrieve_tokens:,} tokens = ${retrieve_tokens / 1e6 * PRICE_PER_M:,.2f}")
print(f"savings factor : {stuff_tokens / retrieve_tokens:.0f}x")
Mini-project: Tiny language model
Train a character-level bigram model on a few paragraphs of text you choose, and generate 100 characters at temperatures 0.5, 1.0 and 2.0. Print all three samples and label which looks loopy, balanced, and chaotic.
A complete version is in solutions/mini_tiny_language_model.py.
Stretch: replace the count table with a small PyTorch model conditioning on the previous 4 characters.
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
| Thinking in words, billing in tokens | Estimates off by 30%+ | Count tokens (the API reports usage) |
| Asking character-level questions | Models see tokens, not letters | Use code for string tasks |
| High temperature for extraction | Random wrong fields | T low for structured tasks |
| Stuffing the full context window | Slow, expensive, worse answers | Retrieve the relevant few passages |
| Trusting confident tone | Fluency ≠ truth | Ground and verify (Parts 15, 17) |
Quick recap
- BPE merges frequent pairs until a fixed vocabulary covers all text.
- There is one mechanism — predict the next token's distribution — and the bigram model shows it naked.
- Temperature was measured directly: the top token's probability fell from 0.991 to 0.875 to 0.619 at T = 0.5, 1 and 2.
- Context is finite and billed; retrieval beats stuffing.
- Models are pretrained, then instruction-tuned, then preference-trained — and their knowledge has a cut-off.
- Hallucination is the mechanism working as designed — engineer around it.
Checklist
- I can run five BPE merges on paper.
- I can explain an LLM as "bigram model, scaled" and what that misses.
- I know when to lower and raise temperature.
- I can name two costs of long context.
- I can name the three training phases and what each adds.
- I plan for hallucination rather than hoping it away.
Read more: Claude API overview