Back to Foundation Models Index | Previous: (y-02) Machine Learning Basics | Next: (y-04) Data and Tokens

Mental Model First

  • A language model is a probability distribution over token sequences. The chain rule turns it into next-token prediction without any assumption, so scoring a sentence and generating one are the same operation. Every model in the course, up to today’s chat models, is a better way to estimate .
  • Word frequencies follow Zipf’s law (a few words are very frequent, most are rare) and vocabulary keeps growing with Heaps’ law. Half of all word types appear once, and most longer word combinations in new text were never seen in training. More data shrinks this problem without ever removing it.
  • n-gram models keep only the last tokens and estimate probabilities by counting. Raw counts give every unseen n-gram probability 0, and one zero factor makes a whole sentence impossible. Smoothing moves probability mass to unseen events; Kneser-Ney does this best among count-based methods.
  • Cross-entropy measures how many bits per token the model needs for real text. Perplexity is , the number of equally likely choices the model is still undecided between. Predicting and compressing are the same problem, and perplexities are only comparable when the tokenization is the same.
  • Counts treat “cat” and “dog” as unrelated symbols. Learned vectors (Bengio’s neural LM, word2vec) put words with similar contexts close together, so evidence about one word transfers to the other. RNNs remove the fixed context window but squeeze the whole past into one state vector; attention removes that bottleneck and leads to the Transformer in Lecture 3.

1. Today’s Lecture

This is the first of the Text LM lectures (Steffen Staab). The 90 minutes are split into six units, each ending with a check question:

UnitTimeTopic
110 minShannon’s game: why predict the next letter?
215 minWord distributions: Zipf, Heaps, the long tail
325 minn-gram models: counting with a short memory, smoothing
415 minEvaluation: cross-entropy, perplexity, compression
515 minCounts to vectors: distributional semantics, word2vec
610 minRecurrent models: one vector for the whole past?

After the lecture you should be able to define a language model and factorize it with the chain rule, explain why sparsity cannot be avoided, estimate and smooth n-gram models from add-one to Kneser-Ney, evaluate with cross-entropy and perplexity and relate both to compression, explain how word2vec replaces counts with learned vectors, and name the bottleneck of recurrent models that attention removes.

The diagrams use one color per role for the rest of the course: input tokens, model internals, outputs, the training signal or loss, and human feedback. Shapes and labels always repeat the color, so color never carries meaning alone.

Most numbers in the lecture are the lecturer’s own computations on 18 Project Gutenberg texts (about 2.1 M tokens).

2. Why Predict the Next Token?

Shannon’s Game

Shannon's guessing game: how many guesses do you need for the next letter of each prefix?

Two prefixes:

  1. the lecture hall was full every seat was tak_
  2. the lecture hall was full every s_

The first is almost free to guess, the second is wide open. Shannon (1951) had people guess text letter by letter and counted how many guesses they needed. Prediction is easy where language is redundant and hard where it carries information.

A character 5-gram model trained on 1.9 M words of Gutenberg text, on the same two prefixes.

A character 5-gram model gives e 91.2% after ...seat was tak and spreads its guesses after ...every s over o (19.6%), t, i, a and h (each around 11%). In bits, the first letter costs bits, and the second costs about bits, roughly a choice among five letters.

A Language Model Is a Distribution over Sequences

The chain rule turns any distribution over sequences into a product of next-token predictions.

A language model assigns a probability to every token sequence. Tokens can be letters, words or word pieces; Lecture 2 of the text block decides which. By the chain rule,

For example, .

The chain rule is exact for every distribution, so the modeling choices come later: which part of the history to keep and how to estimate each factor. Generating text means sampling one token at a time from left to right. The difficulty is that the history grows with every token.

A Short History

Seventy years of counting, then learning. The question (what comes next?) stayed the same.

YearStep
1913Markov counts letter pairs in Eugene Onegin
1948Shannon’s n-gram approximations of English
1951Shannon’s guessing game
2003Bengio: neural language model with learned word vectors
2007Brants et al.: “Large language models” trained on 2 trillion tokens
2013word2vec
2014seq2seq and attention
2017Transformer, then GPT and BERT

The 2007 “large language models” were n-gram models. The phrase is older than neural LLMs.

