Count-based n-grams and the need for generalization
Build a bigram model by counting. Explain why counts become sparse as the context length grows, and how learned vector representations let similar contexts share statistics.
Builds on: Language modeling as next-token prediction
What the animation says
Just count what comes next?
To generate text, we only need the chance of each next token, given everything before it. The most direct way: scan a huge pile of text and count what follows each context. But a full context is almost always unique. You would count it once, then never again. So an n-gram model keeps only the last n minus one tokens and ignores the rest. A bigram keeps just the previous token. Row: the previous token. Column: the next one.
Fill the table
Here is a tiny corpus: the cat sat, the dog sat, the cat ran. Slide a window along it, two tokens at a time. Each pair adds one to its cell. Row 'the' ends up with cat two, dog one. Row 'cat': sat one, ran one. Now each row must become probabilities that add up to one. So after 'the', what is the chance the next word is cat?
Normalize rows, in numpy
Two thirds. Divide by the row total: how often 'the' was followed by anything. Here, three. In numpy, these lines build the vocabulary and an empty six by six table. The for loop walks adjacent pairs and adds one per pair. This line divides each row by its own sum, so every row adds up to one. Now look at row 'dog'. Only one pair ever started with dog. Tap the sensible next word that still got probability zero.
The sparsity wall
Zeros like that are not rare. They are almost everything. An n-gram table has V to the power n cells: every context, times every next token. With fifty thousand tokens and n equal to three, that is one point two five times ten to the fourteen cells. Even a corpus of a trillion tokens fills at most a trillion of them. So over ninety-nine percent stay zero, including many plausible continuations. Bigger n makes it worse.
Vectors share evidence
The table treats cat and dog as unrelated symbols. Nothing learned about one helps the other. Instead, give each word a short list of numbers, a vector. Cat is one and point nine. Dog is point nine and one. They are close because both show up in the same places: after 'the', and before 'sat'. Give 'ran' the vector one, one. Score a pair with a dot product: multiply matching numbers, then add. Cat dot ran is one plus point nine: one point nine. What does dog dot ran give?
From counting to learning
One point nine: point nine plus one. Exactly the same score as cat. So 'dog ran' is no longer ruled out, even though that pair never appeared. In real models these numbers are not hand-picked. They are adjusted to fit the data: learned. Similar contexts end up close together and share evidence. Counting hits a wall. Similarity gets past it. That is the core move behind LLMs.
Truncate the context, then count
Bigram estimate and the sparsity wall
Counts can't transfer; vectors can
A bigram model in numpy
import numpy as np
words = "the cat sat . the dog sat . the cat ran .".split()
vocab = sorted(set(words)); idx = {w: i for i, w in enumerate(vocab)}
V = len(vocab)
counts = np.zeros((V, V))
for a, b in zip(words, words[1:]):
counts[idx[a], idx[b]] += 1
P = counts / counts.sum(axis=1, keepdims=True)
print(P[idx["the"], idx["cat"]]) # 0.666...
print(P[idx["dog"], idx["ran"]]) # 0.0 - never seen
Counting hits a wall; similarity gets past it
On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.
Bytewise
All courses