All courses

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

▶ Watch this lesson Start the whole course

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.

Why not just count what comes next?

The chain rule says a model of $p(x_t \mid x_{<t})$ is all we need to generate text. The most direct way to get it is to scan a huge pile of text and count how often each token follows each context. That is plain bookkeeping. So why don't LLMs work this way? And what do they do instead that lets them handle sentences nobody has ever written?

Truncate the context, then count

A full context $x_{<t}$ is almost always unique, so counting it directly is hopeless. An **n-gram model** keeps only the last $n-1$ tokens and ignores the rest. A **bigram** ($n=2$) uses just the previous token. Build a $V\times V$ table: the row is the previous token, the column is the next token. Add 1 each time a pair appears, then divide each row by its total. Larger $n$ gives more context but far fewer examples per row.

Bigram estimate and the sparsity wall

$$p(x_t=b \mid x_{t-1}=a)=\frac{\text{count}(a\,b)}{\sum_{b'}\text{count}(a\,b')}$$ count$(a\,b)$ is how often token $a$ is immediately followed by $b$ in the corpus. The denominator is how often $a$ is followed by anything. An n-gram table has $V^{n-1}$ contexts × $V$ next tokens $=V^n$ cells. With $V=50{,}000$ and $n=3$, that is $1.25\times10^{14}$ cells. A $10^{12}$-token corpus holds at most $10^{12}$ trigram occurrences, so over 99% of cells stay at zero. Many perfectly plausible continuations are among them.

Counts can't transfer; vectors can

Corpus: *the cat sat . the dog sat . the cat ran .* After *the*: cat 2, dog 1, so $p(\text{cat}\mid\text{the})=2/3$. After *cat*: sat 1, ran 1, so each gets $1/2$. After *dog*: only sat, so $p(\text{ran}\mid\text{dog})=0$. The table treats cat and dog as unrelated symbols. Now give each word a vector: cat $=(1.0,0.9)$, dog $=(0.9,1.0)$. They are close because both words appear in the same places (after *the*, before *sat*). Give *ran* the vector $(1,1)$ and score each pair by a dot product: cat·ran $=1.0+0.9=1.9$ and dog·ran $=0.9+1.0=1.9$. Similar vectors give similar predictions, so dog→ran is no longer ruled out.

A bigram model in numpy

Count adjacent pairs into a $V\times V$ table, then normalize each row so it sums to 1. Row $a$ is now the next-token distribution after $a$.
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

An n-gram model counts what follows the last $n-1$ tokens. It is trivial to build, but the number of possible contexts grows as $V^{n-1}$. Most contexts and pairs are never seen: an unseen pair gets probability zero, and an unseen context gets no estimate at all. Instead, tokens and contexts can be represented as vectors whose numbers are adjusted to fit the data (learned). Then similar contexts end up close together and share evidence. That is the core move behind LLMs.

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.