3. Distributions over Words

Most Words Are Rare

Moby Dick: 44% of its distinct words occur exactly once.

Moby Dick has 215,970 word tokens and 17,365 distinct words (types). 44% of the types occur exactly once (hapax legomena), yet together they make up only 3.5% of the tokens. Across all 18 texts, 37% of 43,495 types are hapaxes. Rare words are many and frequent words are few, so most counts in any table of word statistics are 0 or 1.

Zipf’s Law

Rank against frequency on log-log axes is close to a straight line. The fit on ranks 10 to 10,000 has slope -1.22; the flat step at the end is the words seen once.

Zipf's law and the five most frequent words in the Gutenberg selection.

If is the frequency of the word with rank , then

On a log-log plot this is a straight line with slope . The Gutenberg fit gives on ranks 10 to 10,000. The top five words are the (133,602), and (95,442), of (71,269), to (48,057) and a (33,945), and the top 100 words cover 55% of all tokens. The pattern holds across languages and corpora (Zipf 1949; Piantadosi 2014 reviews the evidence).

Heaps’ Law and Sparsity

Vocabulary size against tokens read. The fit V = 44 · N^0.48 is sub-linear: twice the text gives about 39% more words.

Heaps’ law describes how the vocabulary grows with the amount of text :

For the Gutenberg selection, and . Doubling the text multiplies the vocabulary by . Growth slows down but never stops.

Share of test units never seen in training: 0.9% of words, 19% of bigrams, 54% of trigrams and 76% of 4-grams.

Train on 90% of the sentences (1,901,157 tokens) and test on the other 10%. Only 0.9% of the test words are new, but 19% of the test bigrams, 54% of the trigrams and 76% of the 4-grams never occurred in training. Counting assigns all of these probability 0 unless the model is smoothed.

Sparsity is a property of language statistics. More data brings more new words and many more new word combinations, so no corpus is ever large enough for pure counting.

Is Zipf’s Law About Language at All?

Random typing also produces a Zipf-like curve (Miller 1957; Li 1992).

What Zipf’s law tells us: there are few frequent words and a huge tail of rare ones, any finite corpus misses most possible events, and models therefore have to share statistical strength across words.

What it does not tell us: a monkey hitting letter keys and the space bar at random produces a similar curve, so the law says nothing about meaning. Why language has this shape is still debated.

4. n-gram Models and Smoothing

The Markov Assumption

A trigram model predicts "mat" from the two previous tokens only.

An n-gram model keeps only the last tokens of the history:

is a unigram model (no context), a bigram model and a trigram model. An n-gram model is a Markov chain of order over tokens.

Maximum-Likelihood Estimation: Just Count

Bigram MLE on a three-sentence toy corpus. Every unseen bigram gets probability 0.

The maximum-likelihood estimate of a bigram probability is the relative frequency:

Toy corpus:

<s> the cat sat </s>
<s> the cat ran </s>
<s> a dog sat </s>
BigramCount
cat | the22/2 = 1
sat | cat11/2
sat | dog11/1 = 1
dog | the00

“the dog sat” gets probability 0 because “dog | the” was never seen, even though both words are in the corpus.

Which Sample Came from Which n?

Four samples from models trained on three Austen novels (363,331 tokens). Match them to n = 1, 2, 3 and 5.

Longer context reads better until the model only copies. At n = 5 the whole sample is Austen verbatim.

SamplenLongest run copied from the training text
B12 words
D24 words
A36 words
C522 words, the whole sample

Larger makes the text more fluent, but the counts get sparser, and at the model recites Austen. The trade-off between memorization and generalization comes back with every larger model in the course.

Add-One (Laplace) Smoothing

A sentence probability is a product, so a single unseen bigram makes the whole sentence impossible. Smoothing fixes that by reserving probability for unseen events.

Add-k smoothing pretends every bigram was seen k more times. With k = 1 it is so crude that the bigram model gets worse than the unigram model.

With this is Laplace smoothing. In the Gutenberg corpus . After “the” there are 10,306 seen successors and 15,729 unseen ones, and add-one hands the unseen ones 11% of the probability mass after “the” and far more after rarer words. The add-one bigram model reaches a test perplexity of 1,401, worse than the unigram model’s 699.

