Majid Al-RaimiWhy language models predict words

ICS 582Lecture 03Part 01

Why language models predict words

The motivation for language modeling, the applications that rely on next-word probabilities, the two equivalent views of what an LM computes, and the split between count-based and neural models.

Concepts
5
Slides
1-9
Reading
30 min
Understood
0/5 concepts

Why this part matters

Every system you will meet in this course, from spell checkers and speech recognizers to machine translation, phone keyboards and today's large language models, rests on one quantity: the probability of the next token given everything before it. This part pins down exactly what that quantity is before the lecture shows how n-grams estimate it.

The rest of the lecture is about estimation, evaluation and repair, and none of it makes sense until the target is clear. Exams routinely ask you to name an application and explain how a probability over word sequences helps it, and any research project that touches text generation, decoding or scoring uses the vocabulary set up here.

By the end you can

  1. Define a language model as a probability distribution over the next word given a history, and explain why it outputs a distribution rather than a single word.
  2. Explain how an LM helps spelling correction, speech recognition, machine translation, AAC and predictive text, using the candidates-plus-ranking (noisy channel) pattern.
  3. Relate next-word probabilities to whole-sentence probability through the chain rule, and compute the probability of a short sentence from given bigram values.
  4. Contrast count-based and neural language models on estimation, generalization and parameter growth.

Read the roadmap as one story. We want to predict the next word, so we count words in a corpus to estimate probabilities. We measure the result with Perplexity, and we look at what the model has learned by generating text from it. Then the model breaks: any word sequence it never saw gets probability zero. The second half of the lecture is the repair kit, from Smoothing through interpolation, Backoff and absolute discounting to Kneser-Ney, and it closes by connecting perplexity to Entropy.

  1. Motivation: predicting words. What an LM computes and where that number is used. This part.
  2. N-grams. The chain rule and the Markov assumption turn an impossible history into the last few words.
  3. Estimating n-gram probabilities. Counting and dividing: maximum likelihood estimates, and log probabilities to avoid underflow.
  4. Evaluating language models: perplexity. How to tell a better model from a worse one on held-out text without building a whole application.
  5. Sampling from an LM. Generating text by drawing from the distribution, which shows what the model has actually learned.
  6. Generalization and overfitting. Why a model tuned to its training corpus fails on new genres and assigns zero to unseen n-grams.
  7. Smoothing, interpolation and backoff. Moving probability mass to unseen events and mixing in shorter contexts.
  8. Absolute discounting. Subtracting a fixed amount from every seen count, justified by held-out data.
  9. Kneser-Ney intuition. A lower-order distribution built from how many contexts a word completes, not how often it occurs.
  10. Interpolated Kneser-Ney for bigrams. The full computation step by step on a toy corpus.
  11. General Kneser-Ney. The recursion to higher-order n-grams, the standard count-based baseline.
  12. Perplexity and entropy. The information-theoretic meaning of the evaluation metric.

Underneath the twelve stops there is a single question: how do we turn finite counts into a probability for every possible next word, including words never seen after this context? Stops 2 to 4 answer the easy half, for events we have seen. Stops 6 to 11 answer the hard half, for events we have not. The model family that carries all of it is the n-gram language model.

Finish this sentence: The water of Walden Pond is so beautifully ___. You probably thought of blue, green or clear. You did not think of refrigerator or this. You did not produce one word with certainty either. You produced a ranking with a sense of how much more likely some words are than others. That ranking, made numeric, is a language model.

A language model assigns a probability to each possible next word given the words so far, the history. Its output for one history is therefore a whole probability distribution over the vocabulary, and the task of producing it is next-word prediction. Writing the history as w<t, every word before position t:

P(wt∣w<t)for every wt∈V,∑w∈VP(w∣h)=1\begin{gathered} P(w_t \mid w_{<t}) \quad\text{for every } w_t \in V, \\ \sum_{w \in V} P(w \mid h) = 1 \end{gathered}
One history h, one distribution over the whole vocabulary V
Bars for the next word after 'The water of Walden Pond is so beautifully': blue and clear take most of the mass, refrigerator keeps a sliver that is small but not zero. Heights are illustrative, not measured.

The constraint that the probabilities sum to 1 is what makes the numbers comparable. If blue gains probability, something else must lose it. It also explains why the rest of the lecture worries about zeros: a model that spends all its mass on words it has seen has nothing left for refrigerator, even when a strange sentence really does continue that way.

