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
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
- 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.
- Explain how an LM helps spelling correction, speech recognition, machine translation, AAC and predictive text, using the candidates-plus-ranking (noisy channel) pattern.
- Relate next-word probabilities to whole-sentence probability through the chain rule, and compute the probability of a short sentence from given bigram values.
- 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.
- Motivation: predicting words. What an LM computes and where that number is used. This part.
- N-grams. The chain rule and the Markov assumption turn an impossible history into the last few words.
- Estimating n-gram probabilities. Counting and dividing: maximum likelihood estimates, and log probabilities to avoid underflow.
- Evaluating language models: perplexity. How to tell a better model from a worse one on held-out text without building a whole application.
- Sampling from an LM. Generating text by drawing from the distribution, which shows what the model has actually learned.
- Generalization and overfitting. Why a model tuned to its training corpus fails on new genres and assigns zero to unseen n-grams.
- Smoothing, interpolation and backoff. Moving probability mass to unseen events and mixing in shorter contexts.
- Absolute discounting. Subtracting a fixed amount from every seen count, justified by held-out data.
- Kneser-Ney intuition. A lower-order distribution built from how many contexts a word completes, not how often it occurs.
- Interpolated Kneser-Ney for bigrams. The full computation step by step on a toy corpus.
- General Kneser-Ney. The recursion to higher-order n-grams, the standard count-based baseline.
- 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:
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?
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.
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.
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.
| Application | Candidates come from | What the LM decides | Example |
|---|---|---|---|
| Spelling and grammar correction | Variants of the typed words: their, there, they're; improve, improved | Which variant makes the more probable sentence | Their are two midterms |
| Speech recognition | The acoustic model, which proposes word sequences that match the audio | Which sound-alike transcription is fluent English | back soonish / bassoon dish |
| Machine translation | The translation model, which proposes target sentences faithful to the source | Which faithful candidate is also well formed | Pr(S) Pr(T|S) |
| AAC | Every word in the vocabulary, shown as a short menu | Which few words go on the menu, ranked by probability | Eye-gaze word selection |
| Search autocomplete | Continuations of the typed query prefix | Which completions to show, before other ranking signals | a quick → brown fox |
| Mobile keyboard | Completions of the partial word and the next word | The top three suggestions, the best in the center | The quick bro → brown |
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'?
Recall
In the noisy-channel decoders of speech recognition and statistical MT, which factor is the LM and what does it contribute?
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.
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:
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
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>.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.Multiply along the sentence
P(<s> I am Sam </s>) = 2/3 × 2/3 × 1/2 × 1/2.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)
Setup
38 English sentences of fewer than 11 words, each shuffled into a bag.Decode
Search over orderings for the one with the highest trigram probability. No grammar, no meaning, only Pr(S).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.
Recall
Using the SLP3 toy corpus, what is P(<s> I am Sam </s>) under the bigram model?
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.
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.
| Aspect | Count-based (n-gram) | Neural |
|---|---|---|
| How P(w | h) is estimated | Relative frequency of the exact n-gram, then smoothed | A learned function of continuous word vectors |
| Parameters | One per observed n-gram; the possible table grows as |V|^n | Fixed by the network size, shared across all contexts |
| Generalization | Only across identical word sequences | Across similar words: evidence about cat transfers to dog |
| Context length | Short in practice: n of 2 to 5, so 1 to 4 previous words | Long: hundreds to many thousands of tokens in transformers |
| Training cost | One counting pass; fast and cheap | Gradient training over many passes; GPU hours to months |
| Interpretability | Every probability traces to a count you can inspect | Distributed over millions or billions of weights |
| Examples | SRILM, KenLM, modified Kneser-Ney 5-grams | Bengio 2003 MLP, RNN and LSTM LMs, transformers such as GPT-3 |
| Gboard, 2018 | 5-gram FST, 13.0% top-1 recall | CIFG recurrent network, 16.4% top-1 recall |
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.
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
- Speech and Language Processing, 3rd edition draft, chapter 3: N-gram Language ModelsBookJurafsky and Martin, Stanford UniversityDraft of August 19, 2026. LM definition, Walden Pond, applications, chain rule, end symbol footnote, historical notes(opens in a new tab)
- A Statistical Approach to Machine TranslationPaperComputational Linguistics 16(2), 1990, Brown et al.Pr(S) Pr(T|S) decoder; bag translation: 24 of 38 exact, 32 of 38 meaning preserved(opens in a new tab)
- A Neural Probabilistic Language ModelPaperJMLR 3, 2003, Bengio, Ducharme, Vincent and JauvinCurse of dimensionality, 10^50 − 1 free parameters, generalization through similar words(opens in a new tab)
- Federated Learning for Mobile Keyboard PredictionPaperGoogle, 2018, Hard et al.Three suggestions; Katz 5-gram baseline with 1.25 million n-grams; top-1 recall 13.0% against 16.4%(opens in a new tab)
- The Effects of Word Prediction on Communication Rate for AACPaperNAACL-HLT 2007 short papers, Trnka, Yarrington, McCaw, McCoy and PenningtonUnder 10 words per minute against 150 to 200 for speech; 59.9% more words per minute with advanced prediction, measured on simulated (pseudo-impaired) users(opens in a new tab)
- Language Models are Few-Shot LearnersPaperNeurIPS 2020, Brown et al.GPT-3, an autoregressive language model with 175 billion parameters(opens in a new tab)
- A Mathematical Theory of CommunicationPaperBell System Technical Journal 27, 1948, ShannonWord-level approximations to English, the ancestor of n-gram generation(opens in a new tab)
- How Google autocomplete predictions workDocsGoogle Search HelpPredictions reflect real searches and word patterns found across the web(opens in a new tab)