Back-Off and Interpolation

When the long context is unreliable, mix in shorter ones. With 2 trillion tokens even "stupid back-off" works.

Linear interpolation mixes all orders:

with , tuned on held-out data.

  • Back-off uses the trigram if it was seen, otherwise falls back to the bigram, and so on.
  • Interpolation always mixes all orders.
  • “Stupid back-off” (Brants et al. 2007) skips normalization entirely. With 2 trillion tokens it is good enough, so the amount of data changes how much care the smoothing needs.

Kneser-Ney Smoothing

Kneser-Ney asks how many different contexts a word completes. "Francisco" is frequent but only follows "San".

Interpolated Kneser-Ney for bigrams:

  • Subtract a fixed discount from every seen count.
  • Give the freed mass to the continuation distribution , which favors words that follow many different words. “Francisco” has a high count but a low continuation probability, because almost all its occurrences follow “San”.
  • makes the distribution sum to one. Since each of the seen successors gave up , that weight is .

Chen and Goodman (1999) found Kneser-Ney to be the best count-based smoothing method.

Smoothing Matters

Test perplexity on held-out Gutenberg text, same data and vocabulary (|V| = 26,035 including the unknown token). Lower is better.

ModelTest perplexity
Unigram, add-one699
Bigram, add-one1,401
Bigram, add-k (k = 0.003)385
Bigram, interpolated (λ = 0.7)270
Bigram, Kneser-Ney239
Trigram, Kneser-Ney190

Add-one hurts, discounting helps most, and longer context only pays off once the smoothing is right. Even smoothed, an n-gram model cannot tell that “dog” behaves like “cat”, because counts treat words as unrelated symbols. Unit 5 fixes this with vectors.

5. Evaluation: Cross-Entropy, Perplexity, Compression

Intrinsic or Extrinsic?

Intrinsic evaluation measures the model's probabilities; extrinsic evaluation measures task performance.

IntrinsicExtrinsic
Probability of held-out textPerformance on a task: translation, QA, coding
Cross-entropy, perplexity, bits per byteBenchmarks (Lecture 4 onward)
Cheap, exact, used during trainingCloser to what users care about

Lower perplexity usually means better task results, but not always.

Cross-Entropy: Average Surprise

Cross-entropy is the average number of bits per token the model needs for the test text.

For a test text and a model :

  • It estimates the cross-entropy between the true distribution and the model .
  • It can never go below the entropy of the language: .
  • It is the training loss of every LLM in this course (with the natural log instead of ).

Perplexity: The Effective Number of Choices

Perplexity is exponentiated cross-entropy. A fair die has perplexity 6.

A fair die with per throw has , and a uniform model over words has . Perplexity is therefore a branching factor. The trigram Kneser-Ney model’s perplexity of 190 equals 7.6 bits per word: the model behaves as if it were choosing among about 190 equally likely words.

How Predictable Is English?

Shannon's human guessing experiment puts English at roughly one bit per letter.

In Shannon’s experiment (1951, Prediction and Entropy of Printed English), the number of guesses people needed bounds the entropy of English. With 100 letters of context the estimate lies between 0.6 and 1.3 bits per letter, so English is highly redundant: a letter carries about one bit, against the bits of 26 letters and a space chosen uniformly. The character 5-gram model from Unit 1 needs 1.92 bits per character, because humans use far more context.

Prediction Is Compression

A language model plus an arithmetic coder turns text into a bit string of about N times the cross-entropy bits.

Feed the model’s next-token distribution into an arithmetic coder and the text compresses to about bits, which is times the cross-entropy. Better prediction means a shorter code, so minimizing the LM loss is minimizing code length. Decoding needs the same model, which acts as the codebook. Shannon (1948) already treated prediction and compression as the same problem.

Delétang et al. (ICLR 2024): Chinchilla 70B, trained mainly on text, compresses image patches and audio better than PNG and FLAC.

DataClassic codecChinchilla 70B
ImageNet patchesPNG: 58.5%43.4%
LibriSpeech audioFLAC: 30.3%16.4%

Numbers are the size after compression as a share of the raw size (lower is better). The caveat: if you count the 70 B parameters as part of the compressed output, the model compresses small data poorly.