This is not a toy objective. Jurafsky and Martin put it bluntly: large language models are built just by training them to predict words. GPT-3, with 175 billion parameters, is described by its authors as an autoregressive language model, which means exactly this: it computes P(w_t | w<t) one position at a time. A neural language model and an n-gram model answer the same question; they differ only in how they estimate the answer. GPT-3 itself was pretrained with plain next-token prediction, and modern LLMs use this objective or close variants of it; later tuning stages change the objective and shift the probabilities, but the output is still a distribution over the next token.

Recall

What exactly does a language model output for a given history?

A probability for every word or token in the vocabulary given that history: a distribution that sums to 1, not a single word.

Run a dictionary spell checker over Their are two midterms. Every word is in the dictionary, so it passes. The error is a real-word error: the typo produced another valid word, and nothing about any single word reveals it. What reveals it is context. There are is a very common Bigram and Their are is rare, so a model that compares P(There are) with P(Their are) flags the sentence at once. The same holds for Everything has improve, where the fix improved makes the more probable sentence.

Now speech. A recognizer hears something that sounds like I will be back soonish, but the audio is almost identical to I will be bassoon dish. The acoustic evidence cannot separate them. The language model can: back soonish is a far more probable continuation of I will be than bassoon dish.

Two transcriptions of the same audio feed one LM gauge; the LM scores 'be back soonish' as more probable English, the winner is checked and 'be bassoon dish' dims

The pattern: candidates in, ranking out

Both examples share a structure, and it is worth naming because it covers almost every classical application. Some other component proposes candidates: a set of spelling variants, an acoustic model, a translation model, a keyboard decoder. The language model does not know what you meant. It scores how plausible each candidate is as a piece of language, and the system combines that score with the evidence. Brown and colleagues wrote this down for statistical machine translation in 1990 as the noisy channel decoder: given a foreign sentence T, output the English sentence S that maximizes the product below, and they call the first factor the language model probability of S.

S^=arg⁡max⁡S  Pr⁡(S)⏟language model  Pr⁡(T∣S)⏟translation model\hat{S} = \arg\max_{S}\; \underbrace{\Pr(S)}_{\text{language model}}\; \underbrace{\Pr(T \mid S)}_{\text{translation model}}
Brown et al. 1990. In speech recognition the audio takes the place of T.

The split of labour is clean. Pr(T | S) rewards faithfulness to the input. Pr(S) rewards fluency, and it does not care about the input at all, which is why one well trained language model can be reused across speech, translation and spelling. It is also why these are the settings where language models are judged by extrinsic evaluation: a better LM is one that lowers the word error rate or raises the translation score of the whole system.

Prediction on its own

In a second family of applications there is no separate candidate generator. The prefix you have typed is the history, and the system shows the top few entries of P(next | prefix). Search autocomplete turns a quick into brown fox. A translation input box suggests think after what do you. A phone keyboard offers bro, brown and brother while you type The quick bro. All of these are argmax or top-k over the same distribution from the previous concept.

The application with the highest stakes is augmentative and alternative communication (AAC). People who cannot speak or sign may select words from a menu with eye gaze or other small movements. Trnka and colleagues report that AAC users often communicate at under 10 words per minute, against 150 to 200 for speech, and that in a study with simulated AAC users (able-bodied typists slowed by an artificial key delay), advanced word prediction produced 59.9% more words per minute than no prediction. More accurate predictions significantly improve the communication rate, so here a better language model is directly a faster conversation.

ApplicationCandidates come fromWhat the LM decidesExample
Spelling and grammar correctionVariants of the typed words: their, there, they're; improve, improvedWhich variant makes the more probable sentenceTheir are two midterms
Speech recognitionThe acoustic model, which proposes word sequences that match the audioWhich sound-alike transcription is fluent Englishback soonish / bassoon dish
Machine translationThe translation model, which proposes target sentences faithful to the sourceWhich faithful candidate is also well formedPr(S) Pr(T|S)
AACEvery word in the vocabulary, shown as a short menuWhich few words go on the menu, ranked by probabilityEye-gaze word selection
Search autocompleteContinuations of the typed query prefixWhich completions to show, before other ranking signalsa quick → brown fox
Mobile keyboardCompletions of the partial word and the next wordThe top three suggestions, the best in the centerThe quick bro → brown
Where the candidates come from and what the language model decides

