Predicting the next word
How can something that only predicts words write an essay?
Lesson complete
If you like:
Type “the sky is” and stop. What word comes next? You probably thought of “blue.” Maybe “gray.”
No voice: the lesson advances on its own with subtitles.
The voice for this lesson is being recorded: for now it advances on its own with subtitles.
Review modeComment on this stepI finished the lesson
What you will achieve
- Explain how a language model writes: it gives a probability to every word that can come next, picks one, adds it to the context, and repeats.
- Compute probabilities from counts and with softmax, and predict what temperature, top-k, and top-p do to them.
- Answer honestly “how can something that only predicts write an essay?”, including what that answer does not guarantee.
Key ideas
- A language model gives, for a context, a probability to every word (or piece) that can come next.
- The simplest model counts: probability = count ÷ total. Neural networks give scores, and softmax turns them into probabilities that add up to one.
- It writes in a loop: pick a word, add it to the context, and compute again. That is autoregression.
- Always taking the most likely word (greedy) falls into repetition; sampling gives a different text on every run. Temperature sharpens (low) or flattens (high) the probabilities; top-k and top-p cut off rare words.
- Predicting well demands capturing a lot, but the goal is the likely, not the true. From GPT-1 to GPT-3 the objective is the same; the scale changes.
What many people believe
Common belief Since it only predicts the next word, a language model is an autocomplete that copies phrases it has already seen.
What is true It computes a fresh distribution for every context and can write sentences it never read (even our eight-sentence model does). Getting it right at scale demands capturing grammar, facts, and patterns of reasoning. It does optimize for the likely, though, not the true.
Check yourself
Four questions. No grade, no account: they just show whether the idea stuck.
Under the hoodFor those who want the math and the code. You do not need it to follow the course.
The objective: predict the next piece
By the chain rule, the probability of a text factors into next-piece predictions:
A language model is any model of . GPT-1 is trained by maximizing over a corpus, the “standard language modeling objective” (equation 1 of the paper), where is the size of the context window. It is equivalent to minimizing the cross-entropy . Generating is the reverse trip: , one piece at a time (autoregression).
Counting: the n-gram model
With a window of pieces, the maximum-likelihood estimate is the relative frequency:
where counts how many times followed context . In the lesson (, bigrams), “is” appears times and , so . Shannon (1948) already generated text this way: his “second-order word approximation” picks each word according to the transition frequencies from the previous one. The limit is sparsity: with a vocabulary of size there are up to contexts, almost all rare or never seen, and the table does not generalize. Bengio et al. (2003) proposed replacing it with a network that learns a vector per word: if “dog” and “cat” have similar vectors, what is learned from one sentence carries over to the other.
Softmax and temperature
A network produces a score (a logit) for every piece of the vocabulary. The probability is
With it is the ordinary softmax. Adding the same constant to every score changes nothing; that is why the lesson’s scores, (counts ; rounded on screen to ), give exactly count ÷ total. In general, with we get : with , blue gets ; with , ; with , . As all the mass goes to the highest-scoring piece (greedy); as the distribution tends to uniform. The name comes from statistical physics: the Boltzmann distribution has this same form, with the temperature dividing. It plays this role in, for example, knowledge distillation (Hinton et al., 2015).
Top-k and top-p
After the softmax one can truncate. Top-k (Fan et al., 2018, who sample among the most likely) keeps the most likely pieces. Top-p, or nucleus sampling (Holtzman et al., 2020), keeps the smallest set whose probability adds up to at least :
Then it shares the probability out again, , and samples with . Holtzman et al. observed that decoding methods that maximize probability produce text that is “bland, incoherent, or gets stuck in repetitive loops” (the greedy loop in the lesson), and that truncating the unreliable tail, without going all the way to greedy, yields text closer to human writing.
In code
The lesson’s model: count pairs, softmax with temperature, top-p, and greedy writing, with the output it prints:
import math
from collections import Counter, defaultdict
text = ("the sky is blue . the sea is blue . the sky is gray . the sun is big . "
"at night the sky is dark . the sky is blue and the sun shines . "
"the sea is gray . today the sky is blue .")
pieces = text.split()
# 1. Count which piece follows each piece (a bigram model)
table = defaultdict(Counter)
for a, b in zip(pieces, pieces[1:]):
table[a][b] += 1
def softmax(scores, T=1.0):
z = [s / T for s in scores]
m = max(z)
e = [math.exp(v - m) for v in z] # subtracting the max does not change the result
return [v / sum(e) for v in e]
def distribution(context, T=1.0, top_p=1.0):
words = [w for w, _ in table[context].most_common()]
scores = [math.log(c) for _, c in table[context].most_common()] # score = ln(count)
p = softmax(scores, T)
nucleus, acc = [], 0.0 # top-p: the most likely words until they reach top_p
for w, q in zip(words, p):
nucleus.append((w, q)); acc += q
if acc >= top_p - 1e-9: break
total = sum(q for _, q in nucleus)
return [(w, round(q / total, 3)) for w, q in nucleus] # share it out again
print(dict(table["is"]))
for T in (1.0, 0.5, 2.0):
print(T, distribution("is", T))
print(distribution("is", top_p=0.7))
# 2. Write: always take the most likely piece (greedy) and repeat
written = ["the", "sky", "is"]
for _ in range(9):
written.append(table[written[-1]].most_common(1)[0][0])
print(" ".join(written))
# {'blue': 4, 'gray': 2, 'big': 1, 'dark': 1}
# 1.0 [('blue', 0.5), ('gray', 0.25), ('big', 0.125), ('dark', 0.125)]
# 0.5 [('blue', 0.727), ('gray', 0.182), ('big', 0.045), ('dark', 0.045)]
# 2.0 [('blue', 0.369), ('gray', 0.261), ('big', 0.185), ('dark', 0.185)]
# [('blue', 0.667), ('gray', 0.333)]
# the sky is blue . the sky is blue . the sky
The text was written for the lesson, and its Spanish and English versions are parallel word for word, so the counts match in both languages. The scene uses this same model (lm.ts), and verify-data.ts checks it; both live in the lesson folder.
Scale: GPT-1, GPT-2, and GPT-3
All three are decoder-only transformers trained with the objective above. GPT-1 (2018) read BooksCorpus, over 7,000 unpublished books; its size, 117 million parameters, appears in table 2 of the GPT-2 paper (“the smallest model is equivalent to the original GPT”). GPT-2 (2019) reached 1,542 million and read WebText, slightly over 8 million documents (40 GB of text). GPT-3 (2020) has 175,000 million (175 billion). A curiosity: the GPT-3 paper counts 125 million for a model with the same shape as GPT-1 (12 layers of 768). The gap fits the embedding table, which grows with the vocabulary: GPT-1 used 40,000 BPE merges and GPT-2 expanded the vocabulary to 50,257 pieces.
What comes next
We said “words,” but the model works with pieces: tokens (lesson 20). The probability is computed by a network that looks at the whole context with attention (lessons 21 and 22), and what it means to train it on almost the whole internet is the subject of lesson 23.
Decision lens
What this idea means if your job is to decide, not to code.
- The output is probabilistic: the same question can get different answers. For tasks with one right answer (extracting data, classifying) aim for low variation; for ideas and drafts, variation helps.
- Lowering the temperature makes the answer more repeatable, not more truthful: a likely error stays likely. No parameter replaces checking against sources.
- Ask which sampling parameters (temperature, top-p) your application uses and whether you can set them; not every product exposes them.
- A test with a single run is not evidence. Repeat each case several times with the real configuration and measure how much it varies before deciding.
Terms in this lesson
- Language model A model that, given some text (the context), gives a probability to every word or piece that can come next. It writes by adding one piece at a time.
- Autoregression Writing one piece at a time using what has already been written as input: each word produced becomes part of the context for the next.
- Softmax A function that turns any scores into positive probabilities that add up to one: it applies the exponential to each score and divides by the sum.
- Temperature A number that divides the scores before the softmax. Low sharpens the distribution (toward the greedy choice); high flattens it (toward chance).
- Top-p (nucleus sampling) Sampling only among the smallest group of most likely words whose probability adds up to at least p. Top-k does the same with a fixed number, k, of words.
- Sampling Drawing a new data point that follows a distribution: common things come out often and rare things seldom. It is how a generative model generates. (Not to be confused with the audio samples of lesson 2.)
- Distribution The way the data is spread out: which values (or combinations of values) are common, which are rare, and which never appear. With two measures it looks like a cloud of points.
- Embedding A vector of numbers, learned from data, that represents something (a word, a sentence, an image) so that similar things end up close. Each word has a row in an embedding table.
- Parameter Each of the numbers a model adjusts while training and in which it stores what it learned.
- Model A form of rule with adjustable numbers. Once trained, it is the learned rule.
- Token A piece of text (a word, a word fragment, a symbol, or a basic code) taken from the vocabulary. It is the unit the model reads and generates, and the unit you are billed for.
Full transcript
Sources
- Shannon, C. E. (1948). A Mathematical Theory of Communication
- Bengio, Y., Ducharme, R., Vincent, P., Jauvin, C. (2003). A Neural Probabilistic Language Model
- Radford, A., Narasimhan, K., Salimans, T., Sutskever, I. (2018). Improving Language Understanding by Generative Pre-Training (GPT-1)
- Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., Sutskever, I. (2019). Language Models are Unsupervised Multitask Learners (GPT-2; tabla 2: 117M y 1542M parámetros)
- Brown, T. B., et al. (2020). Language Models are Few-Shot Learners (GPT-3)
- OpenAI (2023). GPT-4 Technical Report («pre-trained to predict the next token in a document»)
- Ouyang, L., et al. (2022). Training language models to follow instructions with human feedback (InstructGPT)
- Hinton, G., Vinyals, O., Dean, J. (2015). Distilling the Knowledge in a Neural Network
- Fan, A., Lewis, M., Dauphin, Y. (2018). Hierarchical Neural Story Generation
- Holtzman, A., Buys, J., Du, L., Forbes, M., Choi, Y. (2020). The Curious Case of Neural Text Degeneration
CommentsThis lesson’s public conversation: questions, facts to check, ideas.
Comments live in GitHub Discussions, in the course’s public repository; writing one requires a GitHub account. They load from giscus.app when you open this section. The course reviewers read them, and if a change is accepted, it is applied in both languages. Open the thread on GitHub