Tokenwerk · The LLM textbook

Chapter 12 · II · From numbers to language · 7 minutes

Your first real language model

Your first language model needs no neural network, just a tally sheet. It counts what follows what and writes text from that. Gloriously dumb, but instructive.

A tally sheet as a language model

Now we build the simplest language model of all. No neural network, no training in the real sense, just counting: which character follows which, and how often? That alone lets it generate text. And it shows crystal clear what a better model has to do on top.

A bigram is a pair of tokens directly following each other. A bigram model only looks at the last token to predict the next one. In this first example, every character is a token.

The text abac contains the pairs a→b, b→a and a→c. So after a, b came once and c came once. Our estimate: after a, b and c are each half likely. (The last character has no successor and gives no pair.)

Previous Next a Next b Next c Row sum
a 0 1 1 2
b 1 0 0 1
c 0 0 0 0

We call this count table C. With three possible characters (vocabulary size V = 3) it has shape [3,3], in general [V,V]. The row picks the previous token, the column the next one.

From tally marks to percentages

Turning counts into probabilities is easy: the number in the cell divided by the row sum. After a there were 2 transitions, one of them to b. So b after a has probability 1/2.

That is the whole model already. It “knows” nothing about language; it just kept good books.

From a count to a probability

As a formula:

P(j∣i)=Cij∑kCik.P(j\mid i)=\frac{C_{ij}}{\sum_k C_{ik}}.
Symbol Meaning
i ID of the previous token, i.e. the row
j ID of the desired next token, i.e. the column
CijC_{ij} Count in the cell at row i and column j
k Running index over all possible next tokens
∑kCik\sum_k C_{ik} Sum of the counts in row i
P(j∣i)P(j\mid i) Probability of j when i comes before it

Written with positions, the same thing is P(xt∣xt−1)P(x_t\mid x_{t-1}): the token at position t, given the token right before it. The vertical bar means “given”, not “divided by”.

Problem: what never happened is impossible

Look at the c row: all zeros. We would have to divide by zero, and math says no. Besides, just because we never saw a transition, it shouldn't be impossible for all eternity.

The simple fix: we pretend we saw every transition a little more often, for example once more. That is called additive smoothing.

The a row [0,1,1] becomes [1,2,2]. The new sum is 5, the probabilities are [0.2,0.4,0.4]. The c row becomes [1,1,1], so a third each. What we observed stays in front, but nothing is completely ruled out anymore.

How much to smooth is a tuning knob. With heavy smoothing, rarely observed rows look more and more like an even split; that protects against zeros but waters down real patterns. Something like this is called regularization: deliberately making an estimate more cautious so it doesn't rely too much on a few observations.

Smoothing as a formula

The extra count per cell is called alpha (α\alpha):

P(j∣i)=Cij+α∑kCik+αV,α>0.P(j\mid i)=\frac{C_{ij}+\alpha}{\sum_k C_{ik}+\alpha V},\qquad \alpha>0.

In the denominator alpha is added V times, once for each possible next token. Our example above was α=1\alpha=1.

In Python

All the counting fits into a few lines:

python
import torch
ids = torch.tensor([0, 1, 2, 2, 3])
V = 4
counts = torch.zeros(V, V)
for a, b in zip(ids[:-1], ids[1:]):
    counts[a, b] += 1
prob = (counts + 1) / (counts + 1).sum(-1, keepdim=True)

The browser lab does exactly this with your own text. No pretrained model, no AI service in the background, just your counts.

Generating text: hopping from character to character

Pick a start character. Randomly draw the next one from its row (frequent successors get drawn more often). Use that as the new previous token, repeat. The result often sounds like language that went through a meat grinder: small pieces look real, the whole makes no sense. “hallo” can show up, but so can “hallallall…”.

The problem is easy to name: the model has a memory of exactly one token. “The capital of France is” and “The capital of Italy is” end the same way, so the bigram model predicts the same thing in both cases. It forgot the country long ago.

Such a random process, where the next step depends only on the current state, is called a Markov chain, by the way.

Why such a dumb model?

A bigram model is a baseline: a simple comparison model that every more complicated model has to measure up against. If your fancy transformer ends up doing worse than the tally sheet, something is wrong: in the code, the data or the training. Or your dataset is so small that there is nothing better to learn.

The comparison has to be fair: same test texts, same tokenizer, sensible smoothing. A baseline is not a straw man you make bad on purpose.

What is still missing

The count table needs no training with gradients. But instead of the counts you could use trainable numbers, turn them into probabilities with softmax and improve them with gradient descent. Then we would be at the neural model.

Two tools are still missing for that: embeddings, learned lists of numbers for every token, and an error measure for “did the model hit the right next token?”. The next two chapters deliver both.

And why not just one giant table? A table for all pairs would have 2.5 billion cells with 50,000 tokens, and could still only look back one token. We need a structure that shares knowledge between similar cases and looks further back.

Try it yourself

Train on a text with a clear pattern, like “abcabcabc…”. The model should learn a→b, b→c and c→a. Then enter “abd”. If d never appeared, only the smoothing kicks in. Mini tests like this reveal a lot about how your model handles the unknown.

Build it yourself: in step 3 of part VII you program a learnable version of this table with PyTorch.

Key points

  • A bigram model counts which token follows which and turns that into probabilities.
  • Smoothing makes sure the unseen isn't impossible.
  • Its memory is only one token long, which is why we need better models. As a baseline it stays valuable.