Gboard is the best documented production example. Hard and colleagues describe how the keyboard shows three suggestions and the numbers behind them, and they make a useful benchmark for the comparison in the last concept of this part.

Gboard next-word prediction (Hard et al. 2018)

Suggestions shown
3 candidates, highest probability in the center
Baseline model
Katz-smoothed 5-gram, compiled as a finite-state transducer
Baseline size
1.25 million n-grams, 164,000 unigrams
Top-1 recall on server logs
n-gram 13.0%, federated CIFG 16.4%
Top-3 recall on server logs
n-gram 22.1%, federated CIFG 27.0%

Recall

Why can a spell checker that only consults a dictionary not fix 'Their are two midterms'?

Both words are valid, so it is a real-word error. Only the context probability, P(There are) greater than P(Their are), reveals it.

Recall

In the noisy-channel decoders of speech recognition and statistical MT, which factor is the LM and what does it contribute?

The LM is Pr(S), the prior over output sentences. It rewards fluent orderings, while the channel model Pr(T | S) or Pr(audio | S) rewards faithfulness to the input (Brown et al. 1990).

Quick check

A recognizer hears audio that fits both 'recognize speech' and 'wreck a nice beach'. Which component separates them?

Quick check

In the decoder argmax over S of Pr(S) Pr(T|S), what does the factor Pr(S) reward?

Compare all of a sudden I notice three guys standing on the sidewalk with on guys all I of notice sidewalk three a sudden standing the. Same twelve words, and none repeats, so there are 12! = 479,001,600 orderings. A good language model must put the fluent one near the top of all of them. That asks for something new: not a next word, but a probability for a whole sentence.

Twelve scrambled word tiles slide into the fluent order while the sentence-probability meter rises from almost nothing to high

Language models offer two views. View one is the next-word distribution, P(w_t | w<t). View two is the probability of an entire sequence, P(w_1:T). They are not two models. The chain rule of probability turns one into the other exactly:

P(w1:T)=∏t=1TP(wt∣w<t)P(w_{1:T}) = \prod_{t=1}^{T} P(w_t \mid w_{<t})
Sentence probability is the product of next-word probabilities. Part 02 derives it.

Going the other way, a next-word probability is a ratio of two sequence probabilities, P(w_t | w<t) = P(w_1:t) / P(w_1:t-1), so either view gives you the other. That is why slide 8 can call them equivalent. Here is a preview of the computation with the toy corpus Part 03 uses to teach counting.

Worked example

Preview: scoring a sentence with bigrams

  1. The corpus

    Three sentences, each wrapped in sentence boundary tokens: <s> I am Sam </s>, <s> Sam I am </s>, <s> I do not like green eggs and ham </s>.
  2. Read off the bigram probabilities

    A Bigram model conditions on one previous word. From the counts: P(I | <s>) = 2/3, P(am | I) = 2/3, P(Sam | am) = 1/2, P(</s> | Sam) = 1/2. How these come from counts is Part 03.
  3. Multiply along the sentence

    P(<s> I am Sam </s>) = 2/3 × 2/3 × 1/2 × 1/2.
  4. Result

    1/9 ≈ 0.111. The sentence probability is nothing but the next-word probabilities multiplied.

Is the sentence view really enough to recover word order? Brown and colleagues tested exactly the claim on slide 8 with an experiment they called bag translation. They cut sentences into an unordered bag of words, then asked a Trigram language model to choose the ordering with the highest Pr(S).

Worked example

Bag translation (Brown et al. 1990)

  1. Setup

    38 English sentences of fewer than 11 words, each shuffled into a bag.
  2. Decode

    Search over orderings for the one with the highest trigram probability. No grammar, no meaning, only Pr(S).
  3. Result

    24 of 38 (63%) came back in exactly the original order, and 32 (84%) came back with the meaning preserved.

The idea is older still. In 1948 Shannon drew each word of English text from the distribution of words that follow the previous word, a word bigram model done by hand, and got strings such as THE HEAD AND IN FRONTAL ATTACK ON AN ENGLISH WRITER: not meaningful, but recognizably English in its local order. Local next-word statistics already carry a surprising amount of a sentence's shape.

Recall

Write the relation between the two views of an LM.

P(w_1:T) = ∏ P(w_t | w<t) over t = 1 … T, the chain rule. With </s> at the end, the probabilities of sentences of all lengths sum to 1.

Recall

Using the SLP3 toy corpus, what is P(<s> I am Sam </s>) under the bigram model?