Perplexity Depends on the Tokenization

A character model with perplexity 3.8 is worse per character than a word model with perplexity 190.

ModelUnitPerplexityBits per unitBits per character
Word trigram (KN)word1907.571.51
Character 5-gramcharacter3.781.921.92

Perplexity 3.8 looks far better than 190, but it is worse per character. To compare, normalize by a unit both models share:

Perplexity is a per-token quantity, and tokens are not a fixed unit. Models with different tokenizers have incomparable perplexities until you convert to bits per character or per byte.

6. From Counts to Vectors

You Shall Know a Word by the Company It Keeps

Firth (1957) summed up the distributional hypothesis (Harris 1954) in that sentence: words that occur in similar contexts have similar meanings. A model that knows “cat” and “dog” share contexts can transfer what it learns about one to the other.

Context Counts Become Vectors

Each row of a word-context count matrix is a vector. Similar rows mean similar words.

drinkpourdrivepark
coffee8500
tea7600
car0096
bus0075
  • Similarity is the cosine of two rows: .
  • Reweighting with pointwise mutual information (PMI) discounts contexts that are frequent everywhere.
  • Latent semantic analysis (LSA, Deerwester et al. 1990) applies a truncated SVD to get dense, low-dimensional vectors.

None of this needs labels: the text supplies the contexts.

Concept Hierarchies from Text

Cimiano, Hotho and Staab (JAIR 2005): a noun-verb formal context becomes a concept lattice.

Earlier work from the lecturer’s group used formal concept analysis (FCA). The formal context records which verbs a noun is the object of: a hotel can be booked; an apartment booked and rented; a car booked, rented and driven; a bike booked, rented, driven and ridden; an excursion or a trip booked and joined. A formal concept is a set of nouns that share the same verbs, and the subset order between concepts gives the hierarchy: bookable contains rentable and joinable, rentable contains driveable, and driveable contains rideable.

On tourism and finance corpora, FCA beats agglomerative and divisive clustering against hand-built taxonomies.

MethodTourismFinance
FCA43.8%41.0%
Single linkage38.6%32.2%
Complete linkage36.9%33.4%
Bi-Section-KMeans36.4%32.8%

The scores are F′ against a reference taxonomy with conditional probability weighting. The corpora had 118 M and 185 M tokens, and a parser supplied the contexts (verb-object, verb-subject, verb-PP). Smoothing by clustering similar nouns did not help. Counting contexts already yields structure, and sparsity limits it. Lecture 4 comes back to this: a masked language model learns such a formal context implicitly.

A Neural LM Shares Strength across Words

Bengio et al. (2003) learn the word vectors and the next-word predictor together.

  • Each word has a learned vector .
  • After seeing “the cat sat”, the model also gives “the dog sat” a reasonable probability, provided “cat” and “dog” have similar vectors.
  • The number of parameters grows linearly in , where an n-gram table grows exponentially in .

word2vec: Predict the Neighbors

Skip-gram with negative sampling pulls real word-context pairs together and pushes random pairs apart.

For a word , a context word in its window and random words , skip-gram with negative sampling maximizes

  • Real pairs get a high score and random pairs a low one, so training never needs a softmax over the whole vocabulary.
  • CBOW predicts the word from its context; skip-gram predicts the context from the word.
  • Levy and Goldberg (2014) showed that skip-gram implicitly factorizes a shifted PMI matrix, which makes it counting done by gradient descent.

Nearest neighbors and analogies in the 300-dimensional GoogleNews word2vec vectors.

The lecture queried the GoogleNews vectors live (gensim 4.4.0, 22 Oct 2026):

QueryNearest results
StuttgartDortmund, Wolfsburg, Bremen
PorscheAudi, BMW, Maserati
king − man + womanqueen, monarch, princess
Paris − France + GermanyBerlin, Frankfurt, Dusseldorf
walking − walk + swimswimming, swam, swims

Geography, brands, gender and morphology all come from co-occurrence alone. With these vectors, while .

A PCA projection of countries and capitals: the country-to-capital offsets point in similar directions.

A 2-D PCA projection (after Mikolov et al. 2013, Fig. 2) shows country-capital pairs (China and Beijing, France and Paris, Germany and Berlin) with roughly parallel offsets. The two components explain only 32% of the variance, so the picture is an illustration and does not prove the structure.

Vectors Also Learn Our Stereotypes

The same analogy arithmetic on professions returns stereotyped answers, partly because the standard test excludes the input words.

  • computer_programmer − man + woman gives homemaker, housewife, graphic_designer.
  • doctor − man + woman gives gynecologist, nurse, doctors.

Embeddings reflect the statistics of their training text, including its biases (Bolukbasi et al. 2016). The standard analogy test also excludes the input words from the answers. Allow them, and the nearest word to doctor − man + woman is “doctor” itself (Nissim et al. 2020). Excluding the inputs forces a different answer and exaggerates the effect.

7. Recurrent Models and Their Bottleneck

Recurrent LMs: Unbounded History

An RNN language model updates one hidden state per token and predicts the next token from it.

There is no Markov window, and the same weights are used at every step (Elman 1990; Mikolov et al. 2010). Gradients through many steps vanish or explode, which LSTMs (Hochreiter and Schmidhuber 1997) address with gated memory.

The Bottleneck: One Vector per Sentence

In 2014 encoder-decoder translation, the decoder sees "Das Haus ist klein" only through one vector c.

In encoder-decoder translation (Cho et al. 2014; Sutskever et al. 2014), the encoder reads “Das Haus ist klein” into states and hands the decoder a single vector . The decoder produces “the house is small” from that vector alone, and quality drops on long sentences. Cho et al. reported that performance degrades rapidly as sentence length increases.

Attention: Look Back at Every Encoder State

Bahdanau, Cho and Bengio (ICLR 2015). Line width is the attention weight; for "small" the decoder looks mostly at "klein".

At each decoding step, attention builds a fresh context vector from all encoder states:

When the decoder produces “small”, most of the weight goes to “klein”. There is no single bottleneck vector any more. In 2017 the Transformer drops the recurrence as well, and Lecture 3 of the text block starts there.

8. Recap

Six ideas to keep from the lecture.

  1. A language model is a distribution over sequences, which the chain rule turns into next-token prediction.
  2. Zipf and Heaps describe a long tail, so sparsity is unavoidable.
  3. n-gram models combine a Markov window with counts, and Kneser-Ney handles the unseen best.
  4. Cross-entropy equals code length, and perplexities are only comparable with the same tokenizer.
  5. Similar contexts give similar vectors, and the vectors pick up the biases of the text.
  6. RNNs have unbounded history but squeeze it through one vector; attention removes that bottleneck.

The next lecture covers data and tokens: what models learn from.

Self-Check

  1. Which statement about the chain rule is true? (A) It assumes each word depends only on the previous word. (B) It holds for every distribution over sequences. (C) It only holds if the words are independent.
  1. Moby Dick has 17,365 distinct words. Roughly what fraction of them occurs exactly once?
  1. You double your training corpus. With Heaps’ exponent , how much larger does the vocabulary get?
  1. In the toy corpus (<s> the cat sat </s>, <s> the cat ran </s>, <s> a dog sat </s>), what is the MLE bigram probability of “the cat sat” (with sentence boundaries) and of “the dog sat”?
  1. Your trigram model assigns probability 0 to a test sentence. What is the most likely reason?
  1. Why does the add-one bigram model (perplexity 1,401) do worse than the add-one unigram model (699)?
  1. Why does Kneser-Ney use continuation counts instead of plain unigram counts for the lower-order distribution?
  1. What is the perplexity of a uniform model over a vocabulary of words, and how many bits per word is a perplexity of 190?
  1. Same test set. Model 1 has perplexity 12 with tokenizer X, model 2 has perplexity 18 with tokenizer Y. Which model is better?
  1. Why is minimizing cross-entropy the same as compressing?
  1. Why can a neural LM give “the dog sat” a reasonable probability when only “the cat sat” was in training?
  1. An RNN reads a 1,000-token document. Which statement is true? (A) It can condition on all 1,000 tokens, but only through one fixed-size state. (B) It only sees the last tokens, like an n-gram model. (C) It processes all tokens in parallel.

Back to Foundation Models Index | Previous: (y-02) Machine Learning Basics | Next: (y-04) Data and Tokens