2/3 × 2/3 × 1/2 × 1/2 = 1/9 ≈ 0.111.

Quick check

If a model gives P(w_t | w_<t) at every position, what else does it give you directly?

Train a model on the cat sat on the mat, then ask it about the dog sat on the rug. A model that only counts has never seen dog sat, so it has no evidence for it beyond whatever Smoothing hands out. A model that knows dog behaves like cat and rug like mat can carry the probability across. That difference is the whole of slide 9.

Left, a bigram count table whose 'dog sat' cell is zero; right, an embedding space where dog drifts next to cat, and a teal line bridges the empty cell to the point that now borrows cat's evidence

A count-based language model, also called statistical, estimates P(w | h) by maximum likelihood estimation: the relative frequency of the exact n-gram among all n-grams that share its history. It is transparent, fast and cheap. Its weakness is Sparsity. Bengio and colleagues put the problem as the curse of dimensionality: modelling the joint distribution of 10 consecutive words with a vocabulary of 100,000 has potentially 100,000^10 − 1 = 10^50 − 1 free parameters, and a test sequence is likely to differ from every sequence seen in training.

A neural language model maps each word or token to a continuous vector and learns a function from those vectors to the next-word distribution. Bengio and colleagues explain why this generalizes: an unseen sequence gets high probability if it is made of words similar to words in an already-seen sentence. Jurafsky and Martin name the two n-gram problems neural models solve: the number of parameters increases exponentially as the n-gram order increases, and n-grams have no way to generalize from training to test examples unless they use identical words.

AspectCount-based (n-gram)Neural
How P(w | h) is estimatedRelative frequency of the exact n-gram, then smoothedA learned function of continuous word vectors
ParametersOne per observed n-gram; the possible table grows as |V|^nFixed by the network size, shared across all contexts
GeneralizationOnly across identical word sequencesAcross similar words: evidence about cat transfers to dog
Context lengthShort in practice: n of 2 to 5, so 1 to 4 previous wordsLong: hundreds to many thousands of tokens in transformers
Training costOne counting pass; fast and cheapGradient training over many passes; GPU hours to months
InterpretabilityEvery probability traces to a count you can inspectDistributed over millions or billions of weights
ExamplesSRILM, KenLM, modified Kneser-Ney 5-gramsBengio 2003 MLP, RNN and LSTM LMs, transformers such as GPT-3
Gboard, 20185-gram FST, 13.0% top-1 recallCIFG recurrent network, 16.4% top-1 recall
Count-based and neural language models side by side

This lecture is about count-based models only, which is why slide 9 sets them in bold. That is not nostalgia. Around the turn of the century the standard baseline was modified interpolated Kneser-Ney, available in public toolkits such as SRILM and KenLM, and it is still what you compare against when you need a cheap, inspectable model or a strong prior for a small device.

Recall

State two reasons Bengio et al. and SLP3 give for neural LMs beating n-grams.

n-gram parameters grow exponentially with order (10^50 − 1 for 10 words with |V| = 100,000), and n-grams cannot generalize across similar but non-identical words. Neural LMs use continuous word representations.

Quick check

What is the main reason count-based n-gram models generalize worse than neural language models?

Recap

If you remember nothing else

  • A language model assigns a probability to every possible next word given the history: a distribution, not a single guess.
  • Walden Pond: blue or clear are likely continuations, refrigerator is not. A good LM encodes that intuition numerically.
  • LLMs are pretrained with (variants of) next-token prediction, and in practice LMs run over tokens such as BPE pieces, not raw words.
  • In applications, another component proposes candidates and the LM ranks them by fluency, as in Pr(S) Pr(T|S) for MT.
  • Real-word errors like 'Their are' and acoustic ties like 'back soonish' against 'bassoon dish' are solved by context probability, not by a dictionary.
  • Autocomplete, keyboards (3 Gboard suggestions, 5-gram baseline with 1.25 million n-grams) and AAC menus are top-k predictions from P(next | prefix).
  • Two views, one model: P(w_t | w_<t) and P(w_1:T), linked by the chain rule. </s> makes sentence probabilities a proper distribution.
  • Bag translation: a trigram LM alone restored the exact word order of 63% of short sentences.
  • Count-based LMs estimate from exact n-gram counts. Neural LMs use continuous word representations to generalize to unseen but similar sequences.
  • This lecture covers count-based models. Training and test sets, perplexity, sampling and interpolation carry over to neural LMs; count smoothing does not.

Sources